swing JCheckBox 更换复选框样式

 

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

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

 

 

 1 import java.awt.Color;
 2 import java.awt.Component;
 3 import java.awt.Graphics;
 4 import java.awt.GridLayout;
 5 
 6 import javax.swing.AbstractButton;
 7 import javax.swing.ButtonModel;
 8 import javax.swing.Icon;
 9 import javax.swing.JCheckBox;
10 import javax.swing.JFrame;
11 
12 class CheckBoxIcon implements Icon {
13   public void paintIcon(Component component, Graphics g, int x, int y) {
14     AbstractButton abstractButton = (AbstractButton) component;
15     ButtonModel buttonModel = abstractButton.getModel();
16 
17     Color color = buttonModel.isSelected() ? Color.BLUE : Color.RED;
18     g.setColor(color);
19 
20     g.drawRect(1, 1, 20, 20);
21 
22   }
23 
24   public int getIconWidth() {
25     return 20;
26   }
27 
28   public int getIconHeight() {
29     return 20;
30   }
31 }
32 
33 public class Main {
34   public static void main(String args[]) {
35     JFrame frame = new JFrame();
36     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
37     Icon checked = new CheckBoxIcon();
38     Icon unchecked = new CheckBoxIcon();
39     JCheckBox aCheckBox1 = new JCheckBox("Pizza", unchecked);
40     aCheckBox1.setSelectedIcon(checked);
41     JCheckBox aCheckBox2 = new JCheckBox("Calzone");
42     aCheckBox2.setIcon(unchecked);
43     aCheckBox2.setSelectedIcon(checked);
44     Icon checkBoxIcon = new CheckBoxIcon();
45     JCheckBox aCheckBox3 = new JCheckBox("Anchovies", checkBoxIcon);
46     JCheckBox aCheckBox4 = new JCheckBox("Stuffed Crust", checked);
47     frame.setLayout(new GridLayout(0, 1));
48     frame.add(aCheckBox1);
49     frame.add(aCheckBox2);
50     frame.add(aCheckBox3);
51     frame.add(aCheckBox4);
52     frame.setSize(300, 200);
53     frame.setVisible(true);
54   }
55 }
 1 //关键几行:
 2 URL uncheckedIconUrl = Thread.currentThread().getContextClassLoader().getResource("unchecked.png");
 3 URL checkedIconUrl = Thread.currentThread().getContextClassLoader().getResource("checked.png");
 4 Icon uncheckedIcon = new ImageIcon(uncheckedIconUrl);
 5 Icon checkedIcon = new ImageIcon(checkedIconUrl);
 6 
 7 JCheckBox cb = new JCheckBox("苹果");
 8 
 9 cb.setIcon(uncheckedIcon);
10 cb.setSelectedIcon(checkedIcon);

 

posted @ 2018-08-16 11:56  LiuYanYGZ  阅读(1621)  评论(0编辑  收藏  举报