user2210209
user2210209

Reputation: 17

Update new position for Jlabel

I'm new to Java and I am having some trouble with my assignment. I have a Panel containing 100 JLabels:

for(int i=0;i<100;i++)
{
    num[i] = new JLabel(""+i, JLabel.CENTER);
    mainPanel.add(num[i]);
}

And a button to set image icon for the label when clicked

public void actionPerformed(ActionEvent ae)
{
    int a = ran.nextInt(6) +1;//random number

    int b +=a;            
    if(b>=100)
    {
        b=99;
        num[b].setIcon(icon);
    }
    else
    {                
        num[b].setIcon(icon);              
    }
}

How can i remove the icon from the last position and update it to a new position?

Upvotes: 2

Views: 129

Answers (1)

sanbhat
sanbhat

Reputation: 17622

You can try to remember the index of the array of the label, for which you tried to set the icon.

For example-

int b = 0; // make b an instance variable

public void actionPerformed(ActionEvent ae)
{
    int a = ran.nextInt(6) +1;//random number
    num[b].setIcon(null); //remove the icon from from previously set label

    b=a;  //since b already has some value, b+=a might create unexpected result, hence just assigned a  
    if(b>=100)
    {
       b=99;
       num[b].setIcon(icon);
    }
    else
    {                
       num[b].setIcon(icon);
    }
}

Upvotes: 2

Related Questions