【发布时间】:2013-04-23 04:39:27
【问题描述】:
我有一个名为 LMSPanel 的类,它扩展了 JPanel。该类有以下两种方法:
/**
* 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。
我做错了什么?
【问题讨论】:
-
听起来您有参考问题。当调用
justAddedLbl时,您正在创建一个新标签,这意味着如果多次调用它,您将只能引用最后添加的标签。从 sn-p 不可能确定 -
“无法删除 JLabel” 为什么不直接使用
label.setText("");? -
@MadProgrammer 我也是这么想的,但是每个 LMSPanel 的每个方法只调用一次。所以我首先打电话给
justAddedLbl(),然后我总是直接打电话给removeInfoLbl()。而infoLbl是 JLabel 类型的私有字段。 -
@ciwan 没有可运行的示例,就不可能知道。可以尝试更改标签的文本以确保(而不是尝试删除它)
-
我尝试更改文本。那也没有用。我的猜测是它一定是一个参考问题,但不知道为什么。