如何使用JProgressBar [英] How to use JProgressBar

查看:209
本文介绍了如何使用JProgressBar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 JProgressBar ,必须在一秒钟内载入。我不想等待任何任务完成。只需要在一秒钟内填充进度条。所以我写下面的代码。但它不工作。进度条不填。我是Java的新人。请任何人帮助我。

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()); }

推荐答案

在主Swing线程,EDT或事件分派线程上调用Thread.sleep(...),因为这将不会使你的整个应用程序,进度条和所有,睡觉。可能你看不到任何事情发生1秒钟,然后宾果,整个进度栏被填充。

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.

我建议,而不是Thread.sleep,你使用一个Swing计时器对于这部分,或者如果你想要最终监视一个长时间运行的进程,请使用后台线程,如SwingWorker。 SwingWorkers在JProgressBar教程中讨论。

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.

例如,使用计时器:

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());
}

这篇关于如何使用JProgressBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆