如何在for循环中设置多个JPanel点击事件?

How to set multiple JPanel Click Events in a for loop?

for(int row=0; row<3; ++row) {
    for(int col=0; col<3; ++col) {
        JPanel panel = new JPanel();
        panel.addMouseListener((MouseListener) new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println(String.valueOf(row) + " " + String.valueOf(col));
            }
        });
        this.add(panel);
    }
}

我想要这样的东西,但它抱怨行不是最终变量

Local variable row defined in an enclosing scope must be final or effectively final

我试过其他方法,但我找不到如何在没有错误消息的情况下传递这些参数(行、列)。

尝试这样的事情:

    private int row;
    private int col;
    
    public void Panel(){
        for(row=0; row<3; ++row) {
            for(col=0; col<3; ++col) {
                JPanel panel = new JPanel();
                panel.addMouseListener((MouseListener) new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        System.out.println(String.valueOf(row) + " " + String.valueOf(col));
                    }
                });
                this.add(panel);
            }
        }
    }

史蒂菲