2

This is the code:

  String male = "Male";
  String female = "Female";

 JRadioButton checkGenderMale = new JRadioButton(male);
      checkGenderMale.addActionListener(new genderListener());

JRadioButton checkGenderFemale = new JRadioButton(female);
      checkGenderMale.addActionListener(new genderListener());

class genderListener implements ActionListener{
   public void actionPerformed(ActionEvent event){
       System.out.println( );
   }
}

In the line System.out.println(); I would like the option (the Strings male or female which ever is selected) to print. So what might go in the parenthesis?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Maydayfluffy
  • 427
  • 1
  • 7
  • 16

1 Answers1

3

You need to write

AbstractButton aButton = (AbstractButton) actionEvent.getSource();
System.out.println("Selected: " + aButton.getText());

In your action performed method.

Rahul Borkar
  • 2,742
  • 3
  • 24
  • 38
  • When I put that in, actionEvent is underlined red. Would you explain briefly what the first line is accomplishing? – Maydayfluffy Mar 14 '12 at 05:44
  • 1
    The first line is just getting on which component the event has occurred, in above it is getting occurred on RadioButton, thing is ActionListener is generic for many UI components in JAVA, but there are also Generic classes such as AbstractButton, we can get source of event and then use that source we can get its properties. – Rahul Borkar Mar 14 '12 at 05:48
  • Thank you so much! Will this work to get the selected items from a JComboBox as well? – Maydayfluffy Mar 14 '12 at 05:50
  • It is because you have done a small mistake by adding genderListener on same "checkGenderMale". change second "checkGenderMale.addActionListener(new genderListener());" to "checkGenderFemale.addActionListener(new genderListener());" – Rahul Borkar Mar 14 '12 at 05:55
  • 1
    also if you want to achieve one JRadioButton should get selected you need to add following code where you have added your JRadioButtons, ButtonGroup group = new ButtonGroup(); group.add(checkGenderMale); group.add(checkGenderFemale); – Rahul Borkar Mar 14 '12 at 05:57
  • @Maydayfluffy for JComboBox you need to add ItemListener, please have a look at http://www.exampledepot.com/egs/javax.swing/combobox_CbItemEvt.html it is easy to understand – Rahul Borkar Mar 14 '12 at 06:00
  • It says the page is not available. – Maydayfluffy Mar 14 '12 at 06:05
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/8852/discussion-between-rahul-borkar-and-maydayfluffy) – Rahul Borkar Mar 14 '12 at 06:10
  • you can also check http://docs.oracle.com/javase/tutorial/uiswing/events/itemlistener.html – Rahul Borkar Mar 14 '12 at 06:13