Dylan Lawrence
Dylan Lawrence

Reputation: 1533

Prevent Closing of JDialog from Exit Button

I searched google and stackoverflow quite a bit and they all indicate that using:

d.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

will prevent the exit button from closing the dialog, as of now, it is not... Posted below is the relevant code snippet that seems to be having problems:

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);
}

Upvotes: 3

Views: 2424

Answers (1)

Justin
Justin

Reputation: 25377

Your JDialog is a modal dialog, so everything after setVisible(true) doesn't affect it. Move relevant code to before 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);
}

It is a good habit to only set the dialog as visible when you have finished setting all the options, even with non-modal dialogs.

See JDialog, it says this:

dialog blocks user input to other top-level windows when shown

Also mentioned in An Overview of Dialogs.

Upvotes: 2

Related Questions