仅当多个 JTextField 不为空时才保存

Save only if multiple JTextFields are not empty

我的 JFrame 中有多个 JTextFieldJComboBox。因此,每当我单击 _Add_ 按钮时,它都会检查 当前药物面板 中的四 (4) 个文本字段是否为空。如果不是则执行,但这也取决于 个人信息面板 文本字段是否已填写。

但是当我使用 if and else 语句时出现问题,如果我使用 if and else:

    if(condition if the first textfield is empty) {
        // execute something like the textfield turn to red
    } else if(condition if the second textfield is empty) {
        // execute something like the textfield turn to red
    } else if(condition if the third textfield is empty) {
        // execute something like the textfield turn to red
    } else{
        // execute save information of the patient
    }

在这种情况下,如果第一个文本字段为空,那么它将变为红色,但如果第一个和第二个文本字段均为空,则只有第一个文本字段变为红色。

我也尝试了 if,如果和如果我们应该将 else 放在没有空或无效输入的地方,它将执行并保存患者信息,如下所示:

   if(condition if the first textfield is empty) {
     // execute something like the textfield turn to red
   }
   if(condition if the second textfield is empty) {
     // execute something like the textfield turn to red
   }
   if(condition if the third textfield is empty) {
     // execute something like the textfield turn to red
   }
   if(condition if the fourth textfield is empty) {
     // execute something like the textfield turn to red
   } else

如果我仅使用此最后一个 if 语句仅适用于 else 语句。 因此,如果最后一条语句为真,则执行,但不执行 else 语句,即患者保存信息。

我能做些什么吗?或者有什么教程可以让我了解更多关于 Java 和 if and else?

but were should put the else

if 后跟 else 不是强制性的。指定 else 的目的是让您的代码执行流程在 if 不满足(真)时通过所有其他情况。

if i use this only the last if statement only works for the else statement

因为,if可能满足了,所以执行else的情况。我建议在每个 if 案例中包含 return。这样,如果任何 if 案例得到满足。然后,它不会执行进一步的代码。

这对您来说不是新闻:您做错了。

有多种方法可以实现您想要的解决方案, 这是其中之一:

boolean performSave = true;

if (field1 is empty)
{
    do some stuff.
    performSave = false;
}

if (field2 is empty)
{
    do some stuff.
    performSave = false;
}

... repeat for any number of fields.

if (performSave) // no fields are empty.
{
    save stuff.
}

添加按钮动作侦听器的actionPerformed方法中,你可以试试这个:

public void actionPerformed(ActionEvent e) {

    if (! textFieldsValid()) {
        // one or more of the text fields are empty
        // may be display a message in a JOptionPane
        System.out.println("The text fields are not filled with data, etc...");
        return;
    }

    // else, text fields have valid data, so do whatever processing it further...
}

/*
 * This method checks if the text fields are empty and sets their borders as red. Returns
 * a boolean false in case any of the text fields are empty, else true.
 */
private boolean textFieldsValid() {

    boolean validTextFields = true;

    if (textField1.getText().isEmpty()) {
        validTextFields = false;
        textField1.setBorder(new LineBorder(Color.RED));
    }

    if (textField2.getText().isEmpty()) {
        validTextFields = false;
        // textField2.setBorder(...)
    }

    // ... same with textField3 and textField4

    return validTextFields;
}