如何更改单独线程上的textarea上的文本

时间:2014-11-21 06:12:54

标签: java multithreading swing jtextarea

我有一个连续(在单独的线程上运行)的应用程序侦听特定端口,并在端口上有可用数据时打开Jframe。我必须将端口上收到的数据放到JFrame上的文本区域。这是我的代码

private void startListeningOnThePort(final ServerSocket listeningSocket) {

    Runnable listening = new Runnable() {

        public void run() {

                while (true) {
                    //System.out.println("Waiting for clients to connect...");
                    Socket clientSocket;
                try {
                        String readLine;                          
                        clientSocket = listeningSocket.accept();
                        BufferedReader reader =  new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        MessageWindow msgWindow = new MessageWindow();

                        while ((readLine = reader.readLine())!= null) {

                            System.out.println("The message received is "+readLine);
                            msgWindow.getPreviousMessageHistoryWindow().append(readLine+"\n");
                            //msgWindow.revalidate();
                            msgWindow.showMessageWindow();
                        }     
                } catch (IOException ex) {
                    Logger.getLogger(IntranetChatView.class.getName()).log(Level.SEVERE, null, ex);
                }

                }
        }
    };

    Thread serverThread = new Thread(listening);
    serverThread.start();

}

MessageWindow类包含具有文本区域的Jframe。只要端口上有数据,就会显示Jframe,但文本区域未填充。甚至调试也无济于事。

我认为问题在于获得textArea参考。也许对textArea的引用与我们想要设置文本的内容不同。

对此问题的任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

SwingUtilities.invokeAndWait()

中换行
                        msgWindow.getPreviousMessageHistoryWindow().append(readLine+"\n");
                        //msgWindow.revalidate();
                        msgWindow.showMessageWindow();

来自javadoc

  Causes <code>doRun.run()</code> to be executed synchronously on the
  AWT event dispatching thread.  This call blocks until
  all pending AWT events have been processed and (then)
  <code>doRun.run()</code> returns. This method should
  be used when an application thread needs to update the GUI.
  It shouldn't be called from the event dispatching thread.
  Here's an example that creates a new application thread
  that uses <code>invokeAndWait</code> to print a string from the event
  dispatching thread and then, when that's finished, print
  a string from the application thread.