【发布时间】:2017-11-17 13:54:15
【问题描述】:
我有一个项目想从 jframe 获取输入。在代码运行时,我只需要一次输入 3 个人员数据,并将该数据写入文件名 person.txt。这些数据具有名称昵称年龄,当我编译我的代码时,它不起作用,我只写一个person.txt 文件中的数据。请帮帮我?我无法在我的项目中获得这些。我该怎么办 ?
public class JavaGui {
public String data = "";
JFrame f;
JLabel l1, l2, l3;
JTextField tf1, tf2, tf3;
JButton b;
JavaGui() {
FileWriter fw = null;
try {
fw = new FileWriter("person.txt");
} catch (IOException ex) {
Logger.getLogger(JavaGui.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter pw = new PrintWriter(fw);
f = new JFrame("Java GUI");
l1 = new JLabel("Name");
l1.setBounds(20, 50, 80, 30);
tf1 = new JTextField();
tf1.setBounds(100, 50, 200, 30);
l2 = new JLabel("Nickname");
l2.setBounds(20, 100, 80, 30);
tf2 = new JTextField();
tf2.setBounds(100, 100, 200, 30);
l3 = new JLabel("Age");
l3.setBounds(20, 150, 80, 30);
tf3 = new JTextField();
tf3.setBounds(100, 150, 200, 30);
b = new JButton("Save");
b.setBounds(100, 200, 70, 30);
f.add(l1);
f.add(tf1);
f.add(l2);
f.add(tf2);
f.add(l3);
f.add(tf3);
f.add(b);
f.setSize(350, 350);
f.setLayout(null);
f.setLocationRelativeTo(null);
f.setResizable(false);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < 3; i++) {
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = "";
String nickname = "";
String ageS = "";
int age = 0;
try {
name = "Name : " + tf1.getText();
nickname = "Nickname : " + tf2.getText();
age = Integer.parseInt(tf3.getText());
if (age > 0 && age < 100) {
ageS = "Age : " + age;
} else {
JOptionPane.showMessageDialog(null, "Please Enter Age field by Positive number Or Less than 100");
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Please enter Age field by number type");
}
data += name + " " + nickname + " " + ageS;
pw.println(data);
pw.close();
}
});
}
}
public static void main(String[] args) {
new JavaGui();
}
}
【问题讨论】:
-
我得到了这样的信息
Name : MyName Nickname : MyNickname Age : 14它似乎按我的预期工作。话虽如此,将pw.println(data); pw.close();更改为pw.println(data); pw.flush(); pw.close();是最安全的。一般建议: 1) Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同的语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 .. -
.. white space 的布局填充和边框。 2) 请参阅Detection/fix for the hanging close bracket of a code block 了解我无法再费心解决的问题。
-
先生,我想在这段代码中添加多个人的数据。请帮帮我?
-
试试 FileWriter 而不是 PrintWritter
标签: java swing file-io io printwriter