我正在运行一个已编程的游戏,但我得到四个错误,这些错误都是javax.swing.AbstractButton类型中的方法addActionListener不适用于参数(DisplayArea)。我已确保所有内容都已正确导入,但我是java的新用户,可能会遗漏格式错误。
GUI.java
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.AbstractButton;
public class GUI extends JFrame {
private JButton bleft;
private JButton bRight;
private JButton bUp;
private JButton bDown;
private String[] colors;
private JComboBox colorList;
public DisplayArea display;
public GUI() {
super("Lab 4: Simple GUI");
setBackground(Color.white);
setSize(DisplayArea.SCREEN_SIZE, DisplayArea.SCREEN_SIZE + 50);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Initializes the variable
bleft = new JButton("Left");
bRight = new JButton("Right");
bUp = new JButton("Up");
bDown = new JButton("Down");
colors = new String []{"red", "black", "blue", "green"};
colorList = new JComboBox(colors);
display = new DisplayArea();
add(display, BorderLayout.CENTER);
JPanel buttonpanel = new JPanel();
buttonpanel.add(bleft);
buttonpanel.add(bRight);
buttonpanel.add(bUp);
buttonpanel.add(bDown);
buttonpanel.add(colorList);
add(buttonpanel, BorderLayout.SOUTH);
bleft.addActionListener(display); //ERROR
bRight.addActionListener(display); //ERROR
bUp.addActionListener(display); //ERROR
bDown.addActionListener(display); //ERROR
}
public static void main(String [] args) {
GUI gui = new GUI();
gui.setVisible(true);
}
}
DisplayArea.java
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListene
public class DisplayArea extends JPanel {
public static final int SCREEN_SIZE = 500;
public static final int DELTA = 10;
private Color currentColor;
private Point center;
public DisplayArea(){
setSize(SCREEN_SIZE, SCREEN_SIZE);
center = new Point(SCREEN_SIZE/2, SCREEN_SIZE/2);
currentColor = Color.RED;
}
@Override
public void paint(Graphics g){
super.paint(g);
g.setColor(currentColor);
g.fillOval(center.x, center.y, 10, 10);
}
public void actionPerformed (ActionEvent e){
if(e.getSource() instanceof JButton) {
String cmd = e.getActionCommand();
if(cmd.equals("Left")){
center.x = center.x - DELTA;
} else if (cmd.equals("Right")){
center.x = center.x + DELTA;
} else if (cmd.equals("Up")){
center.y = center.y + DELTA;
} else if (cmd.equals("Down")){
center.y = center.y - DELTA;
}
}
repaint();
}
}
答案 0 :(得分:0)
正如@LuxxMiner所指出的,传递给addActionListener
的值必须是ActionListener
类型。一种选择是声明匿名内部类,如下所示:
bleft.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
//Do stuff here
}
});