【发布时间】:2015-01-25 01:04:20
【问题描述】:
我有一个 JTextPane 用于放置聊天应用程序的聊天历史记录。目前它的内容有两个来源:
- 客户端线程监听服务器消息。
- GUI:添加到消息中的 JField 和按钮(暂时的,因为所有内容都来自服务器)
这是两种方法使用的代码:
private void appendText(String text, AttributeSet attr) {
try {
int len = history.getDocument().getLength();
history.getDocument().insertString(len, text + "\n", attr);
// Convert the new end location
// to view co-ordinates
Rectangle r = history.modelToView(len);
// Finally, scroll so that the new text is visible
if (r != null) {
scrollRectToVisible(r);
}
} catch (BadLocationException e) {
System.out.println("Failed to append text: " + e);
}
}
调试我注意到代码在两种情况下都会执行,但只有在通过 GUI 在 AWT 线程中运行时才会真正显示在组件中。
因此,除非其他人有更好的想法,否则我有以下选择:
- 以某种方式在 AWT 上运行客户端线程。
- 以某种方式在 AWT 上运行 append 方法。
- 请使用你们中的一个人的聪明答案。
有什么想法/建议吗?
【问题讨论】:
标签: java multithreading awt jtextpane