JTextPane 活跃度

发布于 2025-01-04 10:31:28 字数 262 浏览 2 评论 0原文

当按下 JButton 时,我的 Swing 应用程序将文本行打印到 JScrollPane 内的 JTextPane 中。对于快速操作来说没有问题。但是,某些 JButton 调用可能需要几分钟的操作。在此期间该按钮保持灰色。

目前发生的情况是文本被“批量”处理,然后在操作结束时我一次得到数百行,同时按钮变为非灰色。问题是我希望附加到 JTextPane 中显示的文档的文本能够更快出现(在附加的那一刻),而不是在整个操作完成时出现。这将创造更好的用户体验。

我做错了什么?

My Swing application prints lines of text to a JTextPane inside of a JScrollPane when a JButton is pressed. For quick operations there is no issue. However, some JButtons invoke operations that may take a few minutes. The button remains greyed out during this time.

What currently happens is that the text is "batched up" and then I get hundreds of lines all at once at the end of the operation at the same moment the button becomes un-greyed. The problem is that I would like the text being appended to the document displayed in the JTextPane to appear sooner (at the moment it is appended) rather than at the time the entire operation completes. This would create a better user experience.

What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风为裳 2025-01-11 10:31:28

使用 SwingWorker 执行后台操作。

// Your button handler
public void actionPerformed(ActionEvent e) {
  (new SwingWorker<Void, String>() {
    public Void doInBackground() {
      // perform your operation
      // invoke publish("your string");
    }

    protected void process(List<String> chunks) {
      // append your string to the scroll pane
    }
  }).execute();
}

Use a SwingWorker for performing your background operation.

// Your button handler
public void actionPerformed(ActionEvent e) {
  (new SwingWorker<Void, String>() {
    public Void doInBackground() {
      // perform your operation
      // invoke publish("your string");
    }

    protected void process(List<String> chunks) {
      // append your string to the scroll pane
    }
  }).execute();
}
夏见 2025-01-11 10:31:28

您直接从 AWT-Thread 中调用代码,该线程会阻止每个事件。解决方案是将长时间运行的代码放在单独的线程中。当您的代码被执行并获得结果时,您会通知您的视图(使用观察者/可观察模式)。当您的视图收到通知时,您会更新滚动窗格内容。

您还必须验证您是否正在 AWT 线程中运行 (SwingUtilities.isEventDispatchThread())。如果不是,那么您需要使用 SwingUtilities.invokeLater() 在 AWT 线程中调度视图的更新,因为 Swing 不是线程安全的。

You are invoking code directly from within the AWT-Thread which blocks every event. The solution is to put your long-running code in a separate Thread. As your code is executed and obtains results, you notifiy your view (using the observer/observable pattern).As your view is notified, you update the scrollpane content.

You must also verify if you are running in the AWT-Thread or not (SwingUtilities.isEventDispatchThread()). If you are not, then you need to dispatch the update of the view in the AWT-Thread using SwingUtilities.invokeLater() because Swing is not Thread-safe.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文