import
java.awt.GridLayout;
import
java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
import
java.io.BufferedWriter;
import
java.io.FileWriter;
import
java.io.FileNotFoundException;
import
java.io.IOException;
import
java.io.File;
import
javax.swing.JLabel;
import
javax.swing.JDialog;
import
javax.swing.JFrame;
import
javax.swing.JPanel;
import
javax.swing.JButton;
import
javax.swing.JTextField;
import
javax.swing.SwingUtilities;
public
class
OpenningForm {
public
static
void
main(String[] args) {
SwingUtilities.invokeLater(
new
Runnable() {
@Override
public
void
run() {
BasicForm frame =
new
BasicForm(
"Basic Frame"
);
frame.createGUI();
}
});
}
}
class
BasicForm
extends
JFrame {
public
BasicForm(String name) {
setTitle(name);
BasicPanel panel =
new
BasicPanel();
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(
300
,
300
);
}
public
void
createGUI() {
setVisible(
true
);
}
}
class
BasicPanel
extends
JPanel {
public
BasicPanel() {
JButton button =
new
JButton(
"New..."
);
button.addActionListener(
new
ActionListener() {
public
void
actionPerformed(ActionEvent arg0) {
InputDialog inputForm =
new
InputDialog();
inputForm.setVisible(
true
);
}
});
add(button);
}
}
class
InputDialog
extends
JDialog {
public
InputDialog() {
InputPanel panel =
new
InputPanel();
setTitle(
"Input Dialog"
);
add(panel);
setSize(
200
,
150
);
setLocationRelativeTo(
null
);
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setVisible(
false
);
}
}
class
InputPanel
extends
JPanel {
JTextField firstNameField;
JTextField secondNameField;
JTextField phoneNumber;
public
InputPanel() {
GridLayout gridLayout =
new
GridLayout(
4
,
2
);
setLayout(gridLayout);
firstNameField =
new
JTextField(
20
);
secondNameField =
new
JTextField(
20
);
phoneNumber =
new
JTextField(
15
);
JLabel firstNameLabel =
new
JLabel(
"First name: "
);
JLabel secondNameLabel =
new
JLabel(
"Second name: "
);
JLabel phoneNumberLabel =
new
JLabel(
"Phone number: "
);
JButton saveToFileButton =
new
JButton(
"Save to file"
);
saveToFileButton.addActionListener(
new
ActionListener() {
@Override
public
void
actionPerformed(ActionEvent e) {
BufferedWriter writer;
try
{
//File file = new File("contacts.txt");
writer =
new
BufferedWriter(
new
FileWriter(
"contacts.txt"
,
true
));
writer.write(firstNameField.getText() +
"\t"
+ secondNameField.getText() +
"\t"
+ phoneNumber.getText());
writer.newLine();
writer.close();
}
catch
(FileNotFoundException ex) {
ex.printStackTrace();
}
catch
(IOException ex) {
ex.printStackTrace();
}
}
});
add(firstNameLabel);
add(firstNameField);
add(secondNameLabel);
add(secondNameField);
add(phoneNumberLabel);
add(phoneNumber);
add(saveToFileButton);
}
}
-----
from: http://www.java-forums.org/awt-swing/28591-create-form-input-some-data-save-file.html
No comments:
Post a Comment