Search code examples
javaswingjoptionpane

Disable SPACE BAR and ENTER keys in JOPTIONPANE


First, I apologize for the double post ( I can't delete my old one)... Actually, I thought my problem was solved, but it's not...

I have a problem with my software developped in Java. The user (who would be a child of 7-9 years) has to write a text in a JtextPane. When there's no time left for him to write, a pop-up appears saying "there's no time left, it's time to write another story".

The only problem is : if the user is writting when the message pops up, the pop-up disappears because the space bar or "enter" validates the message. And when you write a text, you often press that keys... :/

Is there's anyway I can disable this fonction ? And allow the message to disappear only if the user click "OK" ? I tried using listeners but It didn't work.

I used this to create the MessageDialog :

JOptionPane.showMessageDialog(null,
                new UTIL_LireFichierTXT().getText(MessageTempsImparti)
                ,new UTIL_LireFichierTXT().getText(MessageAttention),JOptionPane.WARNING_MESSAGE);

I am a trainee and my boss told me "you must show a pop-up", so I can't do anyway else... Have you any idea to help me ? Thanks for reading.


Solution

  • It's not a good idea, to do what you want, but I have a solution. You can simply disable all key events when dialog shown. Here is a sample.

        AWTEventListener myListener = new AWTEventListener() {
    
            @Override
            public void eventDispatched(AWTEvent event) {
                if (event instanceof KeyEvent) {
                    ((KeyEvent) event).consume();
                }
            }
        };
        Toolkit.getDefaultToolkit().addAWTEventListener(myListener, AWTEvent.KEY_EVENT_MASK);
        JOptionPane.showMessageDialog(null, "You have a message!");
        Toolkit.getDefaultToolkit().removeAWTEventListener(myListener);
    

    Please use this solution only if your boss really want it. I would preffer to make your text component non-editable and show the warning message as ovelay to it (you can use JLayeredPane for this purpose).