簡體   English   中英

將線程類的字符串值附加到jtextArea

[英]Append a string value from thread class to jtextArea

我已經在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上顯示一個空值。 請幫幫我。

沒有代碼可以檢查客戶端線程是否接收到該字符串。 當您在啟動客戶端線程時立即獲取字段值時,很有可能還沒有完成,而是取初始值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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM