J86
J86

Reputation: 15237

Unable to remove JLabel from JPanel after adding programmatically

I have a class called LMSPanel that extends JPanel. This class has the two following methods:

/**
 * A method to add an informative temporary label to the Panel until
 * the second Sensor is added.
 * 
 * @param zoneid   - The ID of the Zone.
 * @param sensorid - The ID of the Sensor.
 */
public void justAddedLbl(String zoneid, String sensorid)
{
    infoLbl = new JLabel("Sensor: " + zoneid + sensorid + " added. Please Add 2nd Sensor.");
    add(infoLbl);
    revalidate();
}

/**
 * A method to remove the temporary informative label.
 * Only called when second sensor has been added.
 */
public void removeInfoLbl()
{
    remove(infoLbl);
    revalidate();
}

The adding method works fine, but when I try and call the removeInfoLbl the Label stays and does go away. I've tried repaint() and all sorts of combinations I found online and I still cannot remove the JLabel.

What am I doing wrong?

Upvotes: 2

Views: 1353

Answers (2)

sreejit
sreejit

Reputation: 131

I just quickly tried this, and calling repaint() instead of revalidate() works for me. I think the reason the label is not going away, is that the panel is not getting repainted.

If you are always going to display just one label, why not use setText() like Andrew Thompson suggested.

Upvotes: 1

karthi
karthi

Reputation: 1099

  public void removeInfoLbl()
    {
  remove(infoLbl);
  revalidate();
  repaint();
  SetVisible(true);
 }

SetVisbile(true) this will be show your current view which is available.. So try this..

Upvotes: 0

Related Questions