Finding the radio button that have been clicked [*Resolved*]
Hello,
I have a user interface using swing. I have 3 radio buttons grouped (Economy, Business, First). I want to find which one the user has clicked. I have grouped the radio buttons and placed them inside a panel. I have added addItemListener to each one. I have used to the code below to print out the radio button that have been clicked. I want to print out either Economy, Business or First, depending on which one the user clicked.
All this code does is print out a load of rubbish, each time a radio button is clicked. Not sure why.
VB Code:
public void itemStateChanged(ItemEvent event)
{
String item = "";
if ( event.getStateChange() == ItemEvent.SELECTED )
{
item = event.getItem().toString();
System.out.println("Radio Button: " + item);
}
}
Thanks in advance,
Steve
Re: Finding the radio button that have been clicked
One way is to add an action command to the radio button where you create it. Once you have the action command set, then you can reference it:
in the init (or where ever you are creating the button):
Code:
JRadioButton jrb = new JRadioButton("Test");
jrb.setActionCommand("Test");
in the listener thingy, change your code to this:
Code:
if ( event.getStateChange() == ItemEvent.SELECTED )
{
System.out.println("Radio Button: " + event.getActionCommand());
}
The code has not been tested, but I believe it will work. There are several other ways of doing this, but I think this is the easiest for you.
NOTE: You should (in my opinion) be using an actionlistener on the radio buttons as opposed to the item listener.
Re: Finding the radio button that have been clicked
Hello System_Error,
Thanks for your reply. Unfortunity the code did not work, there was a compile error:
cannot resolve symbol
symbol : method getActionCommand ()
I think that this is because I am using it in the itemStateChanged method. Possible?
Is there another way to solve this?
Thanks in advance,
Steve
Re: Finding the radio button that have been clicked
Use an actionlistener rather than an itemlistener.... You should have done that in the first place.
Re: Finding the radio button that have been clicked [* Resolved *]
Hello,
Thanks for your help. This is the solution that worked.
rdoReturn.addActionListener(this);
public void actionPerformed(ActionEvent action)
{
System.out.println("Radio Button in action: " + action.getActionCommand() );
}
Many thanks.