0

JMenuItem has the following constructor: (Source: GrepCode)

public JMenuItem(Action a) {
    this();
    setAction(a);
}

However, when my code has

import javax.swing.*;
import java.awt.event.ActionEvent;

public class ActionTest extends JApplet {

    private final JFrame frame = new JFrame("Title");
    private final JMenuBar menuBar = new JMenuBar();
    private final JMenu fileMenu = new JMenu("File");
    protected Action someAction;
    private JMenuItem someButton = new JMenuItem(someAction);

    public ActionTest() {}

    @Override
    public final void init() {
        frame.setJMenuBar(menuBar);
        menuBar.add(fileMenu);
        fileMenu.add(someButton);
        someButton.setText("Button");
        someAction = new AbstractAction("Title") {

            public void actionPerformed(ActionEvent event) {
                //do stuff
            }
        };
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        JApplet applet = new ActionTest();
        applet.init();
    }
}

and I press the JMenuItem, actionPerformed() is not even called.

Is this a bug, or is my approach completely wrong?

After doing more research, I find that this is the method that it eventually boils down to. It seems to implement a shallow copy, which should simply point to the same memory block that I gave it in the constructor.

The same thing should be occurring when I add the file menu to the menu bar. When the file menu is added, it references the memory block. Whatever is inside that memory block is what is displayed. Then, I add the menu item and it appears in the JMenu.

Somehow it is different when I'm dealing with Actions or constructors. Could somebody explain the difference?

gobernador
  • 5,659
  • 3
  • 32
  • 51

2 Answers2

3

It seems like from what you've posted that you haven't defined your Action when you initialize the JMenuItem. Therefore, because you are passing in null, no action is being triggered

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
1

someButton is initialized before someAction, so you are passing null to the JMenuItem. Initialize someButton after you have created someAction and everything will go fine.

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117