我有一個名爲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。
我在做什麼錯?
這聽起來像你有一個參考問題。當調用'justAddedLbl'時,你正在創建一個新的標籤,這意味着如果它被多次調用,你只會引用最後添加的標籤。從片段中不可能知道 – MadProgrammer 2013-04-23 04:49:04
*「無法移除JLabel」*爲什麼不簡單地使用'label.setText(「」);'? – 2013-04-23 04:58:40
@MadProgrammer這也是我的想法,但每個方法只會爲每個LMSPanel調用一次。所以我首先調用'justAddedLbl()',然後我總是直接調用'removeInfoLbl()'。而'infoLbl'是JLabel類型的私有字段。 – Ciwan 2013-04-23 12:49:13