简体   繁体   English

UIManager和JCheckBox图标

[英]UIManager and JCheckBox icon

My GUI has JTable with column that has boolean type which is being showed as a JCheckBox. 我的GUI的JTable的列类型为boolean,显示为JCheckBox。 Metal colors don't suit to my GUI, so I used next code: 金属颜色不适合我的GUI,因此我使用了下一个代码:

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. 我得到了想要的未选择复选框,但是UIManager中没有可以更改以自定义选择的JCheckBox的键。 Is there way to change selected JCheckBox view globally? 有没有办法全局更改选定的JCheckBox视图? PS I tried both and opaque and transparent background, result is the same - checkbox doesn't work as it has to. PS我尝试了不透明和透明的背景,结果是一样的-复选框无法正常工作。

Override the paintIcon method of Icon to draw different icons when it's selected or not. 覆盖IconpaintIcon方法,以在选择或不选择它时绘制不同的图标。

This is a stack overflow answer demos how to implement a tri-states JCheckBox 这是一个堆栈溢出答案演示,演示了如何实现三态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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM