1

我在 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 上会显示一个空值。请帮帮我。

4

1 回答 1

1

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

SwingUtilities.invokeLater调用移到分配变量的行之后run的线程方法中。从那里移除。th1messth1.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();
}
于 2013-02-01T14:45:14.167 回答