java小型记事本代码
时间: 2024-06-18 22:05:02 浏览: 202
Java小型记事本代码的实现可以基于Swing组件库,以下是一个简单的Java小型记事本的代码示例:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class JavaNotepad extends JFrame implements ActionListener {
JTextArea area = new JTextArea(20,120);
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("文件");
JMenuItem open = new JMenuItem("打开");
JMenuItem save = new JMenuItem("保存");
JMenuItem exit = new JMenuItem("退出");
public JavaNotepad() {
JScrollPane scroll = new JScrollPane(area);
area.setFont(new Font("宋体",Font.BOLD,20));
add(scroll,BorderLayout.CENTER);
setJMenuBar(mb);
mb.add(file);
file.add(open);
file.add(save);
file.add(exit);
open.addActionListener(this);
save.addActionListener(this);
exit.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == open)
openFile();
else if (e.getSource() == save)
saveFile();
else if (e.getSource() == exit)
System.exit(0);
}
public void openFile() {
JFileChooser chooser = new JFileChooser();
int option = chooser.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
area.setText("");
try {
Scanner scan = new Scanner(new FileReader(chooser.getSelectedFile().getPath()));
while (scan.hasNext())
area.append(scan.nextLine() + "\n");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
public void saveFile() {
JFileChooser chooser = new JFileChooser();
int option = chooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter(chooser.getSelectedFile().getPath()));
out.write(area.getText());
out.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
public static void main(String[] args) {
JavaNotepad editor = new JavaNotepad();
editor.setDefaultCloseOperation(EXIT_ON_CLOSE);
editor.pack();
editor.setVisible(true);
editor.setLocationRelativeTo(null);
}
}
```
该记事本可以打开、保存、退出文件,功能简单,适合初学者学习。
阅读全文