Close all Java child windows

这一生的挚爱 提交于 2019-12-11 18:34:32

问题


In Java Swing is there a way to find and close all JDialog objects currently being displayed?

I have a large application and there are multiple parts that can call to display a dialog but from one single point I want to be able to detect and close it.


回答1:


Keep a reference to each of the dialogs (perhaps in a collection). When needed, iterate the collection and call dialog.setVisible(false).

As suggested by @mKorbel, you can also use:

Window[] windows = Window.getWindows();

You'd just need to check for the 'parent' window when iterating the array and closing things.




回答2:


The class Window which superclasses JFrame has the method getOwnedWindows which you can use to get an array of all child (owned) Windows (including JFrames and JDialogs).

public class DialogCloser extends JFrame {

    DialogCloser() {

        JButton closeChildren = new JButton("Close All Dialogs");
        JButton openDiag = new JButton("Open New Dialog");

        closeChildren.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                Window[] children = getOwnedWindows();
                for (Window win : children) {
                    if (win instanceof JDialog)
                        win.setVisible(false);
                }
            }
        });

        openDiag.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                JDialog diag = new JDialog(DialogCloser.this);
                diag.setVisible(true);
            }
        });

        getContentPane().add(openDiag, BorderLayout.PAGE_START);
        getContentPane().add(closeChildren, BorderLayout.CENTER);

        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {

        new DialogCloser();
    }
}

Edit:

The question was changed to

find and close all JDialog objects currently being displayed

and I still assume they are all children of the same parent.




回答3:


The following piece of code does the trick:

private void closeAllDialogs()
{
    Window[] windows = getWindows();

    for (Window window : windows)
    {
        if (window instanceof JDialog)
        {
            window.dispose();
        }
    }
}


来源:https://stackoverflow.com/questions/29859469/close-all-java-child-windows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!