Reputation: 25
I'm using an ItemListener for my radiobuttons. I saw a lot of ItemListener functions, but mine seems to work differently.
... jUserButton2.addItemListener(ffs);
}
private ItemListener ffs = new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String user = e.getItem().toString();
System.out.println(user);
}
}
};
The value it returns is "javax.swing.JRadioButton[User,445,453,49x18,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.synth.SynthBorder@1f2f60d,flags=288,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],paintBorder=false,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=User]"
Shouldn't it return just the value? (in this case is "User")
Upvotes: 1
Views: 1061
Reputation:
As the docs say:
public Object getItem()
Returns the item affected by the event.
The item affected is a JRadioButton
(which is also what the console prints). This is logical correct, since the item affected is that button. Simply change the code to this:
String user = ((JRadioButton) e.getItem()).getName();
System.out.println(user);
Upvotes: 1
Reputation: 36621
JRadioButton
is a JToggleButton
. If you look into the source code, you will see that the event is fired using the protected fireItemStateChange
method. For example, in the javax.swing.JToggleButton.ToggleButtonModel#setSelected
method you find the following code:
// Send ItemEvent
fireItemStateChanged(
new ItemEvent(this,
ItemEvent.ITEM_STATE_CHANGED,
this,
this.isSelected() ? ItemEvent.SELECTED : ItemEvent.DESELECTED));
This means that when you receive the ItemEvent
and call getItem
, you will receive the JRadioButton
(the this
in the above code (third constructor argument)).
Calling toString
on the radio button gives you exactly what you are seeing.
You can fix this by casting e.getItem()
to a JRadioButton
and call getText()
(or whatever info you want to retrieve) on it
Upvotes: 1