0

Like the title says, I'm trying to assign a new color to 1 of 10 panels when that panel is clicked. So far the code looks like this.

public void setBoard()
{

    for(int i = 0; i < NUM; i++) {
        panel[i] = new JPanel();
        panel1.add(panel[i]);
        panel[i].setBackground(col1);
        panel[i].addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
            panel[i].setBackground(col3);
            }
        });

    }

    for(int y = 0; y < bombs; y++) {
        panel[randomNum()].setBackground(col2);
    }

}

panel1 is the overall container where all the panels go.

With this code here I am getting the error message that the local variable i must be final in order to reference it from an inner class. So how do I do that?

1 Answer 1

0

There is no need for the array. The event contains a reference to the component that generated the event:

public void mouseClicked(MouseEvent e) 
{
    Component panel = e.getComponent();
    panel.setBackground(col3);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.