Java Swing - 如何自定义JCheckBox复选标记图标

摘自 https://www.w3cschool.cn/java/codedemo-484050311.html

 import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridLayout; 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);
}
}
 //关键几行:
URL uncheckedIconUrl = Thread.currentThread().getContextClassLoader().getResource("unchecked.png");
URL checkedIconUrl = Thread.currentThread().getContextClassLoader().getResource("checked.png");
Icon uncheckedIcon = new ImageIcon(uncheckedIconUrl);
Icon checkedIcon = new ImageIcon(checkedIconUrl); JCheckBox cb = new JCheckBox("苹果"); cb.setIcon(uncheckedIcon);
cb.setSelectedIcon(checkedIcon);
05-11 21:45