The example below shown how to do it with JTextPane. For JTextArea, it's quite simpler, just call JTextArea.append()
This is useful when you spawn external process from a Swing application and want to see its output in your own text component.
Jan 04 2009: Revised regarding Eric Burke's comment below.
JTextPane version:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 |
private void updateTextPane( final String text) { SwingUtilities.invokeLater( new Runnable() { public void run() { Document doc = textPane.getDocument(); try { doc.insertString(doc.getLength(), text, null ); } catch (BadLocationException e) { throw new RuntimeException(e); } textPane.setCaretPosition(doc.getLength() - 1 ); } }); } private void redirectSystemStreams() { OutputStream out = new OutputStream() { @Override public void write( final int b) throws IOException { updateTextPane(String.valueOf(( char ) b)); } @Override public void write( byte [] b, int off, int len) throws IOException { updateTextPane( new String(b, off, len)); } @Override public void write( byte [] b) throws IOException { write(b, 0 , b.length); } }; System.setOut( new PrintStream(out, true )); System.setErr( new PrintStream(out, true )); } |
JTextArea version:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 |
private void updateTextArea( final String text) { SwingUtilities.invokeLater( new Runnable() { public void run() { textArea.append(text); } }); } private void redirectSystemStreams() { OutputStream out = new OutputStream() { @Override public void write( int b) throws IOException { updateTextArea(String.valueOf(( char ) b)); } @Override public void write( byte [] b, int off, int len) throws IOException { updateTextArea( new String(b, off, len)); } @Override public void write( byte [] b) throws IOException { write(b, 0 , b.length); } }; System.setOut( new PrintStream(out, true )); System.setErr( new PrintStream(out, true )); } |