Skip to main content

setSelected(boolean) is never called for the ButtonModel of JCheckbox

2 replies [Last post]
swpalmer
Offline
Joined: 2003-06-10

I have code that looks like this:

<br />
class MyModel extends DefaultButtonModel<br />
{<br />
    public void setSelected(boolean b)<br />
    {<br />
        System.out.println("Hello?");<br />
        super.setSelected(b);<br />
    }<br />
}</p>
<p>JCheckBox test = new JCheckBox("Say hi?");<br />
test.setModel( new MyModel() );<br />

But clicking the checkbox never calls setSelected. If I also override isSelected() the isSelected method IS called in my class.

Any ideas what is going on here? I'm off to file a bug...

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
karsten
Offline
Joined: 2003-06-11

The JCheckBox checks the selection state in #isSelected and reduces
the number of calls to the model's #setSelected(boolean) method.

See JToggleButton.ToggleButtonModel for a sample implementation of a check box model.

Karsten

swpalmer
Offline
Joined: 2003-06-10

Hmmm... The docs for ButtonModel state:

* In use, a UI will invoke {@link #setSelected} when a mouse
* click occurs over a check box or radio button.

But that is obviously not true if you derive from DefaultButtonModel. The doc is very specific that the UI invokes setSelected... looking at the implementation of ToggleButtonModel I see that it is the model that handles calling setSelected on itself based on setArmed/setPressed etc.

Deriving from ToggleButtonModel instead of DefaultButtonModel does the trick. I was thinking that logic was in JToggleButton/JCheckBox and not the model.

Thanks.