JProgressBar动态更改条形颜色

时间:2013-01-17 07:19:49

标签: java swing jprogressbar nimbus uimanager

我正在使用JProgressBar组件以及Nimbus UI默认值。问题是,当我想手动更改每个进度条的条形颜色时,我通过设置BasicProgressBarUI函数来使用JProgressBar.setUI()。这会带来更多麻烦,因为我想改变条形颜色,似乎我松开了jprogressbar的默认外观(Border,backgroundcolor dissappears)。

所以我可以在代码初始化时设置Nimbus ProgressBar的UIDefaults。它有效。

但我想动态更改每个进度条的条形颜色。

还有其他方法可以更改JProgressBar的条形颜色吗?

public class ProgressGenerator extends JFrame {

    protected int minValue = 0;
    protected int maxValue = 100;
    protected int counter = 0;
    protected JProgressBar progressBar;

    public ProgressGenerator() {
        super("JProgressBar Demo");
        setSize(300, 100);

        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (ClassNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (InstantiationException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (UnsupportedLookAndFeelException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        progressBar = new JProgressBar();
        progressBar.setMinimum(minValue);
        progressBar.setMaximum(maxValue);
        progressBar.setStringPainted(true);

        progressBar.setForeground(Color.GREEN);

        JButton start = new JButton("Start");
        start.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Thread runner = new Thread() {
                    public void run() {
                        counter = minValue;
                        while (counter <= maxValue) {
                            Runnable runme = new Runnable() {
                                public void run() {
                                    progressBar.setValue(counter);
                                }
                            };
                            SwingUtilities.invokeLater(runme);
                            counter++;
                            try {
                                Thread.sleep(100);
                            } catch (Exception ex) {
                            }
                        }
                    }
                };
                runner.start();
            }
        });
        getContentPane().add(progressBar, BorderLayout.CENTER);
        getContentPane().add(start, BorderLayout.WEST);
        WindowListener wndCloser = new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        };
        addWindowListener(wndCloser);
        setVisible(true);
    }

    public static void main(String[] args) {
        new ProgressGenerator();
    }
}

2 个答案:

答案 0 :(得分:4)

+1以Kelopatra为先。

这是我做的一个例子:

JProgressBar颜色通过以下方式初始设置:

UIDefaults defaults = new UIDefaults();
defaults.put("ProgressBar[Enabled].foregroundPainter", new MyPainter(Color.GREEN));
defaults.put("ProgressBar[Enabled+Finished].foregroundPainter", new MyPainter(Color.GREEN));

progressBar.putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE);
progressBar.putClientProperty("Nimbus.Overrides", defaults);

在50%的进展中,颜色将变为红色:

if (progressBar.getValue() == 50) {//change color on 50%
   UIDefaults defaults = new UIDefaults();
   defaults.put("ProgressBar[Enabled].foregroundPainter", new MyPainter(Color.RED));
   defaults.put("ProgressBar[Enabled+Finished].foregroundPainter", new MyPainter(Color.RED));
   progressBar.putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE);
   progressBar.putClientProperty("Nimbus.Overrides", defaults);                          
}

Test.java:

enter image description here

enter image description here

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;

public class Test {

    public static void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        final JProgressBar progressBar = new JProgressBar();
        progressBar.setStringPainted(true);
        progressBar.setValue(0);
        progressBar.setBorderPainted(false);

        JButton startButton = new JButton("Start");

        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                UIDefaults defaults = new UIDefaults();
                defaults.put("ProgressBar[Enabled].foregroundPainter", new MyPainter(Color.GREEN));
                defaults.put("ProgressBar[Enabled+Finished].foregroundPainter", new MyPainter(Color.GREEN));

                progressBar.putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE);
                progressBar.putClientProperty("Nimbus.Overrides", defaults);

                SwingWorker worker = new SwingWorker() {
                    int current = 0, lengthOfTask = 100;

                    @Override
                    public Void doInBackground() {
                        while (current <= lengthOfTask && !isCancelled()) {

                            try { // dummy task
                                Thread.sleep(50);
                            } catch (InterruptedException ie) {
                            }

                            setProgress(100 * current / lengthOfTask);
                            current++;
                        }
                        return null;
                    }
                };
                worker.addPropertyChangeListener(new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent pce) {

                        String strPropertyName = pce.getPropertyName();
                        if ("progress".equals(strPropertyName)) {
                            int progress = (Integer) pce.getNewValue();
                            progressBar.setValue(progress);

                            if (progressBar.getValue() == 50) {//change color on 50%
                                UIDefaults defaults = new UIDefaults();
                                defaults.put("ProgressBar[Enabled].foregroundPainter", new MyPainter(Color.RED));
                                defaults.put("ProgressBar[Enabled+Finished].foregroundPainter", new MyPainter(Color.RED));

                                progressBar.putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE);
                                progressBar.putClientProperty("Nimbus.Overrides", defaults);
                            }

                        }
                    }
                });
                worker.execute();
            }
        });

        JPanel holder = new JPanel();
        holder.add(progressBar);
        holder.add(startButton);

        frame.add(holder);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }
                createAndShowGUI();
            }
        });
    }
}

class MyPainter implements Painter<JProgressBar> {

    private final Color color;

    public MyPainter(Color c1) {
        this.color = c1;
    }
    @Override
    public void paint(Graphics2D gd, JProgressBar t, int width, int height) {
        gd.setColor(color);
        gd.fillRect(0, 0, width, height);
    }
}

答案 1 :(得分:3)

Nimbus支持每个组件的皮肤,例如其他QA中已经回答的问题。应用于JProgressBar“bar”,这意味着使用自定义foregroundPainter配置实例,如:

progressBar = new JProgressBar();

UIDefaults defaults = new UIDefaults();
Painter painter = new MyPainter(Color.GREEN);
defaults.put("ProgressBar[Enabled].foregroundPainter", painter);
defaults.put("ProgressBar[Enabled+Finished].foregroundPainter", painter);

progressBar.putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE);
progressBar.putClientProperty("Nimbus.Overrides", defaults);

mimimal(丑陋的)画家会是这样的:

public static class MyPainter extends AbstractRegionPainter {

    private Color fillColor;
    public MyPainter(Color color) {
        // as a slight visual improvement, make the color transparent
        // to at least see the background gradient
        // the default progressBarPainter does it as well (plus a bit more)
        fillColor = new Color(
                color.getRed(), color.getGreen(), color.getBlue(), 156);
    }

    @Override
    protected void doPaint(Graphics2D g, JComponent c, int width,
            int height, Object[] extendedCacheKeys) {
        g.setColor(Color.GREEN);
        g.fillRect(0, 0, width, height);
    }

    @Override
    protected PaintContext getPaintContext() {
        return null;
    }

}

为了让它在视觉上令人愉悦,请查看ProgressBarPainter:它的包是私有的,除了了解它如何实现其渐变/路径绘制以及在自定义实现中执行相同操作之外,您无法做很多事情。