java记事本代码
时间: 2023-07-02 13:18:46 浏览: 109
毕业设计JAVA记事本源代码
以下是 Java 编写的简单记事本代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Notepad extends Frame implements ActionListener {
MenuBar mb;
TextArea ta;
Menu file;
MenuItem open, save, exit;
FileDialog fd;
String filename;
public Notepad() {
super("Untitled - Notepad");
mb = new MenuBar();
file = new Menu("File");
open = new MenuItem("Open");
save = new MenuItem("Save");
exit = new MenuItem("Exit");
open.addActionListener(this);
save.addActionListener(this);
exit.addActionListener(this);
file.add(open);
file.add(save);
file.addSeparator();
file.add(exit);
mb.add(file);
setMenuBar(mb);
ta = new TextArea();
add(ta);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
setSize(600, 400);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == open) {
fd = new FileDialog(this, "Open", FileDialog.LOAD);
fd.setVisible(true);
if (fd.getFile() != null) {
filename = fd.getDirectory() + fd.getFile();
setTitle(filename + " - Notepad");
readFile();
}
} else if (ae.getSource() == save) {
if (filename == null) {
fd = new FileDialog(this, "Save", FileDialog.SAVE);
fd.setVisible(true);
if (fd.getFile() != null) {
filename = fd.getDirectory() + fd.getFile();
setTitle(filename + " - Notepad");
writeFile();
}
} else {
writeFile();
}
} else {
System.exit(0);
}
}
private void readFile() {
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
ta.setText("");
while ((line = br.readLine()) != null) {
ta.append(line + "\n");
}
br.close();
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
private void writeFile() {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
bw.write(ta.getText());
bw.close();
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
public static void main(String[] args) {
new Notepad();
}
}
```
该代码创建了一个简单的记事本程序,可以打开和保存文本文件。它使用了 AWT 和事件处理程序来实现用户界面和交互。
阅读全文