gpt4 book ai didi

java - 如果用户忘记在我的代码中选择 jRadioButton 如何停止执行?

转载 作者:行者123 更新时间:2023-12-02 04:09:17 25 4
gpt4 key购买 nike

我的问题可能很简单,但无法解决它,我正在开发一个项目
我放置了 2 个单选按钮来选择性别; 如果用户忘记确定性别我如何打印错误消息来敦促用户
确定性别?这段代码开头的问题:

   private void jButton1ActionPerformed(ActionEvent evt) {                                         
// TODO add your handling code here:
String radioText="";
if (jRadioButton1.isSelected()){radioText=jRadioButton1.getText();}
//male
if (jRadioButton2.isSelected()){radioText=jRadioButton2.getText();}
// female
/*** want here if nothing selected:
* JOptionPane.showMessageDialog(null,"you must determine gender!");
* and exit the code
*/
try
{
String first,second,last,operation;


int bMonth,bDay,bYear; // to set birthDay
int aMonth,aDay,aYear; //to set admissionDate
int fileNo,weight,height;

first = jTextField1.getText();
second = jTextField2.getText();
last = jTextField3.getText();
operation=jTextField14.getText();
bMonth = Integer.parseInt(jTextField4.getText());
bDay = Integer.parseInt(jTextField5.getText());
bYear = Integer.parseInt(jTextField6.getText());

aMonth =Integer.parseInt(jTextField7.getText());
aDay =Integer.parseInt(jTextField8.getText());
aYear = Integer.parseInt(jTextField9.getText());
fileNo=Integer.parseInt(jTextField10.getText());
weight=Integer.parseInt(jTextField12.getText());
height=Integer.parseInt(jTextField13.getText());

Date birth = new Date( bMonth, bDay, bYear );
Date admissionDate = new Date( aMonth, aDay,aYear );
Patient patient = new Patient( first, second,last,fileNo
,birth,admissionDate,weight,height,radioText,operation );

patientsArray.add(patient);


JOptionPane.showMessageDialog( null,patientsArray);
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null,"Input must be Integer!");
}
}

最佳答案

您应该将 ButtonGroup 与单选按钮一起使用。这将允许您一次只能选择一个单选按钮。然后您可以检查 ButtonGroup 的选择。

JRadioButton male = new JRadioButton("Male");
JRadioButton female = new JRadioButton("Female");

ButtonGroup group = new ButtonGroup();
group.add(male);
group.add(female);

然后在 ActionListener 中您可以检查组:

if (group.getSelection() == null)
// no selection has been made

您需要将 ButtonGroup 定义为实例变量,以便可以在 ActionListener 中引用它。

阅读 Swing 教程中关于 How to Use Radio Buttons 的部分了解更多信息和示例。

关于java - 如果用户忘记在我的代码中选择 jRadioButton 如何停止执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33949197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com