发布时间:2019-07-31 19:00:23
本实例创建Swing窗体,单击窗体中的“写入文件”按钮实现写入功能,单击“读取文件”按钮实现从文件中读取信息显示在文本框中
package Zhang15;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import java.awt.event.*;
import java.io.*;
import java.awt.*;
public class Ftest extends JFrame{
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
private JTextArea jTextArea = null;
private JPanel controlPanel=null;
private JButton openButton = null;
private JButton closeButton = null;
public void CreateJFrame(String title) {
JFrame jf = new JFrame(title);
Container container = jf.getContentPane();
JLabel jl = new JLabel("这是一个JFrame窗体");
jl.setHorizontalAlignment(SwingConstants.CENTER);
container.add(jl);
container.setBackground(Color.white);
jf.setVisible(true);
jf.setSize(200, 150);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
private JButton getOpenButton() {
if(openButton==null) {
openButton = new JButton();
openButton.setText("写入文件");
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File file = new File("word.txt");
try {
FileWriter out = new FileWriter(file);
String s = jTextArea.getText();
out.write(s);
out.close();
}catch(Exception e1) {
e1.printStackTrace();
}
}
});
}
return openButton;
}
private JButton getClosrButton() {
if(closeButton==null) {
closeButton = new JButton();
closeButton.setText("读取文件");
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File file = new File("word.txt");
try {
FileReader in = new FileReader(file);
char byt[]=new char[1024];
int len = in.read(byt);
jTextArea.setText(new String(byt,0,len));
in.close();
}catch(Exception e1) {
e1.printStackTrace();
}
}
});
}
return closeButton;
}
public Ftest() {
super();
initialize();
}
private void initialize() {
this.setSize(300, 200);
this.setContentPane(getContentPane());
this.setTitle("JFrame");
}
private JPanel getJContentPane() {
if(jContentPane==null) {
jContentPane = new JPanel();
jContentPane.setLayout(new BorderLayout());
jContentPane.add(getClosrButton(),Borderalayout.CENTER);
jContentPane.add(JFrame(),BorderLayout.SOUTH);
}
return jContentPane;
}
public static void main(String[] args) {
Ftest thisClass new Ftest();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
}
为什么是空白