【发布时间】:2014-05-20 21:02:32
【问题描述】:
我正在创建一个简单的文本编辑器,但遇到了一个小问题。通过单击菜单中的新按钮,我可以打开并打开几个用于创建文本文档的新窗口。我的问题是,如果我从菜单中单击“文件”,然后单击“退出”,它会关闭所有窗口,而不仅仅是我想要关闭的那个。我该怎么做才能关闭所选窗口而不是整个应用程序。
这里有一些代码:
public void actionPerformed(ActionEvent event) {
if(event.getSource() == newFile) {
new EditorGUI();
} else if(event.getSource() == openFile) {
JFileChooser open = new JFileChooser();
open.showOpenDialog(null);
File file = open.getSelectedFile();
openingFiles(file);
} else if(event.getSource() == exit) {
System.exit(0);
}
}
但是,当我单击窗口右上角的 X 时,它可以工作:
private JFrame createEditorWindow() {
editorWindow = new JFrame("JavaEdit");
editorWindow.setVisible(true);
editorWindow.setExtendedState(Frame.MAXIMIZED_BOTH);
editorWindow.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// Create Menu Bar
editorWindow.setJMenuBar(createMenuBar());
editorWindow.add(scroll, BorderLayout.CENTER);
editorWindow.pack();
// Centers application on screen
editorWindow.setLocationRelativeTo(null);
return editorWindow;
}
截图:
【问题讨论】:
-
请参阅The Use of Multiple JFrames, Good/Bad Practice?,了解为什么通常不建议使用多帧的一些背景知识。 OTOH 这听起来像是为数不多的“角落案例”之一,其中拥有多个框架实例(每个正在编辑的文档一个)可能对用户有意义。在这种情况下,向下滚动到讨论该用例的其他一些答案。