[英]JTextArea not working in multithreading - java
I have a code that updates the JTextArea
in run()
method. 我有一个更新
run()
方法中的JTextArea
的代码。
But when run
method executes the append()
method is not executed. 但是当
run
方法执行时, append()
方法不会执行。
It prints the currect value of incomingMessage
variable but not gets append to the JTextArea
. 它输出
incomingMessage
变量的当前值,但不附加到JTextArea
。
public void run()
{
while (true)
{
try
{
if(serverSocketMessage==null)
{
serverSocketMessage = new ServerSocket(Constants.INCOMING_MESSAGE_PORT);
}
System.out.println("Listening to incoming messages");
ObjectInputStream objectInputSender;
String incomingMessage = null;
serverMessage = serverSocketMessage.accept();
objectInputSender = new ObjectInputStream(serverMessage.getInputStream());
Object objectMessage = objectInputSender.readObject();
if (objectMessage instanceof String)
{
incomingMessage = objectMessage.toString();
System.out.println("\nMessage\n"+incomingMessage);
if(incomingMessage!= null)
{
chatingJTextArea.append(incomingMessage);
System.out.println("Not null");
}
chatingJTextArea.append("\n");
chatingJTextArea.append(incomingMessage);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Try invoking append in the EDT
尝试在
EDT
调用附加
private void addMessage(final String message) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
chatingJTextArea.append(message);
}
});
}
A solution would be to implement the processing using a SwingWorker. 一种解决方案是使用SwingWorker来实现处理。 The doInBackground method would implement the processing and you would invoke the publish method with the String to be appended as the argument.
doInBackground方法将实现该处理,并且您将调用带有要附加的String作为参数的publish方法。 Your SwingWorker would then override the process method to take a String argument and append it to the text area.
然后,您的SwingWorker将覆盖process方法以采用String参数并将其附加到文本区域。
I don't have enough privilege to make this a comment but I removed the thing you said is wrong. 我没有足够的权限发表评论,但我删除了您说错的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.