Google Tag Manager

2013/06/28

Turn the JProgressBar red with JLayer and RGBImageFilter

Code

class BlockedColorLayerUI extends LayerUI{
  public boolean isPreventing = false;
  private BufferedImage bi;
  private int prevw = -1;
  private int prevh = -1;
  @Override public void paint(Graphics g, JComponent c) {
    if(isPreventing) {
      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()));
      //BUG: cause an infinite repaint loop: g.drawImage(image, 0, 0, c);
      g.drawImage(image, 0, 0, null);
    }else{
      super.paint(g, 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);
  }
}

References

3 comments:

  1. Uhm, did you know you can just use JProgressBar.setForground(java.awt.Color) ?

    ReplyDelete
  2. * setForeground. Sorry, typo

    ReplyDelete
    Replies
    1. Hi Jop, thanks for your comment.
      The following is a supplement to this example(be clearly unexplained...):

      The second top `JProgressBar+setStringPainted(true)` is using `setForeground(...)` method.
      However, `setForeground(...)` have no effect on the second from the bottom `JProgressBar+setStringPainted(false)+WindowsLookAndFeel`.
      Plus, sets the foreground color of JProgressBar have different meanings to different `LookAndFeel`.
      For example, `NimbusLookAndFeel` foreground color mean to a progress string color not filled area color of progress.

      Delete