开发者

How to use JProgressBar

I want to use JProgressBar and it must be loaded in one second. I don't want wait for any task to complete. Just want to fill the progress bar in one second. So I write following code. But it doesn't working. progress bar wasn't filling. I am new to Java. Please can anyone help me.

    public void viewBar() {

progressbar.setStringPainted(true); progressbar.setValue(0); for(int i = 0; i <= 100; i++) { progressbar.setValue(i); try { Thread.sleep(10); } catch (InterruptedException ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); } } progressbar.setValue(progressbar.getMinimum(开发者_C百科)); }


You can't call Thread.sleep(...) on the main Swing thread, the EDT or "event dispatch thread", as this will do nothing but put your entire application, progress bar and all, to sleep. Likely you're seeing nothing happening for 1 second, then bingo, the entire progress bar is filled.

I suggest that instead of Thread.sleep, you use a Swing Timer for this part, or else if you want to eventually monitor a long-running process, use a background thread such as a SwingWorker. SwingWorkers are discussed in the JProgressBar tutorial.

e.g., with a Timer:

public void viewBar() {

  progressbar.setStringPainted(true);
  progressbar.setValue(0);

  int timerDelay = 10;
  new javax.swing.Timer(timerDelay , new ActionListener() {
     private int index = 0;
     private int maxIndex = 100;
     public void actionPerformed(ActionEvent e) {
        if (index < maxIndex) {
           progressbar.setValue(index);
           index++;
        } else {
           progressbar.setValue(maxIndex);
           ((javax.swing.Timer)e.getSource()).stop(); // stop the timer
        }
     }
  }).start();

  progressbar.setValue(progressbar.getMinimum());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜