The class Window
which superclasses JFrame
has the method getOwnedWindows
which you can use to get an array of all child (owned) Window
s (including JFrame
s and JDialog
s).
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.