Re: [NetBeans]changing menuitems



Daniel Moyne wrote:

- in some methods :
menuItem1=jMenuItem1; //jMenuItem is declared as private by NetBeans
instance = this;

- these 2 methods :
public static GenListView getInstance() {
return instance;
}

This is pretty ugly. Returning a refernce to a private field? Ouch, this totally breaks encapsulation


public void enableMenuItem(JMenuItem menuItem) {
menuItem.setEnabled(true);
}

Fundamentally what you want to do is

public class GenListView extends JFrame // or whatever
{
private JMenuItem menu1;
// ...
public void setEnabledMenu1( boolean enabled ) {
menu1.setEnabled( enabled );
}

}

So now you are free to change the implementation of "menu1" to anything you want, and the caller of "setEnabledMenu1" is none the wiser. This is basic encapsulation.

Where this gets tedious is if you have many, many menu items that need methods so you can set their state. Here is where you can get a little tricky to save yourself work.

First, consider breaking the functionality into interfaces so you aren't stuck with this "GenListView" object forever and ever, and you can move the menu item functionality to a different class if you need to. This also aids you writing a test harness.

For "something tricky" I don't have any great ideas. One simple idea is just to invent a little string based system where you can update menu items by name:

public class GenListView extends JFrame // or whatever
implements MyMenuEnabling
{
private Map<String, JMenuItem> menuList;
// ...
@Override
public void setEnabledMenuByName(
String name, boolean enabled ) {
menuList.get( name ).setEnabled( enabled );
}

}

Now you can add as many menu items as you like, and just use strings to identify them. This can give you a lot of flexibility, since you are now very, very loosely coupled to the menu code. You can also push errors (spelled a name wrong) from compile time to runtime, which can make debugging harder. So it's important not to go completely bananas with this sort of loose coupling. Perhaps an enum would be a good intermediary between Strings and explicit one-per-menu method calls.


Note: code not complete, or even syntax checked.

.