JAVA中将JTextField里面的字符串保存到记事本里面然后再另一窗口读出来
2015-05-02
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class TestFrame extends JFrame {
private JLabel reason;
private JTextField field;
private JButton ok, exit;
public TestFrame() {
super("学生需填信息");
reason = new JLabel("学生请假理由:");
field = new JTextField(20);
ok = new JButton("提交");
ok.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveReason();
showReason();
}
});
exit = new JButton("退出");
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(reason);
this.add(field);
this.add(ok);
this.add(exit);
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
private void saveReason() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(
"请假原因.txt")));
writer.append(field.getText().trim());
writer.close();
} catch (Exception exp) {
}
}
private void showReason() {
JFrame frame = new JFrame("执行窗口");
JLabel reason = new JLabel("");
frame.add(reason);
frame.setSize(300, 100);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
reason.setText(field.getText().trim());
frame.setVisible(true);
}
public static void main(String[] args) {
new TestFrame();
}
}