問題描述
我正在嘗試實現(xiàn)一個全局加載對話框...我想調(diào)用一些靜態(tài)函數(shù)來顯示對話框和一些靜態(tài)函數(shù)來關(guān)閉它.同時我在主線程或子線程中做一些工作......
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...
我嘗試關(guān)注,但對話框沒有更新...最后一次,在再次隱藏之前,它會更新...
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;
}
推薦答案
如果沒有動畫,說明你正在事件調(diào)度線程中工作,同時顯示加載幀.這個后臺工作應(yīng)該在另一個線程中完成.
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();
}
附注:實例化、填充和使加載框架可見的代碼應(yīng)包裝在 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.
這篇關(guān)于Java - 全局的、可重用的加載對話框的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!