zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    Linux操作系统中,.zip、.tar、.tar.gz、.tar.bz2、.tar.xz、.jar、.7z等格式的压缩与解压
    R 环境内存限制的更改
    R 安装与环境配置
    开启博客园之路
    react-router @4用法整理
    react性能调谐与diff算法
    react新版本生命周期
    col-md-push-*和col-md-offset的区别
    react 基础篇 #2 create-react-app
    react-draft-wysiwyg富文本
  • 原文地址:https://www.cnblogs.com/LiuYanYGZ/p/9486477.html
Copyright © 2011-2022 走看看