views:

42

answers:

2

So there's a frame (main app). From here, I open a Modal JDialog and start a background thread working whilst displaying progress (log entries) in a table. This process is critical and should not be stoppable/hideable/closeable, thus why the dialog's close button is de-activated until everything's finished. However, the user can at any time tap the ESC key and my onCanceled() is called, thus calling this.dispose().

EDIT: I inherited this project and oversaw how deep the rabbit hole of inheritance went, thus overseeing handling of ESC already, followed by e.consume() which is why my solutions weren't working!

+1  A: 

You must ignore strokes from ESC key. You can do this by listening key events from your dialog as the following (Suppose variable jDialog is your dialog object).

jDialog.addKeyListener(new KeyListener() {
    @Override
    public void keyPressed(KeyEvent e) {
        // Catch ESC key stroke.
        if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
            // TODO ignore or warn user here.
            // or call e.consume();
        }
    }

    // Other overriden methods here.
});
ovunccetin
`e.consume();`?
Ishtar
Speaking of which, e.consume() was being called by some evil base class way down in the chain after handling ESC.. which is why adding listeners didn't help! Otherwise ovunccetin's answer would have worked perfectly ;)
glenneroo
+2  A: 

However, the user can at any time tap the ESC key and my onCanceled() is called

This sounds like custom code added to the APP since most LAF's don't implement the Escape key by default. So I would remove the custom code.

However,if this default behaviour for your LAF then the proper way to intercept the Escape key is to use Key Bindings. The tutorial shows how to override/remove a binding.

camickr
HA thanks for that! I inherited this crazy project and yes now that you point it out, ESC was already being handled far down in a chain of base classes I had overlooked - followed by an evil e.consume()
glenneroo