【问题标题】:Recursion causes exit to exit all JFrames (terminates app)递归导致 exit 退出所有 JFrame(终止应用程序)
【发布时间】:2011-01-24 12:57:18
【问题描述】:

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

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

【问题讨论】:

    标签: java swing recursion terminate


    【解决方案1】:

    我完全删除了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) {}
                });
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 我之前尝试过 DISPOSE_ON_CLOSE 但仍然没有帮助,我只是尝试了一下以确保问题仍然存在。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      相关资源
      最近更新 更多