javaswingjprogressbar

how to change the color of JProgressBar


1 I am trying to change the color of the progress bar but it stays orange here's the code:

test(){  
        UIManager.put("ProgressBar.background", Color.BLACK);
        UIManager.put("ProgressBar.foreground", Color.RED);
        UIManager.put("ProgressBar.selectionBackground", Color.YELLOW);
        UIManager.put("ProgressBar.selectionForeground", Color.BLUE);
        
          
         bar = new JProgressBar();
         bar.setBounds(20, 30,400 , 200);
         bar.setString("Welcome...");
         bar.setStringPainted(true);
         this.add(bar);

        

I've tried .setbackground it also didnt work


Solution

  • the problem with your code might relate to the location which you called UIManager. if you call it before object initialization it works correctly:

    UIManager.put("ProgressBar.background", Color.GREEN);
    UIManager.put("ProgressBar.foreground", Color.BLUE);
    UIManager.put("ProgressBar.selectionBackground", Color.RED);
    UIManager.put("ProgressBar.selectionForeground", Color.GREEN);
    
    JProgressBar progress = new JProgressBar();
    

    result:
    enter image description here

    and if you call UIManager after initialization the result will differ:

    JProgressBar progress = new JProgressBar();
    
    UIManager.put("ProgressBar.background", Color.GREEN);
    UIManager.put("ProgressBar.foreground", Color.BLUE);
    UIManager.put("ProgressBar.selectionBackground", Color.RED);
    UIManager.put("ProgressBar.selectionForeground", Color.GREEN);
    
    

    result:
    enter image description here]2