【问题标题】:Append a string value from thread class to jtextArea将线程类中的字符串值附加到 jtextArea
【发布时间】:2013-02-01 14:36:54
【问题描述】:

我在 netbeans 中创建了一个服务器线程类,并使用 netbeans swing 自动生成的 Jframe 创建了一个调用该类的 GUI 应用程序。我想将线程类中的字符串值附加到我的 JtextArea,但我的 Jtextarea 上显示的值为 null 。未返回字符串请帮助我。代码示例如下

public class simpletestserver1 extends Thread {
String message,mess;
public void run(){
.
.//some coding here
.
.
DataOutputStream outToClient = new DataOutputStream(c.getOutputStream()); 
Scanner r = new Scanner(c.getInputStream());
outToClient.writeBytes(m+'\n');

mess=r.nextLine(); 
// THIS IS THE MESSAGE THAT NEEDS TO BE APPENDED TO 
// MY JTEXTAREA IN MY JFRAME CLASS 

现在我有另一个将数据发送到服务器的客户端线程。当程序在另一个动作事件上运行时,服务器线程已经开始监听。现在,一个按钮按下动作,我的客户端线程开始向我的服务器发送数据,文本应该附加到我的 JtextArea jframe类如下:

package sdiappgui;
import java.util.*;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import java.awt.Window;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level; 
import java.util.logging.Logger;
public class SendEmail extends javax.swing.JFrame {
public SendEmail() {
initComponents();
}
. //some coding here for other generated components
.at this point my server thread has already started on a previously clicked button    action and it is already listening ,i start my client thread and the data sent to server should be appended to my jtextarea
.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)     {                                         
// TODO add your handling code here: 
final simpletestserver1 th1=new simpletestserver1();  
final simpletestclient1 th2=new simpletestclient2();                    
javax.swing.SwingUtilities.invokeLater(new Runnable() {
              @Override
        public void run() {
            th2.start();
            jTextArea2.append("received: " +th1.mess +'\n');     
        }
    });
}

但是我的 jtextarea 没有收到客户端返回的任何字符串。当我运行程序时,jtextArea 上会显示一个空值。请帮帮我。

【问题讨论】:

  • 如需更好的帮助,请尽快发帖SSCCE
  • 这个thread,可能对给定的主题有所帮助。

标签: java multithreading swing jtextarea


【解决方案1】:

没有代码可以检查客户端线程是否已经收到了字符串。当您在启动客户端线程时立即获取字段值,很有可能它还没有完成,而是采用初始值 null。

SwingUtilities.invokeLater 调用移动到分配变量mess 的行之后的线程th1run 方法中。从那里删除th1.start()

// Inside th2.run method:
mess=r.nextLine(); 
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        jTextArea2.append("received: " +th2.mess +'\n');     
    }
 });
}


public SendEmail() {
  initComponents();
  th2.start();
}

【讨论】:

  • 我的线程类不包含在 Jfram 类中,我无法调用它,因为它是一个私有类,我的服务器之前已经开始监听,这里的 th1.start() 是我的客户端线程。请查看我的更新说明。
  • 抱歉,忽略了。当然这是 th2,而不是 th1。但是您希望从 th1.mess 参考中获得哪个值?看起来像是一个错误的对象来取值。
  • 其实我想收到客户端给服务器的消息。服务器读取消息并将其输出到我的 jtextarea 上。我的服务器最初是在另一个按键上启动的,并且 t 已经在侦听来自客户端的消息。这就是我引用 th1.mess 的原因,它应该从客户端读取消息并在我的 jtextarea 上输出消息!
猜你喜欢
  • 2011-12-25
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
  • 2014-04-02
  • 2013-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多