Question

I am using swing and wanting to make my JProgress bar look more attractive by adding a soft gradient to it that matches the theme of the app.

My progress bar is in a JTable cell which i have working but my current example paints the cell with a gradient instead of the JProgress bar itself. I would like the cell to be plain white but the progress bar go from light grey -> to dark grey as it get more complete.

Open to not using JProgress bar if something else will do the trick. (Maybe just using the cell renderer?)

My cell renderer

class JPBRenderer extends JProgressBar implements TableCellRenderer {

Batch batch;

public JPBRenderer() {
    super();
    setStringPainted(true);
    setBorderPainted(false);
    setOpaque(false); //EDIT 1
    setForeground(UIConfig.backgroundColor);
}

public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column) {
    batch = ((BatchTableModel)table.getModel()).getBatchForRow(row);
    setMinimum(0);
    setMaximum(batch.getQuantityToProduce());
    setValue(batch.getQuantityCompleted());
    setString(GeneralUtils.formatNumber((batch.getQuantityCompleted()/batch.getQuantityToProduce())*100, 1) + " %");
    return this;
}

@Override
protected void paintComponent(Graphics g) {

    Color color2 = UIConfig.backgroundColor;
    Color color1 = UIConfig.backgroundColor.brighter().brighter();
    double value = 1;
    if(batch != null){
        value = batch.getQuantityCompleted()/batch.getQuantityToProduce();
    }
    int w = getWidth();
    int h = getHeight();
    Graphics2D g2d = (Graphics2D) g;

    GradientPaint gp = new GradientPaint(0, 0, color1, w, 0, color2);

    g2d.setPaint(gp);
    g2d.fillRect(0, 0, w, h);

    super.paintComponent(g);
}
}

My Batch class contains...

public class Batch {
    private Integer id;
    private BigDecimal length;
    private int quantityToProduce;
    private int quantityCompleted;

    //Constructors and getters...
}

Thanks in advance!

Was it helpful?

Solution

You'll need a custom ProgressBarUI, perhaps derived from BasicProgressBarUI illustrated here. You may be able to use the existing paintDeterminate() implementation as a guide. A LinearGradientPaint applied to a BasicSliderUI is seen here.

Alternatively, consider the ProgressIcon shown here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top