以编程方式添加后无法从JPanel删除JLabel [英] Unable to remove JLabel from JPanel after adding programmatically

查看:58
本文介绍了以编程方式添加后无法从JPanel删除JLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为LMSPanel的类,该类扩展了JPanel .此类具有以下两种方法:

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

添加方法效果很好,但是当我尝试调用removeInfoLbl时,Label仍然存在并且消失了.我已经尝试过repaint()以及在网上找到的各种组合,但仍然无法删除JLabel.

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.

我在做什么错了?

推荐答案

我很快尝试了一下,对我来说调用repaint()而不是rev​​alidate()即可.我认为标签没有消失的原因是面板没有重新粉刷.

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.

如果您始终只显示一个标签,为什么不使用像Andrew Thompson建议的那样使用setText().

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

这篇关于以编程方式添加后无法从JPanel删除JLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆