Setting the JProgressBar colors

You can set the progress rectangle color and remaining area color with setForeground and setBackground.
To set the color of the string drawn inside the progress bar, you have two choices (there is no trivial API method to set these colors, look at bug http://developer.java.sun.com/developer/bugParade/bugs/4226498.html.

  • Set the UIManager property values ProgressBar.selectionForeground and ProgressBar.selectionBackground before creating the JProgressBar. Beware that all your JProgressBar components will take on this color.
  • Extend the JProgressBar UI class to provide a method setSelectionForeground and setSelectionBackground

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("JProgressBar Color Demonstration");
 
      // sets the color of the string painted inside the progressbar
      // selectionForeground is the color of the string that appears
      //    in the rectangle that shows the progress
      // selectionBackground is the color of the string that appears
      //    in the rectangle that shows the remaining area
      UIManager.put("ProgressBar.selectionForeground", Color.red);
      UIManager.put("ProgressBar.selectionBackground", Color.green);
 
      JProgressBar pb = new JProgressBar(0, 100);
      pb.setValue(50); 
      pb.setStringPainted(true);
 
      // sets the foreground color, but only the 
      // rectangle that shows the progress, not the text  
      pb.setForeground(Color.green);
 
      // sets the background color, the rectangle that  
      // shows the remaining area
      pb.setBackground(Color.red);
 
      // add the scroll pane to this window.
      getContentPane().add(pb);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}