一个简单的不能再简单的记事本,仅拥有打开,保存的功能,不是很完美。。。。。
package com.test;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
public class Txt extends JFrame implements ActionListener{
JTextArea jta = null;
JMenuBar jmb = null;
JMenu jm= null;
JMenuItem jmi1 = null;
JMenuItem jmi2 = null;
public Txt(){
jta = new JTextArea();
jmb = new JMenuBar();
jm = new JMenu("文件");
jmi1 = new JMenuItem("打开");
jmi1.addActionListener(this);
jmi1.setActionCommand("open");
jmi2 = new JMenuItem("保存");
jmi2.addActionListener(this);
jmi2.setActionCommand("save");
this.setJMenuBar(jmb);//在最上面放入MenuBar组件
this.add(jta);
jmb.add(jm);
jm.add(jmi1);
jm.add(jmi2);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300,400);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
//判断与哪个选项被选中
if(e.getActionCommand().equals("open")){
//JFileChooser组件 *………………*
JFileChooser jfc = new JFileChooser();
//设置名字
jfc.setDialogTitle("请选择文件");
//ShowOpenDialog打开某文件的对话框 null代表默认位置
//ShowSaveDialog存储某文件的对话框
jfc.showOpenDialog(null);
jfc.setVisible(true);
//得到要打开文件的路径
String FilePath = jfc.getSelectedFile().getAbsolutePath();
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(FilePath);
br = new BufferedReader(fr);
String s = "";
String all = "";
while((s=br.readLine())!=null){
all+=s+"\r\n";
}
jta.setText(all);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally{
try {
br.close();
fr.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
else if(e.getActionCommand().equals("save")){
JFileChooser jfc1 = new JFileChooser();
jfc1.setDialogTitle("另存为");
jfc1.showSaveDialog(null);
jfc1.setVisible(true);
String path = jfc1.getSelectedFile().getAbsolutePath();
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(path);
bw = new BufferedWriter(fw);
bw.write(this.jta.getText());
} catch (IOException e1) {
e1.printStackTrace();
}finally{
try {
bw.close();
fw.close();
} catch (IOException e1) {
}
}
}
}
public static void main(String[] args) {
new Txt();
}
}