4

Client has gui and extra thread (to process socket input and print it out to passes object of type PrintStream). The gui form has new javax.swing.JTextArea(). I need to pass to thread the object PrintStream to write to: ClientThreadIn(PrintStream inOutput){...}. How to create/bind gui JTextArea to accept data form ClientThreadIn using PrintStream?


Client:

    in = new BufferedReader(new InputStreamReader(s.getInputStream())); 
    out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
ClientThreadIn threadIn = new ClientThreadIn(in, System.out); // client passes it's System.out to thread for writing

So JTextArea should be similar to console. It should be able to accept data from Thread (actually Thread writes to PrintStream of gui)... Is there something similar to JTextArea.getInputStream()?

4

1 回答 1

10

一种方法是创建一个将JTextArea 链接到OutputStream 的类,例如TextAreaOutputStream,并让它扩展OutputStream。给它一个 StringBuilder 对象来保存它在覆盖中构造的字符串write(int b),并给它一个对要写入文本的 JTextArea 的引用。然后当遇到换行符时,将 String 写入 JTextArea,但一定要在 Swing 事件线程或 EDT 上执行此操作。

例如:

import java.io.IOException;
import java.io.OutputStream;

import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

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() {
   }

   @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);
   }
}

然后将它包装在 PrintStream 对象中并让您的套接字使用它是微不足道的。

于 2012-06-03T19:27:04.303 回答