2013-04-23 59 views
2

我有一个名为LMSPanel的类,扩展了JPanel。这个类有以下两种方法:以编程方式添加后无法从JPanel删除JLabel

/** 
* 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标签保持和不走开。我试过repaint()和我在网上找到的各种组合,我仍然无法删除JLabel。

我在做什么错?

+3

这听起来像你有一个参考问题。当调用'justAddedLbl'时,你正在创建一个新的标签,这意味着如果它被多次调用,你只会引用最后添加的标签。从片段中不可能知道 – MadProgrammer 2013-04-23 04:49:04

+0

*“无法移除JLabel”*为什么不简单地使用'label.setText(“”);'? – 2013-04-23 04:58:40

+0

@MadProgrammer这也是我的想法,但每个方法只会为每个LMSPanel调用一次。所以我首先调用'justAddedLbl()',然后我总是直接调用'removeInfoLbl()'。而'infoLbl'是JLabel类型的私有字段。 – Ciwan 2013-04-23 12:49:13

回答

1

我赶紧想这一点,并调用重绘(),而不是重新验证()的工作原理为了我。我认为标签不会消失的原因是面板不会被重新粉刷。

如果你总是只显示一个标签,为什么不使用像Andrew Thompson建议的setText()。

+0

没有工作:(尝试repaint和setText()。 – Ciwan 2013-04-23 12:47:13

+0

我我的猜测是,Eclipse和个人电脑需要一个软件包,它可以帮助你解决问题,重新开始? :/ – Ciwan 2013-04-23 23:47:12

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

SetVisbile(真),这将是展示当前视图是可利用的。 那么试试这个..

+0

你真的认为整个'容器'是隐形的吗?如果'Container'不可见时,他将如何检测'JLabel'未被移除 – Robin 2013-04-23 07:25:17

+0

Jlabel已被移除,但容器仍显示j标签多次..所以如果我们再次使用Setvisble(true)它会显示当前的容器... – karthi 2013-04-23 08:20:28

+0

@Ciwan你有答案吗? – karthi 2013-04-23 09:24:04

相关问题