将 ActionListener() 添加到 Java 中的 JButton-Array:编译错误

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 中传递 xy

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);

            }
        }

注意添加的 txty 使它起作用。 问候