lia*_*gle 1 java swing actionlistener jmenuitem
我刚刚开始了一个简单的 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
Run Code Online (Sandbox Code Playgroud)
在我看来你有
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");
Run Code Online (Sandbox Code Playgroud)
在任何方法定义之外,无法调用该代码。
尝试这个:
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);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)