Is there any way to auto-select a jmenu within my jmenubar when the user's pressing the "ALT" key ? (Like windows softwares)
The problem is that the default behavior of my jframe, when the "ALT" key is pressed, is to show up a menu containing the following actions : restore, move, size, reduce, ...
What I want my java application to do, is to select my jmenu first item when "alt" is pressed. (Like it would do with a mnemonic : "alt + f")
Add the action to the
ActionMap
andInputMap
of yourJRootPane
. See below:I've found the response very useful, but also with a drawback.
Imagine you're using Cross PlatForm L&F (Metal) and you've defined mnemonics to all the menus; you know that those menus are invoked against pressing . So, if we put the solution provided by black panda the results on a pressing are first we watch the desired menu deployed but immediately after switches to the first menu.
I think that the best way would be on ALT pressing only the first menu should be selected but without showing its contents (Those contents shoud appear on a down key pressing). Is there any way to do this in Cross Platform L&F?.
Alternatively there is another way to proceed without any extra code. If we invoke the System L&F (Windows in my case) the ALT key behaves as desired. See stackoverflow question 13474555 for details.
Use actionmap and inputmap of JComponent to do this job. Since JFrame is not a descendant of JCompoenent i would suggest you adding JPanel to your jframe and then,
I have found just by using
frame.setJMenuBar(jmenubar);
whereframe
is your JFrame andjmenubar
is your JMenuBar, it'll automatically do this. You don't even have to add it to your layout manager.