简体   繁体   English

在打开新框架时关闭jframe

[英]close jframe while opening new one

i try to open new frame which is named stage2 while closing the main frame. 我尝试在关闭主框架的同时打开一个名为stage2的新框架。 but when i put main.setVisible(false) there its said not an enclosing class and i put this listener on jpanel class which called by the mainframe. 但是当我把main.setVisible(false)放到那里时,它说不是一个封闭的类,我把这个监听器放在大型机调用的jpanel类上。 so its look like this.. 所以看起来像这样

class main extends JFrame()
{
   main()
     {
     }
   add(story2)
}

class story2 extends JPanel()
{
    public void mouseClicked(MouseEvent e)
            {

                 new stage2(); 
                 main.this.setVisible(false);
            }
}

That is because story2 is indeed not an inner class of main . 这是因为story2确实不是main的内部类。 You should use JComponent's getTopLevelAncestor() to get a handle to the JFrame story2 is in and then do what you want with the JFrame. 您应该使用JComponent的getTopLevelAncestor()来获取JFrame story2所在的句柄,然后使用JFrame进行所需的操作。 Something like this: 像这样:

((JFrame)this.getTopLevelAncestor()).dispose();

(If you won't be needing main JFrame any more, it is better to use dispose() than just setVisibke(false) , in order to free resources and memory.) (如果不再需要main JFrame,则最好使用dispose()不是setVisibke(false)来释放资源和内存。)

The above code-sample is just a demonstration. 上面的代码示例只是一个演示。 In a production-ready app you should, of course, first check that the top-level ancestor can be cast to JFrame (or at least Window). 当然,在可用于生产环境的应用程序中,您首先应该检查是否可以将顶级祖先转换为JFrame(或至少转换为Window)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM