2015-05-05 47 views
1

我想要做的是在過程發生時顯示帶有進度欄的新面板。JPanel直到代碼後才顯示

我的代碼如下:

case "GoButton": 
    cards.show(this, "pp"); 
    this.test(); 
    cards.show(this, "panel1"); 
    break; 

這是一個actionPerformed方法

但是當我運行它只是忽略了第一cards.show程序,它執行test代碼,然後它執行秒cards.show

我還會爲你提供其餘的代碼,以防你需要它

public CreatePanel(JFrame frame) { 
     ext = new ArrayList<>(); 
     files = new ArrayList<>(); 

     this.mainWindow = frame; 
     this.setSize(256, 256); 
     cards = new CardLayout(); 
     this.setLayout(cards); 

     panel1 = new JPanel(null); 
     createPanel1(panel1); 
     this.add(panel1, "panel1"); 

     panel2 = new JPanel(null); 
     createPanel2(panel2); 
     this.add(panel2, "panel2"); 

     panel3 = new JPanel(null); 
     createPanel3(panel3); 
     this.add(panel3, "pp"); 

     cards.show(this, "panel1"); 
    } 

public class ProgressPanel { 
    private static JPanel panel; 
    private static JProgressBar progressBar; 
    private static int progress; 

    public static JPanel createProgressPanel(){ 
     ProgressPanel.panel = new JPanel(null); 
     ProgressPanel.initPanel(); 
     return ProgressPanel.panel; 
    } 

    private static void initPanel(){ 
     panel.setLayout(new GridBagLayout()); 
     GridBagConstraints c = new GridBagConstraints(); 

     progressBar = new JProgressBar(0, 100); 
     progressBar.setValue(progress); 
     progressBar.setStringPainted(true); 
     panel.add(progressBar, c); 
    } 

    public static void updateProgress(int x){ 
     ProgressPanel.progress += x; 
    } 

    public void resetProgress(){ 
     this.progress = 0; 
    } 
} 
+0

'panel3 = new JPanel(null);'Java GUIs必須在不同的操作系統上工作',屏幕大小,屏幕分辨率等使用不同語言環境中的不同PLAF。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。 –

回答

5

你可能喜歡這裏的問題:this.test();。我敢打賭,這種方法會調用長時間運行的代碼,並且由於它在Swing事件線程上被調用,所以它將阻止您的GUI自動更新並實際上完全凍結GUI。解決方案:爲長時間運行的任務使用SwingWorker或其他後臺線程。請看Concurrency in Swing

請注意,如果你使用的SwingWorker,你需要使用時,後臺線程已經完成,並通知任何一個PropertyChangeListener或done()方法,它的時間打電話cards.show(this, "panel1");。我自己,我會爲我的SwingWorker添加一個PropertyChangeListener,既然這樣,我既可以監聽監聽器的完成,也可以監聽worker的progress屬性中的更改,然後使用該值設置我的JProgressBar的值。

+0

嗯,我會研究它,我會明天應用更改,讓你知道。感謝您的快速回復! –

相關問題