用java编写一个记事本程序能在eclipse且文件菜单上包含打开、保存和退出功能
时间: 2024-12-23 18:18:24 浏览: 0
编写一个简单的记事本程序,我们可以在Eclipse环境中创建一个新的Java SWT应用,因为SWT提供了一个简洁的界面控件库。这里是一个基本框架,包含了文件菜单上的打开、保存和退出操作:
```java
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.jface.dialogs.MessageDialog;
import java.io.*;
public class NotepadApp extends Shell {
private Text textArea;
private Menu menuBar;
private MenuItem openItem;
private MenuItem saveItem;
private MenuItem exitItem;
public NotepadApp() {
super("简易记事本");
// 设置窗口样式
Style style = new Style();
style.configure(Shell.TITLE_BAR | Shell.CLOSE | Shell.MIN | Shell.MAX);
// 创建文本区域
textArea = new Text(this, SWT.MULTI | SWT.V_SCROLL);
textArea.setBounds(0, 0, 400, 300);
// 创建菜单栏
menuBar = new Menu(this);
setMenuBar(menuBar);
// 创建菜单项
createMenuItems();
}
private void createMenuItems() {
openItem = new MenuItem(menuBar, SWT.PUSH);
openItem.setText("&打开");
openItem.addSelectionListener(e -> handleOpenFile());
saveItem = new MenuItem(menuBar, SWT.PUSH);
saveItem.setText("&保存");
saveItem.addSelectionListener(e -> handleSaveFile());
exitItem = new MenuItem(menuBar, SWT.PUSH);
exitItem.setText("&退出");
exitItem.addSelectionListener(e -> handleExit());
}
private void handleOpenFile() {
FileDialog dialog = new FileDialog(this, SWT.OPEN);
if (dialog.open() != null) {
try (BufferedReader reader = new BufferedReader(new FileReader(dialog.getFile()))) {
String line;
while ((line = reader.readLine()) != null) {
textArea.append(line + "\n");
}
} catch (IOException e) {
MessageDialog.openError(this, "错误", "无法打开文件: " + e.getMessage());
}
}
}
private void handleSaveFile() {
FileDialog dialog = new FileDialog(this, SWT.SAVE);
if (dialog.open() != null) {
try (PrintWriter writer = new PrintWriter(new FileWriter(dialog.getFile()))) {
writer.println(textArea.getText());
} catch (IOException e) {
MessageDialog.openError(this, "错误", "无法保存文件: " + e.getMessage());
}
}
}
private void handleExit() {
if (!textArea.getText().isEmpty()) {
int result = MessageDialog.openQuestion(this, "确认", "是否保存未更改的内容?");
if (result == MessageBox.OK) {
handleSaveFile();
}
}
dispose();
}
// 主函数启动应用程序
public static void main(String[] args) {
Display display = new Display();
final NotepadApp app = new NotepadApp();
app.open();
display.dispose();
}
}
```
阅读全文