1 import javax.swing.*;
2 import java.io.*;
3 import java.awt.*;
4 import java.awt.event.*;
5
6
7 public class Ftest extends JFrame {
8 private static final long serialVersionUID = 1L;
9 private JPanel jContentPane = null;
10 private JTextArea jTextArea = null;
11 private JPanel controlPanel = null;
12 private JButton openButton = null;
13 private JButton closeButton = null;
14
15 private JTextArea getJTextArea() {
16 if (jTextArea == null) {
17 jTextArea = new JTextArea();
18 }
19 return jTextArea;
20 }
21
22 private JPanel getControlPanel() {
23 if (controlPanel == null) {
24 FlowLayout flowLayout = new FlowLayout();
25 flowLayout.setVgap(1);
26 controlPanel = new JPanel();
27 controlPanel.setLayout(flowLayout);
28 controlPanel.add(getOpenButton(), null);
29 controlPanel.add(getCloseButton(), null);
30 }
31 return controlPanel;
32 }
33
34
35 private JButton getOpenButton() {
36 if(openButton == null) {
37 openButton = new JButton();
38 openButton.setText("写入文件");
39 openButton.addActionListener(new ActionListener() {
40 public void actionPerformed(ActionEvent e) {
41 File file = new File("word.txt");
42 try {
43 FileWriter out = new FileWriter(file);
44 String s = jTextArea.getText();
45 out.write(s);
46 out.close();
47 }catch (Exception e1) {
48 e1.printStackTrace();
49 }
50 }
51 });
52 }
53 return openButton;
54 }
55 private JButton getCloseButton() {
56 if(closeButton == null) {
57 closeButton = new JButton();
58 closeButton.setText("读取文件");
59 closeButton.addActionListener(new ActionListener() {
60 public void actionPerformed(ActionEvent e) {
61
62 File file = new File("word.txt");
63 try {
64 FileReader in = new FileReader(file);
65 char byt[] = new char[1024];
66 int len = in.read(byt);
67 jTextArea.setText(new String(byt, 0, len));
68 in.close();
69 }
70 catch (Exception e1) {
71 e1.printStackTrace();
72 }
73 }
74 });
75 }
76 return closeButton;
77 }
78
79 public Ftest() {
80 super();
81 initialize();
82 }
83 public void initialize() {
84 this.setSize(300, 200);
85 this.setContentPane(getJContentPane());
86 this.setTitle("JFrame");
87 }
88 private JPanel getJContentPane() {
89 if(jContentPane == null) {
90 jContentPane = new JPanel();
91 jContentPane.setLayout(new BorderLayout());
92 jContentPane.add(getJTextArea(), BorderLayout.CENTER);
93 jContentPane.add(getControlPanel(), BorderLayout.SOUTH);
94 }
95 return jContentPane;
96 }
97 public static void main(String[] args) {
98 Ftest thisClass = new Ftest();
99 thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
100 thisClass.setVisible(true);
101 }
102 }