Hi, I have a menu system setup as follows:
Code:
public JMenuBar createMenuBar()
{
//Create the Commands menu
JMenu commands = new JMenu("Commands");
commands.setMnemonic(KeyEvent.VK_C);
commands.add(makeMenuItem("Connect", "Connect."));
commands.add(makeMenuItem("Disconnect", "Disconnect."));
commands.add(makeMenuItem("Send Message", "Send a message
commands.setToolTipText("What do you want to do today?");
menuBar.add(commands);
return menuBar;
}
private JMenuItem makeMenuItem(String label, String tootip)
{
JMenuItem item = new JMenuItem(label);
item.addActionListener (this);
item.setToolTipText(tootip);
return item;
}
My question is this. I want to disable the "Send Message" menu item. How do I go about this?
In advance thanks for the help.
The thing is that I need to enable and disable menu items as the program is running and as you can see this is where my problems begin.
How do I disable and enable menu items as the program is running bearing in mind that I do not want to restructure my current code if I can help it.
Thanks.
you need to keep a reference of the item you want to modify. it works like this:
MenuItem send = createMenuItem("Send Message", "Whatever");
menu.addItem(send);
//later in code
send.setEnabled(false/true);
-
but you HAVE to keep a reference for yourself.. think of java objects like balls, with string attached.. when you say createMenuItem, that creates a ball, and gives it to the menu, which attaches some string to it (to tether it to the menu otherwise the garbage collector will take the ball away)
thus, only the menu has a hold on the ball.. instead, you create it, you tether a string to it with:
MenuItem mi = create...
"mi" is the name of your string, and it gets you access to the ball..
when you add mi to the menu.. the menu follows mi (string) to the ball (object) and attaches its own reference.. now you have a string tether, and the menu has a tether
----
note when i say string, i mean like rope, twine, cotton.. not string as in:
String myString = "hello world"
just a little tip to help you think of java objects in memory, all tied together with string.. cut all strings to an object and it floats away, and garbage collector comes along..
note that any reference to a particular menuitem that you keep, will probably need to be a class-wide reference
Thanks, just looks like I will have to make the menu items that i want to enable/disable global.