简体   繁体   English

在此示例中如何调用OutputStream中的write方法?

[英]How is the write method in OutputStream called in this example?

I found an example online and code is shown below. 我在网上找到了一个示例,下面显示了代码。 The TextAreaOutputStream is instantiated in TestAreaOutputStreamText. TextAreaOutputStream在TestAreaOutputStreamText中实例化。 I don't understand how the write method is called in this example. 我不明白在此示例中如何调用write方法。 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)); 如果根本不使用它(不在您的已发布代码中),则在调用此行之后使用它。System.setOut 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 . ,这将更改“标准输出”的文档 ,这意味着以后对System.out.print方法的所有调用都将发送到TextAreaOutputStreamtaOutputStream实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM