2017-09-12 32 views
0

好了,所以我知道该怎么做无限期JProgressBars,但我不明白怎么做明确的。例如,假设我使用JProgressBar来表示我正在加载游戏。在加载这个游戏我有信息,我想从信息的一些文件加载​​并初始化变量:Java:如何有一个明确的JProgressBar加载的东西?

private void load() { 
    myInt = 5; 
    myDouble = 1.2; 
    //initialize other variables 
} 

并说我有4个文件,我想负荷信息。如何翻译此文件以提供100%的精确加载栏?

+1

的可能的复制[JProgressBar的,而在摆动数据加载](https://stackoverflow.com/questions/13366801/jprogressbar-while-data-loading-in-swing) –

+0

@NisheshPratap这没有帮助,我不明白那个人想要做什么。 –

回答

0

你需要做的工作在一个单独的线程,并随着工作的进展更新进度条的模型。

它在Swing事件线程,它可以通过与SwingUtilities.invokeLater执行更新代码来实现执行模式的更新是非常重要的。

例如:

public class Progress { 
    public static void main(String[] args) { 
     JFrame frame = new JFrame("Loading..."); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     JProgressBar progressBar = new JProgressBar(0, 100); 
     frame.add(progressBar); 
     frame.pack(); 
     frame.setVisible(true); 

     // A callback function that updates progress in the Swing event thread 
     Consumer<Integer> progressCallback = percentComplete -> SwingUtilities.invokeLater(
      () -> progressBar.setValue(percentComplete) 
     ); 

     // Do some work in another thread 
     CompletableFuture.runAsync(() -> load(progressCallback)); 
    } 

    // Example function that does some "work" and reports its progress to the caller 
    private static void load(Consumer<Integer> progressCallback) { 
     try { 
      for (int i = 0; i <= 100; i++) { 
       Thread.sleep(100); 
       // Update the progress bar with the percentage completion 
       progressCallback.accept(i); 
      } 
     } catch (InterruptedException e) { 
      // ignore 
     } 
    } 
} 
+0

那么这是否意味着我必须自己衡量进度?例如,如果我加载了3个变量,这是否意味着每次我初始化一个变量时,我都必须设置每次进度?另外,' - >'做什么? –

+0

是的,你必须自己更新进度条。看到[这个答案](https://stackoverflow.com/questions/15146052/what-does-the-arrow-operator-do-in-java)重新箭头操作符。 – teppic

相关问题