提问者:小点点

禁用JDialog Box上的转义键


我是java初学者。

我在JDialog框上创建了必须等待回复的内容

为tha编写以下代码

final Object[] options = {"Yes!! I am woking", "No!! was not working"};

final JOptionPane optionPane =
        new JOptionPane("IT look like are you busy  \n with Something else!!! \n Are you working?",
                JOptionPane.QUESTION_MESSAGE,
                JOptionPane.YES_NO_OPTION, null, options);

JDialog dialog = optionPane.createDialog("Are you working?");
dialog.setAlwaysOnTop(true);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.toFront();
dialog.setVisible(true);

现在的问题是,当显示此对话框时,用户可以通过按转义键关闭此对话框,现在我想在按转义键时停止对话框以关闭。有人能帮我吗?

我有参考以下链接这是不使用完整的我

JDialog:如何禁用我的模式对话框的ESC键?


共2个答案

匿名用户

我已经找到了上述问题的完美解决方案。

首先,我们必须将JDialog设置为可聚焦:

 jDialog.setFocusable(true);

然后应用以下代码来禁用转义键:

    jDialog.addKeyListener(new KeyListener() {
         @Override
         public void keyPressed(KeyEvent e) {
           // Catch ESC key stroke.
           if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
              e.consume();
           }
         }
        });

匿名用户

您必须为JDialog上的添加侦听器设置以下属性true。

 jDialog.setFocusable(true);

然后通过添加键侦听器,您可以通过以下代码禁用或避免转义键

    jDialog.addKeyListener(new KeyListener() {
     @Override
     public void keyPressed(KeyEvent e) {
                   write any code related to kdy
     }
    });