• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2674
  • Last Modified:

change color of JProgressBar

i have a JProgressBar which I am using during a Task

is it possible to change the color of progress bar (default is orange to say green) when the process is finished,

thanks
0
max_dub
Asked:
max_dub
1 Solution
 
Bart CremersJava ArchitectCommented:
Your task already has a way to let your JProgressbar now the current progress (set the value of the JProgressbar). At the end of your task you can also let it change the color:
import javax.swing.*;
import java.awt.*;
import java.util.Random;
import java.util.concurrent.TimeUnit;
 
public class Test extends JFrame {
 
    private JProgressBar bar;
 
    public static void main(String[] args) throws Exception {
        Test test = new Test();
        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        test.pack();
        test.setLocationRelativeTo(null);
        test.setVisible(true);
 
        Task task = new Task(test);
        new Thread(task).start();
    }
 
    @Override
    protected void frameInit() {
        super.frameInit();
 
        bar = new JProgressBar(0, 100);
        bar.setForeground(Color.ORANGE);
 
        add(bar);
    }
 
    public void setProgress(int value) {
        bar.setValue(value);
    }
 
    public void setFinished() {
        bar.setForeground(Color.GREEN);
    }
}
 
class Task implements Runnable {
 
    private Test feedback;
 
    public Task(Test test) {
        this.feedback = test;
    }
 
    public void run() {
        try {
            Random rnd = new Random();
            int value = 0;
            while (value < 100) {
                TimeUnit.MILLISECONDS.sleep(rnd.nextInt(400) + 300);
                value += rnd.nextInt(25) + 5;
                value = Math.min(value, 100);
                feedback.setProgress(value);
            }
            feedback.setFinished();
        } catch (InterruptedException e) {
            Thread.interrupted();
        }
    }
}

Open in new window

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now