java记事本图形界面
时间: 2023-07-16 17:14:11 浏览: 95
java 记事本 图形化界面
以下是一个简单的 Java 记事本图形界面的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class JavaNotepad extends JFrame implements ActionListener {
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem newMenuItem = new JMenuItem("New");
JMenuItem openMenuItem = new JMenuItem("Open");
JMenuItem saveMenuItem = new JMenuItem("Save");
JMenuItem exitMenuItem = new JMenuItem("Exit");
public JavaNotepad() {
setTitle("Java Notepad");
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
fileMenu.add(newMenuItem);
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
add(scrollPane);
newMenuItem.addActionListener(this);
openMenuItem.addActionListener(this);
saveMenuItem.addActionListener(this);
exitMenuItem.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newMenuItem) {
textArea.setText("");
} else if (e.getSource() == openMenuItem) {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
FileReader reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
textArea.read(bufferedReader, null);
bufferedReader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
} else if (e.getSource() == saveMenuItem) {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
FileWriter writer = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
textArea.write(bufferedWriter);
bufferedWriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
} else if (e.getSource() == exitMenuItem) {
System.exit(0);
}
}
public static void main(String[] args) {
JavaNotepad notepad = new JavaNotepad();
notepad.setVisible(true);
}
}
```
运行该代码将会打开一个简单的记事本窗口,其中包含菜单栏和一个文本区域。用户可以使用菜单栏上的选项来新建、打开、保存或退出文档。文本区域支持复制、粘贴和撤销等基本文本编辑功能。
阅读全文