简体   繁体   English

JDialog:如何禁用“模态”对话框的ESC键?

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

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. 从这里,我打开Modal JDialog并启动后台线程工作,同时在表中显示进度(日志条目)。 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(). 但是,用户可以随时点击ESC键并调用我的onCanceled(),从而调用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! 编辑:我继承了这个项目,并监督了继承的兔子洞有多深,从而已经监督了ESC的处理,随后是e.consume(),这就是为什么我的解决方案无法正常工作的原因!

You must ignore strokes from ESC key. 您必须忽略ESC键的笔划。 You can do this by listening key events from your dialog as the following (Suppose variable jDialog is your dialog object). 您可以通过以下方式监听对话框中的键事件来做到这一点(假设变量jDialog是您的对话框对象)。

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

However, the user can at any time tap the ESC key and my onCanceled() is called 但是,用户可以随时点击ESC键,并且我的onCanceled()被调用

This sounds like custom code added to the APP since most LAF's don't implement the Escape key by default. 这听起来像自定义代码添加到了APP,因为大多数LAF默认情况下不实现Escape键。 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 . 但是,如果此默认行为是LAF的默认行为,则拦截Escape键的正确方法是使用Key Bindings The tutorial shows how to override/remove a binding. 本教程显示了如何覆盖/删除绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM