2013-04-23 109 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

相關問題