问题描述
我正在尝试从多个单选按钮中获取值。这意味着每当我选择多个按钮时,它应该打印该值。假设我在选择该选项后选择了披萨和汉堡,然后按下提交按钮,它将打印在该按钮中分配的值。
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");
}
}
}
解决方法
目前,即使选择了多个单选按钮,您也只会打印一个结果,因为您已经在单个 actionPerformed
块中的 if-else
方法中设置了评估代码。因此,一旦一个语句的计算结果为 true
,则跳过该块的其余部分。
因此,要解决此问题,您实际上可以检查单个 JRadioButton
语句中的每个 if
,如下所示:
boolean selectionFound = false;
if (pizza.isSelected() && e.getSource() == button) {
selectionFound = true;
System.out.println("Pizza is selected");
}
if (cabab.isSelected() && e.getSource() == button) {
selectionFound = true;
System.out.println("Cababa is selected");
}
if (burger.isSelected() && e.getSource() == button) {
selectionFound = true;
System.out.println("Burger is selected");
}
if (!selectionFound) {
System.out.println("Nothing is selected");
}
通过这种方法,每一个选择都会被评估。
此外,如果注册此 ActionListener
的唯一组件是您的按钮,则可以省略对操作源的检查。