使用 SwingWorker 显示加载动画
Using SwingWorker to show a loading animation
我的问题:
我的应用程序中有一个执行时间很长的任务(需要从 Web 获取数据),我正在尝试显示一个带有动画的加载屏幕(只是一个旋转的圆圈,不需要进度条),同时正在执行任务
到目前为止我做了什么:
我在面板中创建了加载屏幕的设计并将其添加到 JFrame 并尝试在长过程的代码之前调用实例化 JFrame,然后在过程完成后将其处置,就像这样:
LoadingFrame frame = new LoadingFrame();
//Long Process
Wiring wiring = new Wiring(node.source);
wiring.generateScopeForTargetNode();
// close() calls setVisible(false) and then dispose()
frame.close();
然而,框架直到任务完成才重新绘制,我收到的只是一个空白框,最后没有处理。
我搜索了这个问题,发现它与线程和并发(我不熟悉)有关,并找到了使用 JDialog
而不是 JFrame
的建议,所以我听从了建议。我最终得到的是:
- JDialog 加载并绘制但动画不播放
- JDialog 未在最后处理
我需要帮助:
我尝试搜索更多问题并找到建议,如果我理解正确的话,我应该使用 SwingWorker
到 运行 线程中的一个任务和另一个线程中的动画。但是我不熟悉线程和 SwingWorker
并且需要帮助来创建一个简单的 SwingWorker
实例来实现我正在尝试做的事情
使用 SwingWorker
"to fetch data from the web" in the background. publish()
interim results as they arrive. Your implementation of process()
can then safely update a view component's model on the event dispatch thread. With even modest granularity, the user will start seeing data instead of an uninformative animation. This complete example 更新监听 JTable
的 TableModel
,但监听 JTextComponent
的 Document
也可以。
我的问题:
我的应用程序中有一个执行时间很长的任务(需要从 Web 获取数据),我正在尝试显示一个带有动画的加载屏幕(只是一个旋转的圆圈,不需要进度条),同时正在执行任务
到目前为止我做了什么:
我在面板中创建了加载屏幕的设计并将其添加到 JFrame 并尝试在长过程的代码之前调用实例化 JFrame,然后在过程完成后将其处置,就像这样:
LoadingFrame frame = new LoadingFrame();
//Long Process
Wiring wiring = new Wiring(node.source);
wiring.generateScopeForTargetNode();
// close() calls setVisible(false) and then dispose()
frame.close();
然而,框架直到任务完成才重新绘制,我收到的只是一个空白框,最后没有处理。
我搜索了这个问题,发现它与线程和并发(我不熟悉)有关,并找到了使用 JDialog
而不是 JFrame
的建议,所以我听从了建议。我最终得到的是:
- JDialog 加载并绘制但动画不播放
- JDialog 未在最后处理
我需要帮助:
我尝试搜索更多问题并找到建议,如果我理解正确的话,我应该使用 SwingWorker
到 运行 线程中的一个任务和另一个线程中的动画。但是我不熟悉线程和 SwingWorker
并且需要帮助来创建一个简单的 SwingWorker
实例来实现我正在尝试做的事情
使用 SwingWorker
"to fetch data from the web" in the background. publish()
interim results as they arrive. Your implementation of process()
can then safely update a view component's model on the event dispatch thread. With even modest granularity, the user will start seeing data instead of an uninformative animation. This complete example 更新监听 JTable
的 TableModel
,但监听 JTextComponent
的 Document
也可以。