Question

i am beginner in java.

i have create on JDialog box which must wait for the reply

for tha the following code is write

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

now the problem is that when this dialog is display the user can close this dialog by pressing the escape key now i want stop the dialog to close on pressing escape key. can any one help me?

i have refer the following link which is not use full for me

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

Was it helpful?

Solution 2

you must have to set the following property true for add listener on JDialog.

 jDialog.setFocusable(true);

then by adding key listener you can disable the or avoid the escape key by following code

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

OTHER TIPS

I have found the perfect solution for the above problem.

First of all we have to set the JDialog focusable:

 jDialog.setFocusable(true);

then apply following code to disable the escape key:

    jDialog.addKeyListener(new KeyListener() {
         @Override
         public void keyPressed(KeyEvent e) {
           // Catch ESC key stroke.
           if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
              e.consume();
           }
         }
        });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top