importjava.awt.BorderLayout;importjava.awt.Container;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjavax.swing.JFileChooser;importjavax.swing.JFrame;importjavax.swing.JMenu;importjavax.swing.JMenuBar;importjavax.swing.JMenuItem;importjavax.swing.JScrollPane;importjavax.swing.JTextArea;public class NotepadDemo extends JFrame implementsActionListener {
JTextArea inputText;
JScrollPane pane;publicNotepadDemo() {this.setTitle("Notepad");this.setSize(600, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane= this.getContentPane();
contentPane.setLayout(new BorderLayout(5,1));
JMenuBar menuBar= newJMenuBar();
JMenu menu= new JMenu("File");
JMenuItem open=new JMenuItem("打开...");
open.addActionListener(this);
menu.add(open);
JMenuItem save=new JMenuItem("存盘");
save.addActionListener(this);
menu.add(save);
menu.addSeparator();
JMenuItem item= new JMenuItem("退出");
menu.add(item);
item.addActionListener(this);
menuBar.add(menu);this.setJMenuBar(menuBar);
inputText=new JTextArea(100, 100);
pane=newJScrollPane(inputText);
contentPane.add(pane);
}public static voidmain(String[] args) {
JFrame frame= newNotepadDemo();
frame.setVisible(true);
}
@Overridepublic voidactionPerformed(ActionEvent event) {
String cmd=event.getActionCommand();if ("退出".equals(cmd)) {this.dispose();
}if ("打开...".equals(cmd)) {
File srcFile=null;
JFileChooser fileChooser=newJFileChooser();int res=fileChooser.showOpenDialog(null);if(res==JFileChooser.APPROVE_OPTION) {
srcFile=fileChooser.getSelectedFile();
}try{
InputStream is= newFileInputStream(srcFile);byte[] buffer = new byte[8*1024];intlen;while ((len = is.read(buffer)) != -1) {
String text= new String(buffer, 0, len,"UTF-8");
inputText.append(text);
}
is.close();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
}if ("存盘".equals(cmd)) {
File destFile=null;
JFileChooser fileChooser=newJFileChooser();int res = fileChooser.showSaveDialog(null);if (res ==JFileChooser.APPROVE_OPTION) {
destFile=fileChooser.getSelectedFile();
}else{
System.out.println("用户取消");return;
}try{
OutputStream os= newFileOutputStream(destFile);
os.write(inputText.getText().getBytes("UTF-8"));
os.close();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}