简体   繁体   English

JMenuItem构造方法不接受操作

[英]JMenuItem Constructor Not Accepting Action

JMenuItem has the following constructor: (Source: GrepCode ) JMenuItem具有以下构造函数:(来源: 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. 我按了JMenuItem ,甚至没有调用actionPerformed()。

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 . 然后,添加菜单项,它出现在JMenu

Somehow it is different when I'm dealing with Action s or constructors. 当我处理Action或构造函数时,它有所不同。 Could somebody explain the difference? 有人可以解释差异吗?

It seems like from what you've posted that you haven't defined your Action when you initialize the JMenuItem. 从您发布的内容来看,初始化JMenuItem时似乎尚未定义Action。 Therefore, because you are passing in null, no action is being triggered 因此,由于您传递的是null,因此不会触发任何操作

someButton is initialized before someAction , so you are passing null to the JMenuItem . someButtonsomeAction之前初始化,因此您将null传递给JMenuItem Initialize someButton after you have created someAction and everything will go fine. 创建someAction之后,初始化someButton ,一切都会顺利进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM