I want to scale a JCheckBox
e.g. equally to its set text's font size. For example when i increase the Font
size the checkbox itself stays small but it should grow with the text or i want to set the size of the box myself:
JCheckBox chckbxTest = new JCheckBox("Test");
chckbxTest.setFont("Arial", Font.BOLD, 27));
If possible, I need the same functionality for JRadioButton
. Unfortunately i haven't found any documentation regarding this functionality.
Solution:
The marked answer helped me to create a fully scalable own styled JCheckbox. The following example draws a simple rectangle filled with another rectangle when checked:
[...]
JCheckBox myCheckBox = new JCheckBox("Test");
myCheckBox.setIcon(new SimpleCheckboxStyle(20));
[...]
class SimpleCheckboxStyle implements Icon {
int dim = 10;
public SimpleCheckboxStyle (int dimension){
this.dim = dimension;
}
protected int getDimension() {
return dim;
}
public void paintIcon(Component component, Graphics g, int x, int y) {
ButtonModel buttonModel = ((AbstractButton) component).getModel();
int y_offset = (int) (component.getSize().getHeight() / 2) - (int) (getDimension() / 2);
int x_offset = 2;
if (buttonModel.isRollover()) {
g.setColor(new Color(0, 60, 120));
} else if (buttonModel.isRollover()) {
g.setColor(Color.BLACK);
} else {
g.setColor(Color.DARK_GRAY);
}
g.fillRect(x_offset, y_offset, fontsize, fontsize);
if (buttonModel.isPressed()) {
g.setColor(Color.GRAY);
} else if (buttonModel.isRollover()) {
g.setColor(new Color(240, 240, 250));
} else {
g.setColor(Color.WHITE);
}
g.fillRect(1 + x_offset, y_offset + 1, fontsize - 2, fontsize - 2);
if (buttonModel.isSelected()) {
int r_x = 1;
g.setColor(Color.GRAY);
g.fillRect(x_offset + r_x + 3, y_offset + 3 + r_x, fontsize - (7 + r_x), fontsize - (7 + r_x));
}
}
public int getIconWidth() {
return getDimension();
}
public int getIconHeight() {
return getDimension();
}
}
For example when i increase the Font size the checkbox itself stays small but it should grow with the text or i want to set the size of the box myself
Then you need to provide custom icons for the font size of your text. See methods like:
setIcon(....)
setSelectedIcon(...)
You would need to do the same for a JRadioButton. Also, you would need different icons for each LAF.