0

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.

1
  • 1
    Try this Swing Menus Commented Jan 9, 2012 at 17:35

1 Answer 1

3

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()); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

I don't suppose you have a reference or an example you could show me? I looked into the documentation for AbstractAction and ActionListener but I'm not sure how your idea is implemented.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.