Java Swing How to - Create custom UI for progress bar








Question

We would like to know how to create custom UI for progress bar.

Answer

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
//w w w .j a  va 2  s .  com
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.plaf.basic.BasicProgressBarUI;

public class Main extends JPanel {

  public Main() {
    JProgressBar jpb = new JProgressBar();
    jpb.setUI(new MyProgressUI());
    jpb.setForeground(Color.blue);
    jpb.setIndeterminate(true);
    this.add(jpb);

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(this);
    f.pack();
    f.setVisible(true);
  }

  public static void main(String[] args) {
    new Main();
  }
}
class MyProgressUI extends BasicProgressBarUI {
  Rectangle r = new Rectangle();
  @Override
  protected void paintIndeterminate(Graphics g, JComponent c) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    r = getBox(r);
    g.setColor(progressBar.getForeground());
    g.fillOval(r.x, r.y, r.width, r.height);
  }
}