需求:用swing编写一个简易的记事本界面
用IO流完成保存文件和读取文件的操作
package Chapter06;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
/**
* 需求:实现简易记事本读取文件保存文件的简单操作
* @author:mg
*/
public class Notepad extends JFrame implements ActionListener {
//创建组件
JMenu jm1;
JMenuBar jmb1;
JTextArea jta;
JMenuItem jmi1;
JMenuItem jmi2;
//构造方法实现界面生成
public Notepad(){
//创建jta
jta = new JTextArea();
jmb1 = new JMenuBar();
this.add(jta);
jm1 = new JMenu("文件");
this.setJMenuBar(jmb1);
jmb1.add(jm1);
jmi1 = new JMenuItem("打开文件");
jmi1.setActionCommand("open");
jmi1.addActionListener(this);
jmi2 = new JMenuItem("保存文件");
jmi2.setActionCommand("save");
jmi2.addActionListener(this);
jm1.add(jmi1);
jm1.add(jmi2);
this.setTitle("记事本");
this.setSize(600,400);
this.setLocation(400,300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//本类进行事件处理
@Override
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("save")){
String filename = "D:\\IDEA代码\\Home_Work\\src\\Chapter06\\a.txt";
FileWriter fw = null;
BufferedWriter bw = null;
try{
fw = new FileWriter(filename);
bw = new BufferedWriter(fw);
String str = this.jta.getText();
bw.write(this.jta.getText());
System.out.println("写入文件成功!");
}catch(Exception e1){
e1.printStackTrace();
}finally {
try{
bw.close();
fw.close();
}catch (IOException e2){
e2.printStackTrace();
}
}
}else if(e.getActionCommand().equals("open")){
String filename = "D:\\IDEA代码\\Home_Work\\src\\Chapter06\\a.txt";
FileReader fr = null;
BufferedReader br = null;
try{
fr = new FileReader(filename);
br = new BufferedReader(fr);
String line = null;
String add = "";
while((line = br.readLine())!=null){
add += line + "\n";
}
this.jta.setText(add);
System.out.println("读取文件成功!");
}catch (IOException e1){
e1.printStackTrace();
}finally {
try{
br.close();
fr.close();
}catch(IOException e2){
e2.printStackTrace();
}
}
}
}
}
package Chapter06;
//测试类
public class Test {
public static void main(String[] args) {
Notepad np = new Notepad();
}
}
代码敲的不容易,给个三连再走吧!