2011-02-24 134 views
13

我想在java中的textArea中獲取控制檯的內容。如何將控制檯內容重定向到Java中的textArea?

例如,如果我們有這樣的代碼,

class FirstApp { 
    public static void main (String[] args){ 
     System.out.println("Hello World"); 
    } 
} 

,我想輸出的「Hello World」到textarea的,什麼的actionPerformed我必須選擇?

+5

太棒了! :) – Roman 2011-02-24 16:44:59

回答

1

你必須System.out重定向到一個定製的PrintStream觀察到的子類,讓每個字符或線添加到該流可以更新textarea的內容(我想,這是一個AWT或Swing組件)

PrintStream實例可以用ByteArrayOutputStream,這將收集的重定向System.out

2

之一的輸出方式,你可以通過System OutputStream設置爲PipedOutputStream做到這一點,並連接到你讀一個PipedInputStream創建從添加文本到您的組件,例如

PipedOutputStream pOut = new PipedOutputStream(); 
System.setOut(new PrintStream(pOut)); 
PipedInputStream pIn = new PipedInputStream(pOut); 
BufferedReader reader = new BufferedReader(new InputStreamReader(pIn)); 

Have you look at the following link?如果沒有,那麼你必須。

8

Message Console示出了用於此的解決方案。

+0

非常有用的鏈接! – 2015-06-11 08:30:35

+0

又是純金。 – gdbj 2017-05-12 19:16:44

2

我發現這個簡單的解決方案:

首先,你必須創建一個類來代替標準輸出:

public class CustomOutputStream extends OutputStream { 
    private JTextArea textArea; 

    public CustomOutputStream(JTextArea textArea) { 
     this.textArea = textArea; 
    } 

    @Override 
    public void write(int b) throws IOException { 
     // redirects data to the text area 
     textArea.append(String.valueOf((char)b)); 
     // scrolls the text area to the end of data 
     textArea.setCaretPosition(textArea.getDocument().getLength()); 
     // keeps the textArea up to date 
     textArea.update(textArea.getGraphics()); 
    } 
} 

然後更換標準如下:

JTextArea textArea = new JTextArea(50, 10); 
PrintStream printStream = new PrintStream(new CustomOutputStream(textArea)); 
System.setOut(printStream); 
System.setErr(printStream); 

的問題是所有的輸出只會在文本區域顯示。樣本來源:http://www.codejava.net/java-se/swing/redirect-standard-output-streams-to-jtextarea

+0

這幾乎是完美的,但每當控制檯輸出textarea閃爍一堆。而不是追加,使用'textArea.setText(textArea.getText()+ String.valueOf((char)paramInt));'而不是像最初的'System.out'那樣閃爍和流動。 – 2017-04-26 01:22:24

+0

您可能必須使用SwingUtilities.invokeLater()才能正常工作。 – 2017-08-24 12:16:20

相關問題