简易版记事本

贲宏硕
2023-12-01

public class TextPad {
private JTextArea contentArea;
private JFrame frame;
private String filename;
public TextPad() {
frame=new JFrame(“记事本”);
frame.setSize(700,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//添加菜单功能
JMenuBar menubar=new JMenuBar();
JMenu menu=new JMenu(“文件”);
JMenuItem newItem=new JMenuItem(“新建”);
newAction(newItem);
menu.add(newItem);
JMenuItem openItem=new JMenuItem(“打开”);
menu.add(openItem);
openAction(openItem);
menubar.add(menu);
frame.setJMenuBar(menubar);
//布局
frame.setLayout(new BorderLayout());
//在中间,增加文字编辑区
contentArea=new JTextArea();
JScrollPane pane=new JScrollPane(contentArea);
frame.add(pane);
frame.setVisible(true);
}

//记事本 菜单 新建操作
private void newAction(JMenuItem newItem) {
newItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
TextPad.this.contentArea.setText("");
TextPad.this.frame.setTitle(“新建-记事本”);
TextPad.this.filename=null;
}
});
}
//记事本,菜单 打开操作
private void openAction(JMenuItem openItem) {
openItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser=new JFileChooser();
FileNameExtensionFilter filter= new FileNameExtensionFilter(
“Text & dat”,“txt”,“dat”);
chooser.setFileFilter(filter);
int returnVal=chooser.showOpenDialog(TextPad.this.frame);
if(returnVal==JFileChooser.APPROVE_OPTION) {
String filename=chooser.getSelectedFile().getPath();
TextPad.this.filename=filename;
try {
String content=StringIoTool.read(filename);
contentArea.setText(content);
TextPad.this.frame.setTitle(filename+"-记事本");
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, “文件打开失败:”+filename);
}
}
}
});
}
public static void main(String[] args) {
new TextPad();
}

}

 类似资料: