我正在尝试实现一个全局加载对话框...我想调用一些静态函数来显示对话框和一些静态函数来关闭它.同时我在主线程或子线程中做一些工作......
I'm trying to implement a global loading dialog... I want to call some static function to show the dialog and some static function to close it. In the meanwhile I'm doing some work in the main thread or in a sub thread...
我尝试关注,但对话框没有更新...最后一次,在再次隐藏之前,它会更新...
I tried following, but the dialog is not updating... Just once at the end, before hiding it again, it updates...
private static Runnable getLoadingRunable()
{
if (loadingRunnable != null)
{
loadingFrame.setLocationRelativeTo(null);
loadingFrame.setVisible(true);
return loadingRunnable;
}
loadingFrame = new JFrame("Updating...");
final JProgressBar progressBar = new JProgressBar();
progressBar.setIndeterminate(true);
final JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
contentPane.setLayout(new BorderLayout());
contentPane.add(new JLabel("Updating..."), BorderLayout.NORTH);
contentPane.add(progressBar, BorderLayout.CENTER);
loadingFrame.setContentPane(contentPane);
loadingFrame.pack();
loadingFrame.setLocationRelativeTo(null);
loadingFrame.setVisible(true);
loadingRunnable = new Runnable() {
public void run() {
try {
while (running) {
Thread.sleep(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
loadingFrame.setVisible(false);
}
});
}
};
return loadingRunnable;
}
public static void showLoadingBar() {
System.out.println("showLoadingBar");
running = true;
threadLoadingBar = new Thread(getLoadingRunable());
threadLoadingBar.start();
}
public static void hideLoadingBar() {
System.out.println("hideLoadingBar");
running = false;
threadLoadingBar = null;
}
如果没有动画,说明你正在事件调度线程中工作,同时显示加载帧.这个后台工作应该在另一个线程中完成.
If it doesn't animate, it means that you're doing work in the event dispatch thread while the loading frame is displayed. This background work should be done in another thread.
这是一个无效的示例:
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
try {
showLoadingBar();
Thread.sleep(10000L); // doing work in the EDT. Prevents the frame from animating
hideLoadingBar();
}
catch (InterruptedException e) {
}
}
}
);
}
这是一个工作示例:
public static void main(String[] args) throws Exception {
showLoadingBar();
Thread.sleep(10000L); // doing work outside of the EDT. Everything works fine
hideLoadingBar();
}
附注:实例化、填充和使加载框架可见的代码应包装在 SwingUtilities.invokeLater()
中,因为它必须在 EDT 中运行.
Side note: the code which instantiates, populates and makes the loading frame visible should be wrapped into SwingUtilities.invokeLater()
, because it must be run in the EDT.
这篇关于Java - 全局的、可重用的加载对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!