[英]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.