views:

422

answers:

1

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?

As always, my apologies ahead of time if this is a duplicate - I searched both Google and Stackoverflow and found nothing.

+1  A: 

You can create you JOptionPane, and then loops through the components of the pane, and the components 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();

broschb
These are the dialogs created with the JOptionPane.showDialog() functions. They return an integer value, and as far as I know there's no way to access an instance of them. Legacy code.
Daniel Bingham
Sounds like you will need to override the JOptionPane class then to add the mnemonic. Either that or create the JOptionPane component, and put it in a dialog yourself, and then you can wrap through the compoents, or better yet, just create your own dialog or option dialog to meet your needs, sounds like that may be your best option, giving you full control of the dialog. Once you create the dialog once, you can then use it everywhere you need it.
broschb
Yeah, the issue was trying to force the mnemonics into the JOptionPane using legacy code with out much refactoring. The more research I'm doing the more it looks impossible. The only way to do it is seems is option A) make my own JDialog or option B) extend JOptionPane. Neither works for this situation.
Daniel Bingham