1

netbeans でサーバー スレッド クラスを作成し、netbeans スイング自動生成 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 が表示されます。私を助けてください。

4

1 に答える 1

1

クライアント スレッドが既に文字列を受信して​​いるかどうかを確認するコードはありません。クライアント スレッドを開始するとすぐにフィールド値を取得するため、まだ行われていない可能性が高く、代わりに初期値 null が取得されます。

変数が割り当てられている行の後のスレッドSwingUtilities.invokeLaterのメソッドに呼び出しを移動します。そこから削除します。runth1messth1.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 に答える