package 我的记事本; import java.awt.*; import javax.print.attribute.standard.Destination; import javax.swing.*; import java.awt.event.*; import java.io.*; public class Mytext extends JFrame implements ActionListener{ JTextArea myTextArea; JScrollPane my; JMenuBar myMenuBar; JMenu file,edit,source; JMenuItem New,Open,Save; JMenuItem Cut,Copy; JMenuItem test; public static void main(String []args){ Mytext a = new Mytext(); } Mytext(){ myTextArea = new JTextArea(); my = new JScrollPane(myTextArea); //标题栏 myMenuBar = new JMenuBar(); file = new JMenu("文件"); edit = new JMenu("编辑"); source = new JMenu("资源"); New = new JMenuItem("新建"); New.setMnemonic('f'); Open = new JMenuItem("打开"); Open.addActionListener(this); Open.setActionCommand("open"); Save = new JMenuItem("保存"); Save.addActionListener(this); Save.setActionCommand("save"); Cut = new JMenuItem("剪切"); Copy = new JMenuItem("复制"); test = new JMenuItem("测试",new ImageIcon("image/shan.jpg")); myMenuBar.add(file); myMenuBar.add(edit); myMenuBar.add(source); file.add(New); file.addSeparator(); file.add(Open); file.addSeparator(); file.add(Save); edit.add(Cut); edit.addSeparator(); edit.add(Copy); source.add(test); this.add(my); this.setTitle("记事本"); this.setIconImage(new ImageIcon("image/tubiao2.jpg").getImage()); this.setJMenuBar(myMenuBar); this.setSize(500,500); this.setLocation(100, 200); this.setResizable(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("open")){ //System.out.println("打开"); JFileChooser mychoose = new JFileChooser(); mychoose.setDialogTitle("文件打开"); mychoose.showOpenDialog(null); mychoose.setVisible(true); String category = mychoose.getSelectedFile().getAbsolutePath(); BufferedReader Mytextbuf = null; FileReader mytext = null; try { mytext = new FileReader(category); Mytextbuf = new BufferedReader(mytext); String msg =""; String zfc =""; while((msg =Mytextbuf.readLine()) != null){ zfc +=msg+"\n"; } myTextArea.setText(zfc); } catch (Exception e1) { e1.printStackTrace(); }finally{ try { mytext.close(); Mytextbuf.close(); } catch (IOException e1) { e1.printStackTrace(); } } } if(e.getActionCommand().equals("save")){ JFileChooser filedestination = new JFileChooser(); filedestination.setDialogTitle("文件另存为"); filedestination.showSaveDialog(this); filedestination.setVisible(true); String category = filedestination.getSelectedFile().getAbsolutePath(); FileWriter destination =null; BufferedWriter destinationbuf = null; try { destination = new FileWriter(category); destinationbuf = new BufferedWriter(destination); myTextArea.write(destinationbuf); } catch (IOException e1) { e1.printStackTrace(); }finally{ try { destination.close(); destinationbuf.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } }