Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get focus in JPopupMenu

I am an experienced Java programmer, but a Swing newbie so please bear with me.

I wish to have a JPopupWindow which has keyboard focus. I want to respond to arrow keys, escape (to close the menu) and Enter (to invoke the item). Must I add a KeyListener to the menu and code all this myself, or is there some sort of "mode" I can set to activate this behavior which seems like it ought to be standard.

The standard Swing tutorial section on JPopupMenus speaks only of mnemonics and accelerators. I don't particularly want those.

Hard to believe that this is totally against the grain of JPopupMenu.

What is best way to get something like I want implemented?

like image 483
Steve Cohen Avatar asked Dec 14 '11 15:12

Steve Cohen


2 Answers

Once you do jpopupMenu.show(Component invoker, int x, int y)it will automatically respond to keyboard as you want. If this is not working then you might need to fix some other issue i.e some other component is snatching away focus from the menu when it should not etc.

like image 185
Ashwinee K Jha Avatar answered Nov 05 '22 02:11

Ashwinee K Jha


Instead of KeyListener, I'd recommend adding Action instances to your JPopupMenu. Use setComponentPopupMenu() to add the popup to your panel.

like image 39
trashgod Avatar answered Nov 05 '22 00:11

trashgod