2014-01-10 23 views
0

我正在學習構建GUI。現在我有一個按鈕。點擊按鈕後,程序運行一些計算。我想重定向輸出並將其添加到我創建的框架中。如何,我發現它只在我重新調整框架大小時纔會更新,但不會自動更新。有人會指出我如何自動做到這一點。代碼在Swing中,如何在計算後自動將結果加載到框架?

部分

jbtnAlpha.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent ae){ 
    Runnable runnable = new SVMthread(fnm_train,fnm_test,fnm_result,jfrm); 
      Thread t = new Thread(runnable); 
      t.start(); 
} 
    }); 

SVMthread在這裏被定義

public class SVMthread implements Runnable{ 
    private String fnm_train; 
    private String fnm_test; 
    private String fnm_result; 
    private JFrame jfrm; 
    SVMthread(String fnm_train,String fnm_test,String fnm_result,JFrame jfrm){ 
     this.fnm_train=fnm_train; 
     this.fnm_test=fnm_test; 
     this.fnm_result=fnm_result; 
     this.jfrm=jfrm; 
    } 
    public void run(){ 
     try { 
     jfrm.add(new ResultPanel()); 
     LibSVMTest.SVMrun(fnm_train,fnm_test,fnm_result); 
     } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 
} 

的ResultPanel是我重定向輸出

public class ResultPanel extends JPanel { 
    private JTextArea textArea = new JTextArea(15, 30); 
    private TextAreaOutputStream taOutputStream = new TextAreaOutputStream(
      textArea, "Test"); 

public ResultPanel() { 
     setLayout(new BorderLayout()); 
     add(new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
       JScrollPane.HORIZONTAL_SCROLLBAR_NEVER)); 
     System.setOut(new PrintStream(taOutputStream)); 
} 

} 

回答

-1

嘗試僅僅使用方法:

frame.revalidate(); 
+1

請刪除SwingUtilities.updateComponentTreeUI(frame);和frame.invalidate(); – mKorbel

+0

-1 for updateComponentTreeUI()。該方法用於由系統進行的LAF更改。您只需要在面板上重新驗證()並重新繪製組件,然後在可見的GUI上添加組件。 – camickr

2
  1. 決不讓大多數Swing中調用像你在做的後臺線程。那是抓住一隻老虎的尾巴 - 它會轉過身來咬你。
  2. 在從Swing容器中添加或刪除組件後,請在容器上調用revalidate()repaint()以使其重新佈置其組件並對其重新繪製。

編輯
關於你的評論:

我是新來這個。你能解釋一下你的背景是什麼意思嗎?對不起,如果這是一個愚蠢的問題。

Google:Swing的併發性。它會回答你的問題。

+0

您好,我是新來這個。你能解釋一下你的背景是什麼意思嗎?對不起,如果這是一個愚蠢的問題。 – Liu

+0

@Liu:見編輯。你已經接受了一個不能解決你的線程問題的答案。不好。 –

+0

謝謝。但我認爲上面的答案現在適合我。也許我的評論讓它有點混亂。我會刪除我的評論。不過,我很欣賞你指出的問題。 – Liu

相關問題