wvdz
wvdz

Reputation: 16651

Java Swing: How to prevent JOptionPane.showConfirmDialog() from focusing?

In my application I use JOptionPane.showConfirmDialog() at several places.

I now have the requirement to prevent it from focusing a button, so that when a user presses <Enter>, the dialog remains.

Is there a way to do this without having to write my own extension of dialog?

To clarify: the main issue is that it may not close when the user presses enter. The dialog not focusing is merely an obvious way of accomplishing that.

Upvotes: 0

Views: 828

Answers (1)

martinez314
martinez314

Reputation: 12332

If you set custom buttons and set the initial button value to null, it will give you the behavior you want: no initially focused button, so pressing the Enter key will not do anything.

See the below example:

public class Test {

    public static void main(final String[] args) {
        final Object[] options = { "OK", "Cancel" };
        JOptionPane.showOptionDialog(null, "Enter won't work.", "Title", 
                JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, 
                null, options, 
                null);  // this is the trick

        JOptionPane.showOptionDialog(null, "Can press Enter.", "Title", 
                JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, 
                null, options, options[1]);
    }
}

Upvotes: 3

Related Questions