I found an example online and code is shown below. The TextAreaOutputStream is instantiated in TestAreaOutputStreamText. I don't understand how the write method is called in this example. How does this example work?
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();
}
});
}
}
If it is used at all (it isn't in your posted code), it is used afters calls to this line System.setOut(new PrintStream(taOutputStream));
, per the documentation that will change the "Standard Output", which means all later calls to the System.out.print
method(s) will be sent to the taOutputStream
instance of TextAreaOutputStream
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.