如何在线程中将新数据附加到JTextArea?

时间:2015-08-05 15:39:36

标签: java multithreading swing sockets settext

我的代码:

public class ClientStarter {
    public static void main(String[] args) {        
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ClientGUI();                            
            }
        });
    }
}

我的代码:

public class ClientGUI {
    ClientMainForm mainForm;
    Client client;

    public ClientGUI() {
        mainForm = new ClientMainForm();
        client = new Client(Constants.HOST_NAME, Constants.PORT, mainForm);     
    }   
}

客户端:

public class Client {
    protected Socket client;
    protected BufferedReader in;
    ClientMainForm mainForm;    

    public Client(String hostName, int ip, ClientMainForm mainForm) {
        try {
            this.client = new Socket(hostName, ip);
            this.in = new BufferedReader(new InputStreamReader(
                    this.client.getInputStream()));
            this.mainForm = mainForm;
            String buffer = null;
            while ((buffer = in.readLine()) != null) {
                this.mainForm.appendTextMsg(buffer);                
                this.mainForm.getTextArea().setText(buffer);

                System.out.println(buffer);
            }               
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }   
}

创建了新的客户表单

 this.mainForm.appendTextMsg(buffer);               
    this.mainForm.getTextArea().setText(buffer);
客户端类循环中的

System.out.println(buffer);正常工作并在控制台中弹出时不执行任何操作。如何使用追加或设置文本方法将该信息动态添加到文本区域?

1 个答案:

答案 0 :(得分:1)

class BackgroundThread implements Runnable {

   @Override
   public void run() {

      // the Swing call below must be queued onto the Swing event thread
      SwingUtilities.invokeLater(new Runnable(){
         @Override
         public void run() {
            // OK To make Swing method calls here
            //append JTextArea here
         }
      });
   }
}