我想在java中的textArea中獲取控制檯的內容。如何將控制檯內容重定向到Java中的textArea?
例如,如果我們有這樣的代碼,
class FirstApp {
public static void main (String[] args){
System.out.println("Hello World");
}
}
,我想輸出的「Hello World」到textarea的,什麼的actionPerformed我必須選擇?
我想在java中的textArea中獲取控制檯的內容。如何將控制檯內容重定向到Java中的textArea?
例如,如果我們有這樣的代碼,
class FirstApp {
public static void main (String[] args){
System.out.println("Hello World");
}
}
,我想輸出的「Hello World」到textarea的,什麼的actionPerformed我必須選擇?
你必須System.out
重定向到一個定製的PrintStream
觀察到的子類,讓每個字符或線添加到該流可以更新textarea的內容(我想,這是一個AWT或Swing組件)
的PrintStream
實例可以用ByteArrayOutputStream
,這將收集的重定向System.out
之一的輸出方式,你可以通過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?如果沒有,那麼你必須。
我發現這個簡單的解決方案:
首先,你必須創建一個類來代替標準輸出:
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
這幾乎是完美的,但每當控制檯輸出textarea閃爍一堆。而不是追加,使用'textArea.setText(textArea.getText()+ String.valueOf((char)paramInt));'而不是像最初的'System.out'那樣閃爍和流動。 – 2017-04-26 01:22:24
您可能必須使用SwingUtilities.invokeLater()才能正常工作。 – 2017-08-24 12:16:20
太棒了! :) – Roman 2011-02-24 16:44:59