Java Swing How to - Create JLayer with JProgressBar








Question

We would like to know how to create JLayer with JProgressBar.

Answer

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.RGBImageFilter;
//from ww w  .  jav a2s  .co  m
import javax.swing.AbstractAction;
import javax.swing.BoundedRangeModel;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLayer;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.WindowConstants;
import javax.swing.plaf.LayerUI;

public class Main {
  public static void main(String[] args) {
    BoundedRangeModel model = new DefaultBoundedRangeModel();
    BlockedColorLayerUI layerUI = new BlockedColorLayerUI();
    JPanel p = new JPanel(new GridLayout(2, 1, 12, 12));

    p.add(new JLayer<JProgressBar>(new JProgressBar(model), layerUI));

    JPanel box = new JPanel();
    box.add(new JButton(new AbstractAction("+10") {
      private int i = 0;
      @Override
      public void actionPerformed(ActionEvent e) {
        model.setValue(i = (i >= 100) ? 0 : i + 10);
      }
    }));

    p.repaint();

    JPanel panel = new JPanel(new BorderLayout());
    panel.add(p, BorderLayout.NORTH);
    panel.add(box, BorderLayout.SOUTH);
    
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(panel);
    f.setSize(320, 240);
    f.setVisible(true);
  }
}

class BlockedColorLayerUI extends LayerUI<JProgressBar> {
  BufferedImage bi;
  int prevw, prevh;

  @Override
  public void paint(Graphics g, JComponent c) {
      JLayer jlayer = (JLayer) c;
      JProgressBar progress = (JProgressBar) jlayer.getView();
      int w = progress.getSize().width;
      int h = progress.getSize().height;

      if (bi == null || w != prevw || h != prevh) {
        bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
      }
      prevw = w;
      prevh = h;

      Graphics2D g2 = bi.createGraphics();
      super.paint(g2, c);
      g2.dispose();

      Image image = c.createImage(new FilteredImageSource(bi.getSource(),
          new RedGreenChannelSwapFilter()));
     g.drawImage(image, 0, 0, c);
  }
}
class RedGreenChannelSwapFilter extends RGBImageFilter {
  @Override
  public int filterRGB(int x, int y, int argb) {
    int r = (int) ((argb >> 16) & 0xff);
    int g = (int) ((argb >> 8) & 0xff);
    int b = (int) ((argb) & 0xff);
    return (argb & 0xff000000) | (g << 16) | (r << 8) | (b);
  }
}