Java实现简单记事本

时间:2021-12-23 01:31:35

代码实现:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea; public class NotepadDemo extends JFrame implements ActionListener {
JTextArea inputText;
JScrollPane pane;
public NotepadDemo() {
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 = new JMenuBar();
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=new JScrollPane(inputText);
contentPane.add(pane);
} public static void main(String[] args) {
JFrame frame = new NotepadDemo();
frame.setVisible(true);
} @Override
public void actionPerformed(ActionEvent event) {
String cmd = event.getActionCommand();
if ("退出".equals(cmd)) {
this.dispose();
}
if ("打开...".equals(cmd)) {
File srcFile=null;
JFileChooser fileChooser=new JFileChooser();
int res=fileChooser.showOpenDialog(null);
if(res==JFileChooser.APPROVE_OPTION) {
srcFile=fileChooser.getSelectedFile();
}
try {
InputStream is = new FileInputStream(srcFile);
byte[] buffer = new byte[8*1024];
int len;
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=new JFileChooser();
int res = fileChooser.showSaveDialog(null);
if (res == JFileChooser.APPROVE_OPTION) {
destFile = fileChooser.getSelectedFile();
} else {
System.out.println("用户取消");
return;
}
try {
OutputStream os = new FileOutputStream(destFile);
os.write(inputText.getText().getBytes("UTF-8"));
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}