我搜索了google和stackoverflow很多,他们都指出使用:
d.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
将阻止退出按钮关闭对话框,截至目前,它不是...发布如下是相关的代码片段似乎有问题:
if (gameArea.hitChest()) {
JDialog d = new JDialog((JFrame) gameArea.getTopLevelAncestor(), "Dialogue", true);
ChestLoot ch = new ChestLoot(player);
d.add(ch);
d.setSize(200, 100);
d.setVisible(true);
d.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
d.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.out.println("Don't Close!");
}
});
System.out.println("Should dispose here");
TileIcon ches = gameArea.getCurrChest();
gameArea.removeChest(ches);
}
答案 0 :(得分:2)
您的JDialog
是一个模态对话框,因此setVisible(true)
之后的所有内容都不会影响它。将相关代码移至setVisible(true)
之前:
if (gameArea.hitChest()) {
JDialog d = new JDialog((JFrame) gameArea.getTopLevelAncestor(), "Dialogue", true);
ChestLoot ch = new ChestLoot(player);
d.add(ch);
d.setSize(200, 100);
d.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
d.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.out.println("Don't Close!");
}
});
d.setVisible(true); //code pauses here and waits for the dialog to be handled
System.out.println("Should dispose here");
TileIcon ches = gameArea.getCurrChest();
gameArea.removeChest(ches);
}
当您完成所有选项的设置后,即使使用非模态对话框,也只能将对话框设置为可见,这是一个好习惯。
见JDialog
,它说:
当 显示 时,对话框会阻止用户输入其他顶级窗口
An Overview of Dialogs中也提到过。