Generate icons for checkboxes

Instead of using this square check boxes you can also set your own images using the three following methods of JCheckBox:

  • setIcon to set the default icon.
  • setSelectedIcon to set the icon displayed when the box is checked.
  • setDisabledIcon to set the icon used when the box is disabled.

Now I mostly need the same image as the default image for selected and disabled icon with either an outline when it’s selected or grayed out if disabled.
So that I don’t have to set those three icons manually each time, I’ve subclassed JCheckBox so that the setIcon sets all three icons:

public void setIcon(Icon defaultIcon) {
	// New icon should have the same size
	int height = defaultIcon.getIconHeight();
	int width = defaultIcon.getIconWidth();
	// Get an image with the icon
	BufferedImage image = new BufferedImage(width, height,
	Graphics2D g2 = image.createGraphics();
	// First paint the icon
	defaultIcon.paintIcon(this, g2, 0, 0);
	// Buffer for the new image
	BufferedImage selected = new BufferedImage(width, height,
	g2 = selected.createGraphics();
	// Draw the original icon
	g2.drawImage(image, null, 0, 0);
	// Create the stroke for the outline
	int strokeSize = (int) (.15 * width);
	g2.setStroke(new BasicStroke(strokeSize, BasicStroke.CAP_ROUND,
	// Then draw the outline
	g2.drawRoundRect(0, 0, width, height, height, height);
	// And create an ImageIcon to use as selected icon
	setSelectedIcon(new ImageIcon(selected));
	// For the disabled icon we just apply a gray filter
	ImageFilter filter = new GrayFilter(false, 0);
	// Apply the filter to the original image
	Image disabled = createImage(new FilteredImageSource(image.getSource(),
	// And create an ImageIcon to use as disabled icon
	setDisabledIcon(new ImageIcon(disabled));

Now I just need to set one of them and the others are created automatically. The result looks like this:
Of course the outline shouldn’t be so thick and the icon already should provide space for the outline.

Leave a Reply

Your email address will not be published. Required fields are marked *