简体   繁体   中英

How to set new background color on a panel when that panel is clicked?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM