[英]Close all Java child windows
在 Java Swing 中有沒有辦法找到並關閉當前顯示的所有JDialog
對象?
我有一個大型應用程序,可以調用多個部分來顯示一個對話框,但我希望能夠從一個點檢測並關閉它。
保留對每個對話框的引用(可能在集合中)。 需要時,迭代集合並調用dialog.setVisible(false)
。
正如@mKorbel 所建議的,您還可以使用:
Window[] windows = Window.getWindows();
在迭代數組和關閉事物時,您只需要檢查“父”窗口。
超類JFrame
的類Window
具有getOwnedWindows
方法,您可以使用該方法獲取所有子(擁有) Window
(包括JFrame
和JDialog
)的數組。
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();
}
}
編輯:
問題改為
查找並關閉當前顯示的所有
JDialog
對象
我仍然認為他們都是同一個父母的孩子。
以下代碼可以解決問題:
private void closeAllDialogs()
{
Window[] windows = getWindows();
for (Window window : windows)
{
if (window instanceof JDialog)
{
window.dispose();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.