Unable to remove JLabel from JPanel after adding programmatically

て烟熏妆下的殇ゞ 提交于 2020-01-30 07:58:49

问题


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?


回答1:


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.




回答2:


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

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



来源:https://stackoverflow.com/questions/16161083/unable-to-remove-jlabel-from-jpanel-after-adding-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!