您好,我正在尝试使用 RMI 实现聊天。该算法如下:共享 RMI 对象和客户端都有一个用于最后键入消息的字符串变量。每当客户端键入消息时,来自共享 RMI 对象的消息就会更新 (messageRMI=messageClient)。如果客户端的最后一条消息与来自 RMI 对象的消息不相等,则最后一条消息将自动输入到 jTextPane 中。
这是 Swing worker :
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground()
throws Exception {
byte[] the_image;
while (true) {
Thread.sleep(1000);
if (connected) {
try {
remote = (I) Naming.lookup("rmi://" + jTextFieldAddress.getText() + "/Niemand23");
switch (remote.refresh_chat(last_message)) {
case 0:
last_message = remote.last_message();
jTextPane1.getStyledDocument().insertString(jTextPane1.getDocument().getLength(), "\n ", null);
if (remote.hasImage()) {
the_image = remote.client_image();
formatC = new ImageIcon(the_image);
jTextPane1.insertIcon(formatC);
} else {
jTextPane1.insertIcon(noImageIcon);
}
jTextPane1.getStyledDocument()
.insertString(jTextPane1.getDocument().getLength(), "\n " + remote.last_message(), style);
jTextPane1.getStyledDocument().insertString(jTextPane1.getDocument().getLength(), "\n", null);
}
} catch (NotBoundException | MalformedURLException | RemoteException | BadLocationException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
};
工作人员应该每秒检查一次状况。最大的问题是,每当客户端键入消息时,第二个客户端的 GUI 就会卡住。我已经尝试了一切但没有结果。有什么想法吗?
最佳答案
如果您阅读 SwingWorker javadocs您会发现您不应该直接更改 doInBackground()
中的 Swing 组件方法。
相反,您应该实现 process()
方法并使用 publish()
doInBackground()
中的方法。具体请看publish method .
就您而言,这需要切换您的 SwingWorker<Void, Void>
至SwingWorker<Void,String>
和publish()
您收到的每条消息。您的process(String...s)
然后方法将填充 jTextPane1
与传入的消息。
尝试一下,看看它是如何工作的。
预计到达时间:此外,您是否需要在循环的每次运行中执行命名查找?地址没有改变,是吗?
关于Java Swing Worker 导致 GUI 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28967029/