我试图为我的大型Swing程序添加一个花哨的InfiniteProgressPanel作为GlassPane。然而,它并没有出现。它看起来类似于这样:
...
InfiniteProgressPanel glassPane = new InfiniteProgressPanel();
setGlassPane(glassPane);
...
glassPane.start();
doSomeStuff();
glassPane.stop();
...
我相信它运行在与它所要掩盖的长进程相同的线程中。我承认,我对线程还不太了解,我可能应该弄清楚如何在一个单独的线程中运行那个InfiniteProgressPanel GlassPane,以及在它自己的线程中运行的长进程。
发布于 2015-01-23 22:34:51
确保:
- No, by using `SwingUtilities.invokeLater(new MyRunnable)` you're doing exactly the opposite -- you're guaranteeing that the long-running code will be called **on** the Swing event thread -- the exact opposite of what you want. Instead use a SwingWorker's `doInBackground()` method to run the long-running code. Regarding your second point, there's no difference whatsoever between `SwingUtilities.invokeLater` and `EventQueue.invokeLater`.
- By using `SwingUtilities.invokeLater(new MyRunnable)` as noted above, or if you're using a SwingWorker then use its publish/process method pair as the SwingWorker tutorial will show you.
setVisible(true)
,因为根据JRootPane API,默认情况下所有JRootPane都是不可见的。
罗曼·盖伊的InfiniteProgressPanel似乎不需要setVisible(没错)。它出现在调用InfiniteProgressPanel.start()方法时。- I am not familiar with this, do you have a link?
发布于 2015-01-23 22:34:22
线程本身是同一程序中的不同进程。
在java中,有许多不同的线程类型,您需要的是SwingWorker
。
Oracle文档中对此的定义/使用是:
当一个Swing程序需要执行一个长期运行的任务时,它通常使用一个工作线程,也称为后台线程。在工作线程上运行的每个任务都由javax.swing.SwingWorker实例表示。SwingWorker本身是一个抽象类;您必须定义一个子类才能创建一个SwingWorker对象;匿名内部类通常用于创建非常简单的SwingWorker对象。
正如您所看到的,这是您所需要的;后台线程。
final InfiniteProgressPanel glassPane;
...
class GlassPaneHandler extends SwingWorker<String, Object> {
@Override
public String doInBackground() {
glassPane.start();
return setUpPaneAndStuff();
}
@Override
protected void done() {
try {
glassPane.stop();
} catch (Exception e) { } //ignore
}
private void setUpPaneAndStuff() {
//code
}
}
...
(new GlassPaneHandler()).execute(); //place this in your code where you want to initiate the pane
有关更多信息,请参见:http://docs.oracle.com/javase/8/docs/api/javax/swing/SwingWorker.html
发布于 2015-01-23 22:33:02
当您正在更新swing UI时,您需要在Swing的事件线程中这样做。这包括创建组件或任何类型的进度更新。您可以通过SwingUtilities.invokeLater(可运行)方法来完成这个任务。
因此,您应该创建glasspane,并在后台线程中通过invokeLater显示它。从长时间运行的流程线程对glasspane的任何进度更新都应该通过invokeLater完成。
https://stackoverflow.com/questions/28119639
复制相似问题