【发布时间】:2016-02-12 17:40:26
【问题描述】:
我正在运行一个已编程的游戏,但我收到四个错误,它们都是 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();
}
}
【问题讨论】:
-
DisplayArea应该实现ActionListener。 (即public class DisplayArea extends JPanel implements ActionListener)将@Override注解放在您希望下次重写的方法之上,以避免此类错误。 -
感谢您解决了问题