Freewind
Freewind

Reputation: 198258

How to store extra data to a swing checkbox?

It's easy to create a checkbox in swing, as:

JCheckBox checkbox = new JCheckBox("hello")

The problem is I also want to associate some other values with this checkbox, e.g. another number, 99

But I can't find any methods of a JCheckBox to do it, how to do it?

Upvotes: 0

Views: 197

Answers (2)

Petter Friberg
Petter Friberg

Reputation: 21710

Option 3.

You really need to store alot of values.... extend it....

public class MySuperStoreAlotOfValuesCheckbox extends JCheckBox{
    private static final long serialVersionUID = 1L;
    private int theInt;
    ... all the values in the world...
    public MySuperStoreAlotOfValuesCheckbox(String text){
        super(text);
    }
    public MySuperStoreAlotOfValuesCheckbox(String text, int theInt){
        super(text);
        this.theInt = theInt;
    }
}

Option 4 as suggested by @mKorbel in comment

checkbox.putClientProperty("myInt",99);

The clientProperty dictionary is not intended to support large scale extensions to JComponent nor should be it considered an alternative to subclassing when designing a new component.

Upvotes: 1

user2575725
user2575725

Reputation:

Option 1: Using Map to associate checkbox with values.

Map<JCheckBox, Integer> map = new HashMap<JCheckBox, Integer>();
map.put(checkbox, 99);
int value = map.get(checkbox);

Option 2: Using JCheckBox#setActionCommand(String cmd)

checkbox.setActionCommand("99");
int value = new Integer(checkbox.getActionCommand());

Upvotes: 0

Related Questions