Reputation: 49
The default JCheckBox
borders in Mac OS are rounded, but I need a square as checkbox.
Is there a way to accomplish this task without using an ImageIcon
?
In other words, I need some examples of Java classes that implement good-looking square-checkboxes (something like this).
Upvotes: 1
Views: 654
Reputation: 347204
I know you said "without using an ImageIcon" - but, it's the simplest solution which doesn't require a lot of mucking about and can easily produce (unselected/selected) quickly and easily
public class ColorCheckBox extends JCheckBox {
public ColorCheckBox(Color unselectedColor, Color selectedColor) {
setSelectedIcon(icon(Color.MAGENTA));
setIcon(icon(Color.WHITE));
}
protected Icon icon(Color filled) {
BufferedImage img = new BufferedImage(25, 25, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(filled);
g2d.fillRect(0, 0, 25, 25);
g2d.dispose();
return new ImageIcon(img);
}
}
But I said ...
Why is everyone so hell bent on not using the simplest solution available to them.
In that case, the next simplest solution might be to simply override the paintComponent
method and paint over what ever the UI delegate is painting...
public class ColorCheckBox extends JCheckBox {
private Color unselectedColor;
private Color selectedColor;
public ColorCheckBox(Color unselectedColor, Color selectedColor) {
this.unselectedColor = unselectedColor;
this.selectedColor = selectedColor;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (isSelected()) {
g.setColor(selectedColor);
} else {
g.setColor(unselectedColor);
}
g.fillRect(0, 0, getWidth(), getHeight());
}
}
Upvotes: 1