只实现了打开和保存的功能,其他功能参考这两个功能即可。
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class L8_9JiShiBen extends JFrame implements ActionListener{
JMenuBar cd;
JMenu cd1,cd2;
JMenuItem cdx1,cdx2;
JTextArea wby;
private int image;
private Object dk;
public static void main(String[] args) {
L8_9JiShiBen ln=new L8_9JiShiBen();
}
public L8_9JiShiBen() {
cd=new JMenuBar();
cd1=new JMenu("文件(F)");
cd1.setMnemonic('F');
cd2=new JMenu("编辑(E)");
cd2.setMnemonic('E');
cdx1=new JMenuItem("打开",new ImageIcon("image/dk.jpg"));
cdx1.addActionListener(this);
cdx1.setActionCommand("open");
cdx2=new JMenuItem("保存",new ImageIcon("image/bc.jpg"));
cdx2.addActionListener(this);
cdx2.setActionCommand("save");
wby=new JTextArea();
cd1.add(cdx1);
cd1.add(cdx2);
cd.add(cd1);
cd.add(cd2);
this.setJMenuBar(cd);
this.add(wby);
ImageIcon tp1=new ImageIcon("image/jsb.jpg");
this.setIconImage(tp1.getImage());
this.setTitle("记事本");
this.setSize(800, 900);
this.setLocation(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("open")) {
//System.out.println("打开");
JFileChooser wjxz=new JFileChooser();//当按下open时,弹出来一个窗口
wjxz.setDialogTitle("文件打开");//弹出几个字,让用户知道这是干什么的
wjxz.showOpenDialog(null);
wjxz.setVisible(true);
String wjlj=wjxz.getSelectedFile().getAbsolutePath();//这一行的作用是得到用户选择的全路径
FileReader wjl=null; BufferedReader hcl=null;
try {
wjl=new FileReader(wjlj);
hcl=new BufferedReader(wjl);
String s="",zfc="";
while((s=hcl.readLine())!=null) {
zfc+=(s+"\n");//每读一行转过来就丢了\n符。所以需要加上
}
wby.setText(zfc);//将字符放在文本域中
}catch(Exception aa) {}
finally {
try {
wjl.close();
hcl.close();
}catch(Exception a1) {
}
}
}else if(e.getActionCommand().equals("save")) {
JFileChooser ljxz=new JFileChooser();
ljxz.setDialogTitle("另存为");
ljxz.showSaveDialog(null);
ljxz.setVisible(true);
String bclj=ljxz.getSelectedFile().getAbsolutePath();
try {
PrintStream p1=new PrintStream(bclj);//print流来保存,中英文均可以保存
System.setOut(p1);
System.out.println(this.wby.getText());//保存上面路径中
}catch(Exception ee) {}
}
}
}
文件的打开和保存都可以实现,类似电脑自带的记事本功能,下图是基本页面。