【发布时间】:2012-11-07 20:54:59
【问题描述】:
我有一个 JScrollPane,其中包含一个 JTextArea 对象。在这个特定的应用程序中,JTextArea 充当“进程控制台”,因此人们可以看到长时间运行的进程正在发生什么。我的代码如下所示:
JTextArea console;
...
// Initializes the console panel, including creation of the JTextArea and JScrollPane
private void initializePanel() {
JPanel consolePanel = new JPanel();
...
console = new JTextArea();
console.setEnabled(false);
textAreaScrollPane = new JScrollPane(console);
...
}
// Appends an incoming message to the console
@Override
public void update(Observable observable, Object consoleMessage) {
console.append(consoleMessage + "\n");
console.update(console.getGraphics());
}
我遇到的问题是我的 JScrollPane 没有以滚动条开头。当文本被附加到底层 JTextArea 时,它会离开 JScrollPane 的底部。不幸的是,滚动条直到长时间运行的过程完成后才会出现。此时,滚动条突然出现,视图跳转到 JTextArea 的最末端。
因此,应用程序看起来像是被冻结了,因为更多消息位于 JScrollPane 的当前视口之外。
我尝试了不同的代码组合来尝试让 JSrollPane 在每次写入消息时重新绘制,但没有这样的运气。 JTextArea 获取消息并在收到消息后立即打印 - 这确实是 JScrollPane 没有立即添加滚动条造成问题。
谢谢。
【问题讨论】:
-
你试过在另一个线程中运行这个“进程”吗?
-
我没有,但这不是一个坏主意。
-
记得在从另一个线程更新 GUI 时使用
SwingUtilities.invokeLater或SwingUtilities.invokeAndWait... -
你想要一个在
JTextArea上调用append()的SwingWorker,见here。