递归导致 exit 退出所有 JFrame(终止应用程序)
我制作了一个应用程序,让用户可以选择完全打开应用程序的新生成。当用户这样做并关闭应用程序时,整个应用程序将终止;不仅仅是窗户。
我应该如何递归地生成应用程序,然后当用户退出 JFrame 生成时;只杀死那个 JFrame 而不是整个实例?
这是相关代码:
[...]
JMenuItem newMenuItem = new JMenuItem ("New");
newMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
new MainWindow();
}
});
fileMenu.add(newMenuItem);
[....]
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
fileMenu.add(exit);
[...]
I have made an application that gives the user the option to open up a new spawn of the application entirely. When the user does so and closes the application the entire application terminates; not just the window.
How should I go about recursively spawning an application and then when the user exits the JFrame spawn; killing just that JFrame and not the entire instance?
Here is the relevant code:
[...]
JMenuItem newMenuItem = new JMenuItem ("New");
newMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
new MainWindow();
}
});
fileMenu.add(newMenuItem);
[....]
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
fileMenu.add(exit);
[...]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您应该尝试
JFrame.DISPOSE_ON_CLOSE
而不是JFrame.EXIT_ON_CLOSE
,因为无论是否有活动线程在运行,EXIT_ON_CLOSE 都会关闭应用程序。如果您仍然遇到问题,您应该考虑引入实例计数器。更聪明地做出反应
另请参阅此讨论
First you should try
JFrame.DISPOSE_ON_CLOSE
instead ofJFrame.EXIT_ON_CLOSE
because EXIT_ON_CLOSE shuts down the application no matter if there are active threads running or not.If you still have issues you should consider to introduce an instance counter. To react smarter
See also this discussion
我完全删除了
frame.setDefaultCloserOperation(JFrame.EXIT_ON_CLOSE);
代码。我将其更改为
DISPOSE_ON_CLOSE
,但问题仍然发生。我最终创建了一个 windowEvent 并添加:frame.dispose();
并且行为正是我想要的。这是代码:
I completely removed the
frame.setDefaultCloserOperation(JFrame.EXIT_ON_CLOSE);
code.I changed it to
DISPOSE_ON_CLOSE
and still the problem was still happening. I ended up creating a windowEvent and adding:frame.dispose();
and the behavior is what I wanted.Here is the code: