我有一个类(如下所示),它扩展了JPanel
并包含一个JTextPane
。我想将System.out
和System.err
重定向到我的JTextPane
。我的班似乎没有工作。当我运行它时,它会重定向系统打印,但它们不打印到我的JTextPane
。请帮忙!将System.out重定向到JTextPane
注意:调用只在应用程序启动时重定向。但是在启动后的任何时间,System.out
调用都不会重定向到JTextPane
。 (即,如果我在课堂中放置了System.out.prinln();
,它将被调用,但是如果将它放置在actionListener
中供以后使用,则不会重定向)。
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));
}
}
我删除了我的答案,因为它是错误的。 – jjnguy 2010-12-14 21:06:23
你是否看到一些呼叫被重定向? – jjnguy 2010-12-14 21:06:52
只有OSXConsole类内的调用才会打印到JTextPane。 – Jakir00 2010-12-14 21:08:38