如何将字符串从工作线程发送到文本区域?

时间:2011-08-22 07:33:48

标签: java swing concurrency inputstream jtextarea

public class Client1 implements Runnable{

    ServerSocket serverSocket = null;
    Socket socket = null;
    DataInputStream dataInputStream = null;
    DataOutputStream dataOutputStream = null;
    String Buffer;
    TextArea ta;
    Handler mhandler;


    public Client1() {
        System.out.println("in constructor");
        EstablishConnection();  
        Buffer = new String();
//      mhandler = handler;
//      ta = t;
    }

    private boolean EstablishConnection()
    {


        try 
        {
            System.out.println("calling socket");
            socket = new Socket("192.168.1.145",8080);
            if(socket != null)
            {
                System.out.println("ContentApp"+ "Socket Successfully created");
            }
        } 
        catch (IOException e) {
            System.out.println("ContentApp"+ "Socket IOException");
            e.printStackTrace();
        }
        try 
        {
            dataInputStream = new DataInputStream(socket.getInputStream());
            System.out.println("ContentApp"+ "DataInputstream Successfully created");
        }
        catch (IOException e) {
            System.out.println("ContentApp"+ "Datainputstream failed");
            e.printStackTrace();
            return false;
        }
        try
        {
            dataOutputStream = new DataOutputStream(socket.getOutputStream());
            dataOutputStream.writeUTF("Hi This is Hinar!");
            System.out.println("ContentApp"+ "Dataoutputstream Successfully created");
        } 
        catch (IOException e) 
        {
            System.out.println("ContentApp"+ "Dataoutputstream failed");
            e.printStackTrace();
            return false;
        }

        if(socket != null)
        {
            run();


        }
        return true;
    }


    public void run() {
        while(true)
        {
            System.out.println("ContentApp"+ "Thread is running Succesfully in loop");
            try {
                System.out.println("reading from socket");
                Buffer = dataInputStream.readUTF();
                System.out.println(Buffer+"this is the data");
                Client.tarea.append(Buffer);// Text area of Frames
                /*ta.setVisible(true);
                ta.setText(Buffer+"this is the Buffer");*/



            } catch (IOException e) 
            {
                System.out.println("ContentApp"+ "Read IO Exception");
            e.printStackTrace();
            }
        }

        }
    }

2 个答案:

答案 0 :(得分:4)

既然你没有发布任何异常或告诉我们实际出了什么问题,我只能猜测......

查看SwingUtilities类中的InvokeAndWaiInvokeLater方法:

答案 1 :(得分:3)

请阅读有关Concurency in Swing的教程,然后只需添加此代码,例如

Runnable doRun1 = new Runnable() {

    @Override
    public void run() {
        ta.setText(Buffer+"this is the Buffer");
        ta.setVisible(true);
    }
};
SwingUtilities.invokeLater(doRun1);