I am trying to get the value from multiple radio button. This means whenever I select more than one button it should print that value. Suppose I select pizza and Burger after selecting that option and press the submit button it will print the value which is assigned in that button.
package radio;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
public class RadioButton extends JFrame implements ActionListener {
JRadioButton pizza;
JRadioButton cabab;
JRadioButton Burger;
JButton button;
ButtonGroup group;
RadioButton() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
button = new JButton();
button.setText("Submit");
button.setFocusable(false);
button.addActionListener(this);
pizza = new JRadioButton("Pizza");
cabab = new JRadioButton("cabab");
Burger = new JRadioButton("Burger");
pizza.setFocusable(false);
cabab.setFocusable(false);
Burger.setFocusable(false);
this.add(button);
this.add(pizza);
this.add(cabab);
this.add(Burger);
this.setVisible(true);
this.pack();
}
@Override
public void actionPerformed(ActionEvent e) {
if (pizza.isSelected() && e.getSource() == button) {
System.out.println("Pizza is selected");
}
else if (cabab.isSelected() && e.getSource() == button) {
System.out.println("Cababa is selected");
}
else if (Burger.isSelected() && e.getSource() == button) {
System.out.println("Burger is selected");
}
else {
System.out.println("Nothing is selected");
}
}
}
Currently you will only get one result printed, even if multiple radiobuttons are selected, because you have set up your evaluation code in the
actionPerformedmethod in a singleif-elseblock. So once one statement evaluates totrue, the rest of the block is skipped.So to fix this, you could actually check every
JRadioButtonin a singleifstatement as follows:With this approach, every single selection is evaluated. Also, if the only component that has registered this
ActionListeneris your button, you can omit the check for the source of the action.