java Swing - 如何从内部关闭表单?如何关闭窗体而不影响父窗体?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6013732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:57:52  来源:igfitidea点击:

Swing - How to close a form from inside? How to close the form without affecting the parent form?

javaswingwindowlistener

提问by Bick

I am creating a form in Swing toolkit.
When I want to close it, I go to the JFrame and set it to visible false.
Since the frame creates a Java class of the form, I can easily do it from outside.

我正在 Swing 工具包中创建一个表单。
当我想关闭它时,我转到 JFrame 并将其设置为可见的 false。
由于框架创建了表单的 Java 类,因此我可以轻松地从外部完成。

When I have a cancel button I usually send a listener inside the form that calls the outer:

当我有一个取消按钮时,我通常会在调用外部的表单内发送一个侦听器:

 Jframe.setVisible (false)

Is there a better way ?

有没有更好的办法 ?

回答by oliholz

The SwingUtilitiesclass provide a method to get the window ancestor of a given component. You can gat the parent Window and call setVisibleor disposeor perhaps only an event.

SwingUtilities类提供一个方法来获得一个给定的组件的窗口祖先。您可以打开父窗口并调用setVisibledispose仅调用一个事件。

Window window = SwingUtilities.getWindowAncestor(this);
window.setVisible( false );
    // OR
window.dispose();
    // OR
WindowListener[] windowListeners = window.getWindowListeners();
windowListeners[0].windowClosing( null );

回答by nilakantha singh deo

try these if you do not need to code much! click here to view image

如果您不需要太多编码,请尝试这些! 单击此处查看图像