【问题标题】:How to append new data to JTextArea in thread?如何在线程中将新数据附加到 JTextArea?
【发布时间】:2015-08-05 15:39:35
【问题描述】:

我的代码:

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); 工作正常并在控制台中弹出时,在客户端类循环中什么也不做。如何使用附加或设置文本方法将该信息动态添加到文本区域?

【问题讨论】:

  • 你阻止了event dispatch thread。在后台线程中运行循环,并仅将invokeLater() 用于 GUI 更新。
  • 你能在你的答案中草拟一些代码吗?我会尝试应用它
  • 您可以使用文本区域的变量名(一个对象)来调用.append(String message) 将数据附加到文本文件中。例如如果我的文本区域的变量名称是 txta1 并且我想将“Hello world”附加到它,代码将是: txta1.append("Hello world"); .希望这会有所帮助。

标签: java multithreading swing sockets settext


【解决方案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
         }
      });
   }
}

【讨论】:

  • 我手动添加新客户端,所以需要main方法。我不明白如何使用invokeLater
  • 你的想法是什么?是否要从多个 JFrame s 追加?
  • 如果使用 java.awt.EventQueue.invokeLater(new Runnable() { 不需要导入 javax.swing.SwingUtilities;
  • 什么时候应该使用invokeLater方法?在什么情况下?它通常适用于invokeLater的简单线程
  • 当您想update 或从自定义线程对Swing components 进行一些修改时,您将需要SwingUtilities。否则修改将不可见。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-25
  • 2015-04-03
  • 1970-01-01
  • 2023-04-08
  • 2014-03-06
  • 1970-01-01
相关资源
最近更新 更多