javaswingnetbeansitemlistener

ItemListener getitem() doesn't return only name


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")


Solution

  • 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);