2012-12-01 44 views
3

我正在努力與Java GUI - 感謝您提前提供任何幫助!我有一個JFrame中,我有幾個組成部分:按鈕(一個JButton)觸發動作監聽者,補償這是一個組件我試着用它的組件更換JScrollPane的(它不事關組件是什麼類型的,可以是文本字段,表格或其他)。Java - 替換JFrame中的組件

我想觸發一個動作 - 刪除組件,放置在同一個地方被刪除的一個新的和重新繪製窗口(我用它來顯示不同類型的文本字段和JTable中的)。這是我有:

JScrollPane sp = new JScrollPane(comp); 
this.add(sp, BorderLayout.CENTER); 
//this works so far - first time I display this is ok! 

private void replace() { 
comp = new Component(...); //name and type of the components is not important 
sp = new JSCrollPane(comp); 
this.remove(sp); //remove old component 
add(sp, BorderLayout.CENTER); 
repaint(); 
revalidate(); 
} 

爲什麼不功能替換工作?它沒有做任何事情(它改變了邏輯組件,所以如果我訪問comp的內容,它會刷新,但它仍然顯示舊的)。

我寫它有點象徵性,導致我的代碼很長...感謝您的幫助! 編輯:在我的代碼中忘了一行..

回答

5

您沒有必要像嘗試刪除滾動窗格一樣。

要更改滾動窗格上顯示簡單地使該呼叫的組分:

sp.setViewportView(new Component(...)); 

該呼叫後,舊的組件從視圖中移除並且用新部件更換。

所以,你的代碼看起來有點像這樣:

JScrollPane sp = new JScrollPane(comp); 
this.add(sp, BorderLayout.CENTER); 

private void replace() { 
    comp = new Component(...); //name and type of the components is not important 
    sp.setViewportView(comp); 
} 
+0

這很好地解決了我的問題,謝謝! – Smajl

+0

沒有biggie哥們! ;-) –

2

從代碼的外觀,你添加的第一個滾動窗格(this.add)是卸下了一個(this.remove)不同。測試從remove中返回的布爾值,看它是否真的被刪除。我想你會發現它不是。

+0

這是錯誤的,我應該先刪除sp,然後創建它並再次添加它... – Smajl

1

有在this board的解決方案:

jpanel.remove(component); //remove component from your jpanel in this case i used jpanel 
jpanel.revalidate(); 
jframe.repaint();//repaint a JFrame jframe in this case 

to add: 
jpanel.add(component); //add component to jpanel in this case i used jpanel 
jpanel.revalidate(); 
jframe.repaint();//repaint a JFrame jframe in this case 

看看這對你的作品。沒有嘗試過自己...