Java Swing How to - Customize JCheckBox Check Mark Icon








Question

We would like to know how to customize JCheckBox Check Mark Icon.

Answer

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridLayout;
/*  w ww .  j  a v a  2s  .  c om*/
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JFrame;

class CheckBoxIcon implements Icon {
  public void paintIcon(Component component, Graphics g, int x, int y) {
    AbstractButton abstractButton = (AbstractButton) component;
    ButtonModel buttonModel = abstractButton.getModel();

    Color color = buttonModel.isSelected() ? Color.BLUE : Color.RED;
    g.setColor(color);

    g.drawRect(1, 1, 20, 20);

  }

  public int getIconWidth() {
    return 20;
  }

  public int getIconHeight() {
    return 20;
  }
}

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Icon checked = new CheckBoxIcon();
    Icon unchecked = new CheckBoxIcon();
    JCheckBox aCheckBox1 = new JCheckBox("Pizza", unchecked);
    aCheckBox1.setSelectedIcon(checked);
    JCheckBox aCheckBox2 = new JCheckBox("Calzone");
    aCheckBox2.setIcon(unchecked);
    aCheckBox2.setSelectedIcon(checked);
    Icon checkBoxIcon = new CheckBoxIcon();
    JCheckBox aCheckBox3 = new JCheckBox("Anchovies", checkBoxIcon);
    JCheckBox aCheckBox4 = new JCheckBox("Stuffed Crust", checked);
    frame.setLayout(new GridLayout(0, 1));
    frame.add(aCheckBox1);
    frame.add(aCheckBox2);
    frame.add(aCheckBox3);
    frame.add(aCheckBox4);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}