Question

I'm practicing my gui skills with Java and I have been doing menus and menu bars. They make sense to me just fine but I have a question about where I can learn more about them.

The basic menus I have done, the ActionListener function actionPerformed has to be in the same class as the menu, and the item that the menu is changing also has to be in the class as the menu.

What If I want to have a menu that affects a JPanel that is created by a constructor from another class and placed in my frame.. I'm not sure how the menu can change components of it.

Any tips, hints or sites you guys have found helpful would be great, thanks in advance.

Was it helpful?

Solution

I find it useful to wrap menubar actions in an Action object. This encapsulates:

  1. The name and icon of the action
  2. If it is enabled or disabled
  3. (for a checkbox action) if it is selected
  4. The keyboard shortcut for the action
  5. The implementation of the action listener

You would define a subclass of AbstractAction in the class whose data that action acts on. Then define a getter for that action so that your menu building code can get it. You can add the Action directly to a menu - a MenuItem is constructed automatically for it.

The other advantage of actions is that that same action can be used in a button, toolbar, etc.

class ModelClass {
   int value;
   Action incAction = new AbstractAction("Increment") {
      public void actionPerformed() {
         value++;
         setEnabled(value < 10);
      }
   };

   public Action getIncAction() {
      return incAction;
   }
}

class UIClass {
   void buildMenu() {
      JMenu menu = new JMenu("Model");
      menu.add(model.getIncAction());
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top