1 回答

TA貢獻1818條經驗 獲得超7個贊
我快速設置了一個沙箱,并使用 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使其起作用。問候
添加回答
舉報