tags:

views:

54

answers:

3

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?

A: 

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.

Brian S
-1, custom painting should be done in paintComponent() not paint(). Read the Swing tutorial section on Custom Painting: http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/TOC.html
camickr
Thanks, I've read it, and several times before. However, the base version of `paint` calls `paintComponent` along with other actions; when I don't need those actions (which is frequent), I have no issues with overriding `paint`. You're just putting "RTFM" in a pretty dress. I have RTFM, and then I RTFSourceCode, and then I made my own logical decision for my own projects.
Brian S
That may be fine for you, but this advice goes against the way Swing was designed to be used and therefore you need to explain the consequences/benefits of using this approach.
camickr
+1  A: 

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().

trashgod
+1  A: 

Read the API. There are methods like:

setIcon()
setSelectedIcon()

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

camickr
This preserves the model's functionality, and it's easier!
trashgod
I guess I don't understand your requirement. The point of these two methods is to replace the "radio button icon" with whatever you want. Post your SSCCE (http://sscce.org) showing the problem.
camickr
It's my fault this got voted down. I clicked the wrong button on accident! This solution totally works. It was very easy to implement and I didn't have to go screwing around with UIs. Thanks!
Mike Caron