2013-09-24 40 views
0

我想在我的Java應用程序中創建一個控制檯(JTextPane),以顯示我的應用程序正在執行什麼操作。我曾經使用過不同的方法嘗試過很多次,但都失敗了......這是我的代碼的一部分。Java - 如何使用文檔在JTextPane中添加文本

MainClass

private final Form form; 

println("Downloading files..."); 

public void println(String line) 
{ 
     System.out.println(line); 
     form.getConsole().print(line); 
} 

表格(GUI)

private TabConsole console; 

tabbedPane.addTab("Console", console); 

public TabConsole getConsole() 
{ 
     return console; 
} 

TabConsole

public void print(final String line) { 
     if (!SwingUtilities.isEventDispatchThread()) { 
      SwingUtilities.invokeLater(new Runnable() 
      { 
      public void run() { 
       TabConsole.this.print(line); 
      } 
      }); 
      return; 
     } 

     Document document = this.console.getDocument(); 
     JScrollBar scrollBar = getVerticalScrollBar(); 
     boolean shouldScroll = false; 

     if (getViewport().getView() == this.console) { 
      shouldScroll = scrollBar.getValue() + scrollBar.getSize().getHeight() + MONOSPACED.getSize() * 4 > scrollBar.getMaximum(); 
     } 
     try 
     { 
      document.insertString(document.getLength(), line, null); 
     } catch (BadLocationException localBadLocationException) { 
     } 
     if (shouldScroll) 
      scrollBar.setValue(2147483647); 
     } 

那是什麼錯我的代碼?感謝您的幫助。

回答

0

重新拋出BadLocationException作爲RuntimeException,儘管代碼看起來正確。你遇到了什麼錯誤?

如果文本沒有顯示,您可能正在更新錯誤的文檔。確保您正在更新TextArea使用的文檔,或者您正在使用的任何文檔來顯示內容。

+0

雅,我也試過RuntimeException之前,我得到0錯誤。並且..我正在使用JTextPane而不是JTextArea – Jeremy

+0

您如何獲取對文檔的引用? –

+0

你是指什麼意思? – Jeremy

相關問題