我在网上找到了一个示例,代码如下所示。 TextAreaOutputStream在TestAreaOutputStreamText中实例化。我不明白在这个例子中如何调用write方法。这个例子是如何工作的?
public class TextAreaOutputStream extends OutputStream {
private final JTextArea textArea;
private final StringBuilder sb = new StringBuilder();
private String title;
public TextAreaOutputStream(final JTextArea textArea, String title) {
this.textArea = textArea;
this.title = title;
//sb.append(title + "> ");
}
@Override
public void flush() {
//this.textArea.setText("");
}
@Override
public void close() {
}
@Override
public void write(int b) throws IOException {
if (b == '\r')
return;
if (b == '\n') {
final String text = sb.toString() + "\n";
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
sb.setLength(0);
//sb.append(title + "> ");
return;
}
sb.append((char) b);
}
}
public class TextAreaOutputStreamTest extends JPanel {
private JTextArea textArea = new JTextArea(15, 30);
private TextAreaOutputStream taOutputStream = new TextAreaOutputStream(
textArea, "Test");
public TextAreaOutputStreamTest() {
setLayout(new BorderLayout());
add(new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
System.setOut(new PrintStream(taOutputStream));
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TextAreaOutputStreamTest());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
答案 0 :(得分:0)
如果它完全被使用(它不在您发布的代码中),则会根据将更改“标准输出”的documentation调用此行System.setOut(new PrintStream(taOutputStream));
后使用它,这意味着以后对System.out.print
方法的所有调用都将发送到taOutputStream
的{{1}}实例。