2013-07-10 34 views
2

我想做一個Java應用程序,並使用Swing從用戶獲取一些輸入數據後,我開始運行我的程序的主要計算塊(不是主要方法只是爲了清楚)。雖然此方法正在運行,但我想按照「請稍等...不要觸摸任何東西」的方式顯示一些內容。但問題是,我用來顯示此內容的JPanel在方法持續時間內全黑這是在做計算正在運行。我試圖在方法的中間打印JLabel.getText(),並按照它應該出來的方式輸出。任何想法爲什麼文本不會出現。以下是我的代碼。JLabel說「請等待」沒有運行

JFrame toDisplay = new JFrame("Please Wait"); 
    toDisplay.setAlwaysOnTop(true); 
    toDisplay.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    toDisplay.setVisible(true); 
    toDisplay.setLayout(new FlowLayout()); 
    toDisplay.setSize(300,200); 
    toDisplay.setLocation((int)dimension.getWidth()/3, (int)dimension.getHeight()/3); 

    JLabel message = new JLabel("<html>CheapTix is currently running<br /> please do not close this box or open the file <br /> Destinations.txt <br /> until instructed to do so</html>"); 
    toDisplay.add(message,BorderLayout.CENTER); 

接下來是我的程序運行的主體。我曾嘗試將toDisplay.add(消息)放在我的程序的主要部分內,但這似乎也不起作用。 任何幫助,我將不勝感激。

+1

退房[此示例](http://stackoverflow.com/questions/16810121/why-does-my-jframe-not-show-my-label/16825813#16825813),用於一個可能的解決方案 – MadProgrammer

回答

5

您的問題是由於Swing併發。您正在Swing事件線程上運行一個長時間運行的進程,這會阻止事件線程進行繪製。解決方案:使用後臺線程,如SwingWorker。

更多關於此,請參閱Concurrency in Swing

此外,

JFrame toDisplay = new JFrame("Please Wait"); 
    toDisplay.setAlwaysOnTop(true); 
    toDisplay.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    toDisplay.setVisible(true); 
    toDisplay.setLayout(new FlowLayout()); 
    toDisplay.setSize(300,200); 
    toDisplay.setLocation((int)dimension.getWidth()/3, (int)dimension.getHeight()/3); 

    JLabel message = new JLabel("<html>CheapTix is currently running<br /> 
     please do not close this box or open the file <br /> 
     Destinations.txt <br /> 
     until instructed to do so</html>"); 
    toDisplay.add(message,BorderLayout.CENTER); 
  • 這看起來好像你顯示一個二級窗口作爲一個JFrame這是不是一個好主意。而是使用一個JDialog。
  • 不要設置組件的大小,而是讓它們自己調整大小。
+0

大謝謝,我不明白,但是因爲我的方法需要用戶的輸入,我怎樣才能使用不帶參數的doInBackGround()方法? – DavidR

+1

@DavidR:參數可以通過給SwingWorker類的構造函數傳遞給SwingWorker。 –

+0

我終於搞定了!如果我告訴過你,我會說謊,但是我很感謝你的幫助。你能否澄清你的編輯。我不明白作爲JFrame的輔助窗口是什麼意思,當我沒有設置我的組件的大小,他們最終微小,我不得不手動擴大他們看到他們的內容。 – DavidR