Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing JMenu Mnemonic

Tags:

java

swing

I have a menu that I created using JMenu. I want to assign a shortcut key Alt-F to this menu. I used setMnemonic('F') to do that, but the menu does not recognise the mnemonic.

What is the best way to troubleshoot or debug this problem ? I find that setting a break point does not help that much.

Thank you.

Code Snippet:

//higher up in variable declaration
/** Menus on the menu bar */
private JMenu uiFindMnu           = new JMenu("Find");
...
//inside the constructor
// set mnemonic for the Find menu
uiFindMnu.setMnemonic('F');
like image 254
zfranciscus Avatar asked Dec 14 '10 00:12

zfranciscus


2 Answers

Inside of a class constructor (extending JFrame):

JMenu helpmenu = new JMenu("File");
helpmenu.setMnemonic('F');
JMenuBar menubar = new JMenuBar();
menubar.add(helpmenu);
setJMenuBar(menubar);

That worked fine for me. You'll have to give some more details about your code in order for me to give a better answer. As far as troubleshooting SWING or any application GUI, one of the best recommendations I can give is to create the simplest possible scenario. I keep a bare-bones JFrame template around that I can throw simple code like this inside for testing. Once you know it works in the simplest scenario you can step back to your project and discover what other portion of your GUI is causing a conflict with this functionality.

Just out of curiosity, you don't happen to have a local variable called 'uiFindMnu' in your Constructor that is hiding your class variable, do you? I'd double check to make sure that the variable that you are calling setMnemonic() on is the one that is added to your MenuBar (and actually displayed).

like image 187
robert_x44 Avatar answered Sep 25 '22 00:09

robert_x44


Suffered with similar problem and realised that due to the setting of Look and feel after initialising the components caused the issue. Flipped the statements and it worked.

Posted a blog post here

like image 38
Ravindra Gullapalli Avatar answered Sep 22 '22 00:09

Ravindra Gullapalli