【发布时间】:2019-09-19 11:10:08
【问题描述】:
我的编程生涯刚刚起步 :) 并为自己设定了编写简单国际象棋程序的目标。我还没有实现任何逻辑。
不幸的是,我使用以下代码收到此错误消息:
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem
但是,我仍然可以正常启动程序并获得具有棋盘图案的场地。只有当我按下按钮时,才会出现上述错误。
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Chess extends JFrame {
//Define variables
private JButton[][] buttons = new JButton[8][8];
private Container board;
private int size = 600;
// Main class opens constructor of Chess
public static void main(String[] args) {
new Chess();
}
// constructor
public Chess() {
//initialize the Chessboard
board = getContentPane();
board.setLayout(new GridLayout(8, 8));
setSize(size, size);
setVisible(true);
//Add buttons to the frame
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) {
buttons[y][x] = new JButton();
board.add(buttons[y][x]);
buttons[y][x].setBorderPainted(false);
//color buttons in the checkerboard pattern
if ((y + x) % 2 != 0) {
buttons[y][x].setBackground(new Color(201, 166, 113));
} else {
buttons[y][x].setBackground(Color.WHITE);
}
//Add event listener
ActionListener buttonListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
pressedButton(y,x);
}
};
buttons[y][x].addActionListener(buttonListener);
}
}
}
public void pressedButton(int y, int x) {
System.out.println(x + " " + y);
}
}
【问题讨论】:
-
该错误意味着您在对程序进行了一些更改后还没有编译您的代码。现在运行时,它将使用编译前的旧版本,并且一旦您执行未正确编译的操作,它将立即失败。我不确定您使用的是什么 IDE,因为大多数 IDE 会在您保存后立即重新编译(尽管有时需要手动构建)?尝试重新编译程序并重新启动。然后它应该可以工作,或者给出一个更有意义的错误。
-
你也可以在for循环外声明
buttonListener。 -
@KevinCruijssen 没有。那不是问题所在。当我按下按钮时,我重新编译并仍然出现同样的错误。
-
@Niklas 也不起作用。我希望每个按钮都返回它的坐标。如果没有 for 循环,唯一的选择是编写 64 个单独的事件监听器
标签: java swing event-handling awt