My GUI has JTable with column that has boolean type which is being showed as a JCheckBox. Metal colors don't suit to my GUI, so I used next code:
ImageIcon icon = new ImageIcon(MyGUI.class.getResource("resources/checkbox1.png"));
UIManager.put("CheckBox.icon", icon1);
I got unselected checkbox I wanted, but there's no key in UIManager that I can change to customize selected JCheckBox. Is there way to change selected JCheckBox view globally? PS I tried both and opaque and transparent background, result is the same - checkbox doesn't work as it has to.
Override the paintIcon
method of Icon
to draw different icons when it's selected or not.
This is a stack overflow answer demos how to implement a tri-states JCheckBox
I found solution on the internet and changed it for myself.
class CheckBoxIcon implements Icon {
public void paintIcon(Component component, Graphics g, int x, int y) {
AbstractButton abstractButton = (AbstractButton)component;
ButtonModel buttonModel = abstractButton.getModel();
if(buttonModel.isSelected())
g.drawImage(createImage("resources/checkbox2.png"), x, y, component);
else
g.drawImage(createImage("resources/checkbox1.png"), x, y, component);
}
public int getIconWidth() {
return 13;
}
public int getIconHeight() {
return 13;
}
protected Image createImage(String path) {
URL imageURL = CheckBoxIcon.class.getResource(path);
Image icn = null;
if (imageURL == null) {
if(null==icn){
//System.out.println("path: "+path);
icn = new ImageIcon (MyGUI.class.getResource(path)).getImage();
if(null!=icn)
return icn;
else{
System.err.println("Resource not found: " + path);
return null;
}
}
return null;
} else {
return (new ImageIcon(imageURL)).getImage();
}
}
}
Then use this line in code.
UIManager.put("CheckBox.icon", new CheckBoxIcon());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.