|
-
Aug 26th, 2006, 12:38 PM
#1
Thread Starter
Frenzied Member
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
Last edited by steve_rm; Sep 4th, 2006 at 06:34 AM.
steve
-
Aug 26th, 2006, 05:01 PM
#2
Frenzied Member
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.
-
Aug 26th, 2006, 10:51 PM
#3
Thread Starter
Frenzied Member
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
-
Aug 27th, 2006, 04:09 PM
#4
Frenzied Member
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.
-
Sep 4th, 2006, 02:50 AM
#5
Thread Starter
Frenzied Member
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|