Creating a modal progress dialog : JProgressBar « Swing « Java Tutorial






import java.awt.BorderLayout;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;

public class Main {
  public static void main(String[] args) {
    JFrame parentFrame = new JFrame();
    parentFrame.setSize(500, 150);
    JLabel jl = new JLabel();
    jl.setText("Count : 0");

    parentFrame.add(BorderLayout.CENTER, jl);
    parentFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    parentFrame.setVisible(true);

    final JDialog dlg = new JDialog(parentFrame, "Progress Dialog", true);
    JProgressBar dpb = new JProgressBar(0, 500);
    dlg.add(BorderLayout.CENTER, dpb);
    dlg.add(BorderLayout.NORTH, new JLabel("Progress..."));
    dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    dlg.setSize(300, 75);
    dlg.setLocationRelativeTo(parentFrame);

    Thread t = new Thread(new Runnable() {
      public void run() {
        dlg.setVisible(true);
      }
    });
    t.start();
    for (int i = 0; i <= 500; i++) {
      jl.setText("Count : " + i);
      dpb.setValue(i);
      if(dpb.getValue() == 500){
        dlg.setVisible(false);
        System.exit(0);
        
      }
      try {
        Thread.sleep(25);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    dlg.setVisible(true);
  }
}








14.32.JProgressBar
14.32.1.JProgressBarJProgressBar
14.32.2.Creating a JProgressBar Component with an Unknown Maximum
14.32.3.A progress bar is used for lengthy tasks.
14.32.4.Labeling a JProgressBarLabeling a JProgressBar
14.32.5.Virtical JProgressBarVirtical JProgressBar
14.32.6.Creating a modal progress dialog
14.32.7.Set all the values at once by using the model
14.32.8.Using an Indeterminate JProgressBarUsing an Indeterminate JProgressBar
14.32.9.Displaying the Percentage Done on a JProgressBar Component
14.32.10.Getting and Setting the Values of a JProgressBar Component
14.32.11.Listening for Value Changes in a JProgressBar Component
14.32.12.Handling JProgressBar Events: notification of data model changes through a ChangeListenerHandling JProgressBar Events: notification of data model changes through a ChangeListener
14.32.13.ProgressBar and Task
14.32.14.SwingWorker and ProgressBar
14.32.15.Customizing JProgressBar Look and Feel