How can I customize the render of JRadioButton?

2019-08-09 05:51发布

问题:

I've created a JRadioButton subclass in which I override the paintComponent method like so:

@Override
protected void paintComponent(Graphics g) {
    g.drawImage(
        isSelected() ? 
           getCheckedImg() :
           getBasicImg()
    , 0, 0, this);
}

but it seems that once the button is drawn, that's the image it uses forever. The isSelected test doesn't seem to have any effect. Are the graphics cached or something by Java? How do I provide my custom JRadioButton with a selected and unselected image? Do I have to write a custom UI?

回答1:

Read the API. There are methods like:

setIcon()
setSelectedIcon()

among others that you can use instead of doing custom painting.



回答2:

To preserve functionality, it's not hard to extend BasicRadioButtonUI and override the delegate's paint() method. You can install your new UI using setUI().



回答3:

Even in Java swing, I generally override paint rather than paintComponent in order to customize the look. I believe the default paint will call paintComponent, but only if the component must be repainted.



标签: java swing awt