3

我制作了一个应用程序,让用户可以选择完全打开一个新的应用程序。当用户这样做并关闭应用程序时,整个应用程序将终止;不仅仅是窗户。

我应该如何递归地生成应用程序,然后当用户退出 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);
[...]
4

2 回答 2

3

首先你应该尝试JFrame.DISPOSE_ON_CLOSE而不是JFrame.EXIT_ON_CLOSE因为 EXIT_ON_CLOSE 关闭应用程序,无论是否有活动线程正在运行。如果您仍然有问题,您应该考虑引入一个实例计数器。做出更聪明的反应另见此讨论

于 2010-03-06T20:43:06.897 回答
0

我完全删除了frame.setDefaultCloserOperation(JFrame.EXIT_ON_CLOSE);代码。

我将其更改为DISPOSE_ON_CLOSE,但问题仍然存在。我最终创建了一个 windowEvent 并添加:frame.dispose();并且行为是我想要的。

这是代码:

                frame.addWindowListener(new WindowListener() {
                public void windowClosing(WindowEvent e) {
                    //Allows for multiple instances and properly closing
                    //only one of the Frames instead of all of them
                    frame.dispose();
                }
                public void windowOpened(WindowEvent e) {}              
                public void windowClosed(WindowEvent e) {}
                public void windowIconified(WindowEvent e) {}
                public void windowDeiconified(WindowEvent e) {}
                public void windowActivated(WindowEvent e) {}
                public void windowDeactivated(WindowEvent e) {}
            });
于 2010-03-13T22:08:24.510 回答