Java 如何更改位于单独线程上的textarea上的文本
我有一个应用程序,它连续(在单独的线程上运行)侦听特定端口,并在端口上有可用数据时打开Jframe。我必须将端口上接收到的数据放到JFrame上的文本区域。下面是我的代码Java 如何更改位于单独线程上的textarea上的文本,java,multithreading,swing,jtextarea,Java,Multithreading,Swing,Jtextarea,我有一个应用程序,它连续(在单独的线程上运行)侦听特定端口,并在端口上有可用数据时打开Jframe。我必须将端口上接收到的数据放到JFrame上的文本区域。下面是我的代码 private void startListeningOnThePort(final ServerSocket listeningSocket) { Runnable listening = new Runnable() { public void run() {
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的引用与我们想要设置的文本不同
对此问题的任何帮助都将不胜感激。将调用包装在
SwingUtilities.invokeAndWait()中。
来自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.
Swing是一个单线程框架,并且不是线程安全的,您永远不应该从事件调度线程的上下文之外创建或更新UI。有关更多详细信息,请参阅。如果可以,而不是使用<代码>线程< /代码>,您可以考虑使用<代码> SvigWorks,请参阅更多细节。如果你必须使用<代码>线程< /代码>,那么你应该使用<代码> SWIVITUTION.VIOKELATER 同步更新到EDT……考虑提供一个演示你的问题的方法。这将减少混乱和更好的响应
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.