Java 将 ActionListener 添加到 JMenuItem

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20411725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:45:24  来源:igfitidea点击:

Adding an ActionListener to JMenuItem

javaswingactionlistenerjmenuitem

提问by liamslagle

I've just begun a simple GUI project, and while creating the menu bar, I ran into an error that I find to be inexplicable. I want to add an ActionListenerto a JMenuItemusing addActionListener, as I have done in the past. However, when I apply said method, Eclipse gives an error: "Syntax error on token "addActionListener", = expected after this token." My only thoughts are that perhaps addActionListeneris being interpreted as a property rather than a method... but I have used this method in the past so I do know that it works. I am unsure of how much code I should provide, so please let me know if I should edit in more.

我刚刚开始了一个简单的 GUI 项目,在创建菜单栏时,我遇到了一个莫名其妙的错误。我想添加一个ActionListener一个来JMenuItem使用addActionListener,因为我在过去所做的那样。但是,当我应用上述方法时,Eclipse 会出现错误:“令牌“addActionListener”上的语法错误,= 预期在此令牌之后。” 我唯一的想法是可能addActionListener被解释为属性而不是方法......但我过去使用过这种方法所以我知道它有效。我不确定我应该提供多少代码,所以如果我应该编辑更多,请告诉我。

package com.movethehead;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

@SuppressWarnings("serial")
public class Main extends JFrame {

    private final int W = 500;
    private final int H = 500;

    JMenuBar menuBar = new JMenuBar();

    JMenu file = new JMenu("File");
    JMenuItem exitItem = new JMenuItem("Exit");
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
                System.exit(0);
        }
    });

    JMenu headMenu = new JMenu("Heads");
    JMenu bgMenu = new JMenu("Backgrounds"); 

    public Main() {
        setTitle("Move the Head");
        setSize(W, H);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        add(new Pnl());
        setJMenuBar(menuBar);
    } // end constructor

    public static void main( String[] args ) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Main f = new Main();
                f.setVisible(true);
        }
    });
} // end main()
} // end Main

采纳答案by Jason

What it looks to me is you have

在我看来你有

JMenuBar menuBar = new JMenuBar();

JMenu file = new JMenu("File");
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ev) {
            System.exit(0);
    }
});

JMenu headMenu = new JMenu("Heads");

outside of any method definition and there is no way to call that code.

在任何方法定义之外,无法调用该代码。

Try this:

尝试这个:

public class Main extends JFrame{

  //initialize integer height/width values along with declaring 
  //Swing component variables
  private final int W = 500,
                    H = 500;

  private JMenu file, headMenu, bgMenu;
  private JMenuBar menuBar;
  private JMenuItem exitItem;

  //constructor
  public Main(){
    setTitle("Move the Head");
    setSize(W, H);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    initializeElements();

  }

  //Initializes the elements, this part is missing from your code above.
  public void initializeElements(){

    menuBar = new JMenuBar();
    file = new JMenu("File");
    exitItem = new JMenuItem("Exit");

    exitItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ev) {
        System.exit(0);
      }
    });

    headMenu = new JMenu("Heads");
    bgMenu = new JMenu("Backgrounds");

  }

  public static void main( String[] args ) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            Main f = new Main();
            f.setVisible(true);
        }
    });
  }
}

回答by MattPutnam

That code is fine. There's likely a syntax error on a nearby line that's messing up the parsing. Either the previous line, or something that screws up the declaration of exitItem.

那个代码没问题。附近的一行可能存在语法错误,导致解析混乱。无论是前一行,还是搞砸了exitItem.