java简易记事本代码
时间: 2024-06-30 16:01:05 浏览: 174
Java简易记事本代码通常是一个基础的控制台应用,它允许用户创建、编辑和查看文本文件。以下是一个简单的例子,使用Java Swing库来创建一个基本的界面:
```java
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class SimpleNotePad {
private JTextArea textArea;
private JButton btnSave, btnCancel, btnLoad;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SimpleNotePad window = new SimpleNotePad();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SimpleNotePad() throws IOException {
JFrame frame = new JFrame("Simple Note Pad");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLayout(new BorderLayout());
textArea = new JTextArea();
textArea.setEditable(true);
JScrollPane scrollPane = new JScrollPane(textArea);
JPanel buttonPanel = new JPanel();
btnSave = new JButton("Save");
btnCancel = new JButton("Cancel");
btnLoad = new JButton("Load");
btnSave.addActionListener(e -> saveToFile());
btnCancel.addActionListener(e -> close());
btnLoad.addActionListener(e -> loadFromFile());
buttonPanel.add(btnSave);
buttonPanel.add(btnCancel);
buttonPanel.add(btnLoad);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);
}
private void saveToFile() {
JFileChooser chooser = new JFileChooser();
if (chooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(textArea.getText());
} catch (IOException e) {
System.out.println("Error saving file: " + e.getMessage());
}
}
}
private void loadFromFile() {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
textArea.setText(reader.lines().collect(Collectors.joining("\n")));
} catch (IOException e) {
System.out.println("Error loading file: " + e.getMessage());
}
}
}
private void close() {
frame.dispose();
}
}
```
这个程序创建了一个简单的窗口,包含一个文本区域用于显示或编辑文本,以及三个按钮用来保存、加载和关闭。用户可以通过选择文件来保存或读取内容。
阅读全文