JDialog: How to disable the ESC key of my Modal dialog?

房东的猫 提交于 2019-12-21 22:34:18

问题


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:


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.




回答2:


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


来源:https://stackoverflow.com/questions/4004174/jdialog-how-to-disable-the-esc-key-of-my-modal-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!