1

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

yona masa
  • 13
  • 2
  • 1
    What OS and what look and feel? – MadProgrammer Apr 05 '22 at 04:49
  • 1
    The location you call `UIManager.put` matters, try to call it on top-level section of your code – Mustafa Poya Apr 05 '22 at 04:58
  • As hinted by MadProgrammer, I have found that this is almost always caused by having a look and feel set that will override what you do (Your IDE may have auto-generated the look and feel code for one without you noticing). As per the JavaDoc for [put](https://docs.oracle.com/en/java/javase/15/docs/api/java.desktop/javax/swing/UIManager.html#put(java.lang.Object,java.lang.Object)) "Stores an object in the developer defaults. This is a cover method for getDefaults().put(key, value). **This only effects the developer defaults, not the system or look and feel defaults.**" emphasis mine. – sorifiend Apr 05 '22 at 05:10
  • 1
    If you do have a look and feel set, then use the following to change the look and feel `UIManager.getLookAndFeelDefaults().put(...);` rather than just changing the system defaults `UIManager.put(...);` – sorifiend Apr 05 '22 at 05:15
  • 1
    @sorifiend I'm found that most "system" look and feels (like Windows and MacOS) will simply ignore the keys altogether – MadProgrammer Apr 05 '22 at 05:24

1 Answers1

1

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

Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36