2012-02-07 49 views
5

這裏是可運行的一段代碼來解釋問題 -從JPanel動態刪除組件

我可以刪除s1和s2,但不能刪除s3。
這似乎沒有MigLayout相關(我恰好在使用它),因爲我看到與默認佈局以及相同的行爲。


import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Dimension; 

import javax.swing.BorderFactory; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

import net.miginfocom.swing.MigLayout; 

public class MyFrame2 extends JFrame { 
    private JPanel main; 
    private JPanel s1; 
    private JPanel s2; 
    private JPanel s3; 

    public static void main(String[] args) throws InterruptedException { 
     MyFrame2 f = new MyFrame2(); 
     f.setVisible(true); 
     Thread.sleep(2000); //you can see all three panels for two seconds 

     f.main.remove(f.s1); 
     f.main.validate(); 
     Thread.sleep(2000); 
     f.main.remove(f.s2); 
     f.main.validate(); 
     Thread.sleep(2000); 
     f.main.remove(f.s3); 
     f.main.validate(); 
    } 

    public MyFrame2() { 
     main = new JPanel(); 

     main.setLayout(new MigLayout()); 

     main.add(new JLabel("Why does s3 not disappear?"),"w 200, h 100, wrap"); 

     s1 = new JPanel(); 
     s1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.GRAY,1),"s1")); 
     main.add(s1,"w 90%, h 300, wrap"); 

     s2 = new JPanel(); 
     s2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.GRAY,1),"s2")); 
     main.add(s2,"w 90%, h 300, wrap"); 

     s3 = new JPanel(); 
     s3.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.GRAY,1),"s3")); 
     main.add(s3,"w 90%, h 300, wrap"); 

     getContentPane().setLayout(new BorderLayout()); 
     getContentPane().add(main, BorderLayout.CENTER); 

     setSize(new Dimension(800, 600)); 

    } 
} 

回答

11

呼叫末,最後f.validate()後:

f.repaint(50L); 

當最後驗證不改變布點。

+0

謝謝。有用! (+1)。你能否詳細說明一下?爲什麼最後一次驗證不會更改佈局,而以前的所有驗證都是這樣做的? (很明顯,我沒有做太多的搖擺發展!) – 2012-02-07 00:43:40

+2

最後一次驗證*會改變佈局 - 你只是看不到它。在調用驗證之後,最後一個組件實際上已被刪除,但您需要重新繪製組件,以便查看此刪除的可視證明。 – 2012-02-07 00:56:50

+0

@HovercraftFullOfEels:謝謝。 – 2012-02-07 01:02:28

5

首先,Swing GUI的對象應當建立並在操作event dispatch thread,但你不能在美國東部時間睡覺。請使用javax.swing.Timer來標記時間,如圖所示here

+0

謝謝。這只是一個簡單的黑客來演示問題 – 2012-02-07 00:37:43

+1

@amol:兄弟組件受到影響,調整大小,並且必須在驗證中重繪。最後一個組件沒有觸發這種重繪。 (對不起這個評論的錯誤點) – 2012-02-07 18:35:59