Note that there are some explanatory texts on larger screens.

plurals
  1. PORedirecting System.out to JTextPane
    primarykey
    data
    text
    <p>I have a class (shown below) that extends <code>JPanel</code> and contains a <code>JTextPane</code>. I want to redirect <code>System.out</code> and <code>System.err</code> to my <code>JTextPane</code>. My class does not seem to work. When I run it, it does redirect the system prints, but they do not print to my <code>JTextPane</code>. Please help!</p> <p><strong>Note:</strong> The calls are only redirected when the application launches. But any time after launch, the <code>System.out</code> calls are not redirected to the <code>JTextPane</code>. (ie, if I place a <code>System.out.prinln();</code> in the class, it will be called, but if it is placed in a <code>actionListener</code> for later use, it does not redirect).</p> <pre><code>public class OSXConsole extends JPanel { public static final long serialVersionUID = 21362469L; private JTextPane textPane; private PipedOutputStream pipeOut; private PipedInputStream pipeIn; public OSXConsole() { super(new BorderLayout()); textPane = new JTextPane(); this.add(textPane, BorderLayout.CENTER); redirectSystemStreams(); textPane.setBackground(Color.GRAY); textPane.setBorder(new EmptyBorder(5, 5, 5, 5)); } 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)); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload