dynamic checkbox icon

来源:互联网 发布:国内大数据龙头企业 编辑:程序博客网 时间:2024/05/20 10:22
A TRICKY FOR DYNAMIC CHECKBOX ICON
 
public static class CheckBoxIcon implements Icon {
    private ImageIcon checkedIcon = (ImageIcon)ControlUtil.createIcon("Bold");
    private ImageIcon uncheckedIcon = (ImageIcon)ControlUtil.createIcon("Underline");
    public void paintIcon(Component component, Graphics g, int x, int y) {
      AbstractButton abstractButton = (AbstractButton) component;
      ButtonModel buttonModel = abstractButton.getModel();
      g.translate(x, y);
      ImageIcon imageIcon = buttonModel.isSelected() ? checkedIcon
          : uncheckedIcon;
      Image image = imageIcon.getImage();
      g.drawImage(image, 0, 0, component);
      g.translate(-x, -y);
    }
    public int getIconWidth() {
      return 20;
    }
    public int getIconHeight() {
      return 20;
    }
  }
 
THIS IS THE OFFICAL WAY
 
public class JCheckBoxCustomIcon extends JFrame {
   
public JCheckBoxCustomIcon() throws HeadlessException {
       
initialize();
   

   
private void initialize() {
       
setSize(300, 300);
       
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
setLayout(new FlowLayout(FlowLayout.LEFT));
      
// Creating checkbox with text label
       
JCheckBox checkBox = new JCheckBox("Check me!");
       
checkBox.setSelected(true);
       
// Set default icon for checkbox
       
checkBox.setIcon(new ImageIcon("icon.png"));
       
// Set selected icon when checkbox state is selected
       
checkBox.setSelectedIcon(new ImageIcon("selectedIcon.png"));
       
// Set disabled icon for checkbox
       
checkBox.setDisabledIcon(new ImageIcon("disabledIcon.png"));
       
// Set disabled-selected icon for checkbox
       
checkBox.setDisabledSelectedIcon(new ImageIcon("disabledSelectedIcon.png"));
       
// Set checkbox icon when checkbox is pressed
       
checkBox.setPressedIcon(new ImageIcon("pressedIcon.png"));
       
// Set icon when a mouse is over the checkbox
       
checkBox.setRolloverIcon(new ImageIcon("rolloverIcon.png"));
       
// Set icon when a mouse is over a selected checkbox
       
checkBox.setRolloverSelectedIcon(new ImageIcon("rolloverSelectedIcon.png"));
       
getContentPane().add(checkBox);
   
}
   
public static void main(String[] args) {
       
SwingUtilities.invokeLater(new Runnable() {
           
public void run() {
               
new JCheckBoxCustomIcon().setVisible(true);
           
}        
});   
}
原创粉丝点击