Question

Is it possible to assign hotkeys and mnemonics to the buttons in a JOptionPane Dialog? I'd like to be able, in a JOptionPane generated message dialog with the options Yes, No and Cancel, press Y to hit the Yes button, N to hit the No button and escape to activate the escape button. Similarly in a dialog with Okay and Cancel buttons I'd like to be able to activate them with enter and escape.

I've attempted passing JButtons into the JOptionPane's button Object array with the Mnemonics set already. The mnemonics work and the buttons show up correctly in the dialogs, however, they do not act properly when they are activated. Most noticeably they do not dispose of the dialog.

What is the correct way to add hotkeys and Mnemonics to a JOptionPane Dialog's buttons?

Was it helpful?

Solution

You can create your JOptionPane, and then loop through the components of the pane (children etc.) checking to see if any components are instanceof JButton, and if so check the text, and set the proper mnemonic.

JOptionPane p = new JOptionPane();
Component[] c = p.getComponents();

OTHER TIPS

Make use of UIManager as follows:

UIManager.put("OptionPane.okButtonMnemonic", "79");  // for Setting 'O' as mnemonic
UIManager.put("OptionPane.cancelButtonMnemonic", "67"); // for Setting 'C' as mnemonic

Send the buttons in as parameters instead of Strings

    JButton button1 = new JButton( "<html>" + nextQuestion1 + "</html>");
    button1.setMnemonic('a');
    JButton button2 = new JButton(nextQuestion2 + "VUHU");
    JButton button3 = new JButton(abort);
    Object[] possibleValues = new Object[]{button1,button2,button3};
    int selectedValue = showOptionDialog(owner, question, possibleValues);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top