Change the color of a jProgressBar

Asked

Viewed 2,606 times

3

How can I change the color my Progressbar, it always turns a little orange weird, I tried to use this code but it didn’t work:

UIManager.put("ProgressBar.background", Color.orange);
UIManager.put("ProgressBar.foreground", Color.blue);
UIManager.put("ProgressBar.selectionBackground", Color.red);
UIManager.put("ProgressBar.selectionForeground", Color.green);

1 answer

3


These properties need to be defined before creating the JProgressBar. For example:

UIManager.put("ProgressBar.background", Color.orange);
UIManager.put("ProgressBar.foreground", Color.blue);
UIManager.put("ProgressBar.selectionBackground", Color.red);
UIManager.put("ProgressBar.selectionForeground", Color.green);

JProgressBar progress = new JProgressBar();
getContentPane().add(progress);

If you need to change the color after the component has been created or make this change of colors based on the percentage of progress, the solutions of that question can solve.

Here is an example, using the properties you posted next to the question. Here is the result:

progressbar

I put in a thread only to show the increasing bar percentage.

import java.awt.*;
import javax.swing.*;

public class Window extends JFrame implements Runnable {

    private final JProgressBar progress;

    public Window(String title) throws HeadlessException {
        super(title);
        setSize(300, 80);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        UIManager.put("ProgressBar.background", Color.orange);
        UIManager.put("ProgressBar.foreground", Color.blue);
        UIManager.put("ProgressBar.selectionBackground", Color.red);
        UIManager.put("ProgressBar.selectionForeground", Color.green);

        progress = new JProgressBar();
        progress.setStringPainted(true); // para mostrar a porcentagem como texto na barra
        getContentPane().add(progress);
        new Thread(this).start();
    }

    @Override
    public void run() {
        for(int i = 0; i < 100; i++){
            progress.setValue(i); 
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {}
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new Window("stackoverflow pt").setVisible(true);
        });
    }
}
  • 1

    I understood, so I was on the wrong track because I was using the component ready. It seems to be a little complicated, but I’ll take a look

Browser other questions tagged

You are not signed in. Login or sign up in order to post.