如何更改 JProgressBar 的颜色

how to change the color of JProgressBar

1 我正在尝试更改进度条的颜色,但它仍然是橙色这里是代码:

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);

        

我试过 .setbackground 也没用

您的代码问题可能与您调用的位置有关 UIManager。 如果您在对象初始化之前调用它,它会正常工作:

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();

结果:

如果您在初始化后调用 UIManager,结果将不同:

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);

结果:
]2