【问题标题】:Disable Escape key on JDialog Box禁用 JDialog Box 上的 Escape 键
【发布时间】:2014-04-25 06:03:26
【问题描述】:

我是java初学者。

我在 JDialog 上创建了必须等待回复的对话框

下面的代码是写的

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: How to disable the ESC key of my Modal dialog?

【问题讨论】:

    标签: java swing joptionpane jdialog


    【解决方案1】:

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

    首先我们要设置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();
               }
             }
            });
    

    【讨论】:

      【解决方案2】:

      您必须将以下属性设置为 true 才能在 JDialog 上添加侦听器。

       jDialog.setFocusable(true);
      

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-12
        • 2010-12-20
        • 1970-01-01
        • 2019-01-30
        • 2011-12-06
        相关资源
        最近更新 更多