Google Tag Manager

2020/12/31

Use thumbnail as default Icon for JRadioButton

Code

class SelectedIcon implements Icon {
  private final Icon icon;
  private final Color color;

  protected SelectedIcon(Icon icon, Color color) {
    this.icon = icon;
    this.color = color;
  }

  @Override public void paintIcon(Component c, Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.translate(x, y);
    icon.paintIcon(c, g2, 0, 0);
    Path2D triangle = new Path2D.Double();
    triangle.moveTo(getIconWidth(), getIconHeight() / 2d);
    triangle.lineTo(getIconWidth(), getIconHeight());
    triangle.lineTo(getIconWidth() - getIconHeight() / 2d, getIconHeight());
    triangle.closePath();

    g2.setPaint(color);
    g2.fill(triangle);
    g2.setStroke(new BasicStroke(3f));
    g2.drawRect(0, 0, getIconWidth(), getIconHeight());
    g2.setPaint(Color.WHITE);
    Font f = g2.getFont();
    g2.drawString("?", getIconWidth() - f.getSize(), getIconHeight() - 3);
    g2.dispose();
  }

  @Override public int getIconWidth() {
    return icon.getIconWidth();
  }

  @Override public int getIconHeight() {
    return icon.getIconHeight();
  }
}

Explanation

Change the default radio button of JRadioButton to an image thumbnail and the selected state button to an icon with a border drawn on the thumbnail.

References

No comments:

Post a Comment