How to set all the values at once using the model in a JProgressBar with Java?


The getModel() method is used to set all the values at once for a JProgressBar −

int newVal = 5;
int newMin = 0;
int newMax = 100;
progressBar.getModel().setRangeProperties(newVal, 0, newMin, newMax, true);

The following is an example to set all the values at once using the model in a progress bar −

Example

package my;
import javax.swing.*;
public class SwingDemo extends JFrame {
   JProgressBar progressBar;
   int i = 0;
   SwingDemo() {
      int min = 0;
      int max = 1000;
      progressBar = new JProgressBar(min, max);
      int newVal = 5;
      int newMin = 0;
      int newMax = 100;
      progressBar.getModel().setRangeProperties(newVal, 0, newMin, newMax, true);
      progressBar.setBounds(70, 50, 120, 30);
      progressBar.setValue(0);
      progressBar.setStringPainted(true);
      add(progressBar);
      setSize(550, 150);
      setLayout(null);
   }
   public void inc() {
      while (i <= 1000) {
         progressBar.setValue(i);
         i = i + 50;
         try {
            Thread.sleep(100);
         } catch (Exception e) {}
      }
   }
   public static void main(String[] args) {
      SwingDemo s = new SwingDemo();
      s.setVisible(true);
      s.inc();
   }
}

The output is as follows. The Progress Bar is displaying −

The Progress Bar completely visible now −

Updated on: 30-Jul-2019

43 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements