Home > Software engineering >  How to set multiple JPanel Click Events in a for loop?
How to set multiple JPanel Click Events in a for loop?

Time:04-12

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.

CodePudding user response:

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

  • Related