Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

printing what radio button has been clicked by the user. 2

Status
Not open for further replies.

steve1rm

Programmer
Aug 26, 2006
255
0
0
GB
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.

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
 
You can try creating the radiobuttons and setActionCommand to represent the words you want printed for each; and add the buttons to a buttonGroup.

use addActionListener to each button

public void actionPerformed(ActionEvent e){
buttonGroup.getSelection().getActionCommand() should retrive the label of the selected radio button
}

 
Or use the getText method to retrieve the name of the option.

Cheers,
Dian
 
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.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top