[英]Add ActionListener() to JButton-Array in Java: compilation error
我正处于我的编程生涯的开始:) 并为自己设定了编写一个简单的国际象棋程序的目标。 我还没有实现任何逻辑。
不幸的是,我使用以下代码收到此错误消息: 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);
}
}
我快速设置了一个沙箱,并使用 java 版本 11 和语言级别 11 让它工作。
您不能在 ActionListener 中传递x
或y
。
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) {
int tx = x;
int ty = y;
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(ty, tx);
}
};
buttons[y][x].addActionListener(buttonListener);
}
}
请注意添加的tx
和ty
使其工作。 问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.