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

I want something like this but it complains that row is not final variable

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

I've tried other ways but I can't find how to pass those parameters(row, col) without error messages.



Solution 1:[1]

Try something like this:

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

Steffi

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steffi