If statement 如果文本字段为空,如何禁用按钮?

If statement 如果文本字段为空,如何禁用按钮?,if-statement,javafx,text,textfield,If Statement,Javafx,Text,Textfield,我不能禁用我的按钮。在下面的代码中,接受是一个按钮,电子邮件是一个文本字段 email.setOnAction(ae -> { if(!email.getText().isEmpty()) { accept.setDisable(false); } else accept.setDisable(true); }); 如果我在文本字段中写入,它不会起任何作用。您可以使用一个简单的布尔绑定绑定到按钮的禁用属性。只需两行代码即可完成此任务: Bo

我不能禁用我的按钮。在下面的代码中,
接受
是一个
按钮
电子邮件
是一个
文本字段

email.setOnAction(ae -> {
    if(!email.getText().isEmpty()) {
        accept.setDisable(false);
    } else
        accept.setDisable(true);
});

如果我在文本字段中写入,它不会起任何作用。

您可以使用一个简单的
布尔绑定
绑定到
按钮的
禁用属性
。只需两行代码即可完成此任务:

BooleanBinding isTextFieldEmpty = Bindings.isEmpty(textField.textProperty());
button.disableProperty().bind(isTextFieldEmpty);
您可以使用下面的MCVE查看其运行情况:

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class BooleanBindingExample extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        // Simple interface
        VBox root = new VBox(5);
        root.setPadding(new Insets(10));
        root.setAlignment(Pos.CENTER);

        // TextField and Button
        TextField textField = new TextField();
        Button button = new Button("Click Me");
        root.getChildren().addAll(textField, button);

        // Create a BooleanBinding for the textField to hold whether it is null
        BooleanBinding isTextFieldEmpty = Bindings.isEmpty(textField.textProperty());

        // Now, bind the Button's disableProperty to that BooleanBinding
        button.disableProperty().bind(isTextFieldEmpty);

        // Show the Stage
        primaryStage.setWidth(300);
        primaryStage.setHeight(300);
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
}

按照Zephyr的回答,您可以直接将其绑定到按钮中:

button1.disableProperty().bind(Bindings.isEmpty(textField1.textProperty()));
或者,如果要在多个文本字段为空时禁用按钮:

button1.disableProperty().bind(
    Bindings.isEmpty(textField1.textProperty())
        .or(Bindings.isEmpty(textField2.textProperty()))
        .or(Bindings.isEmpty(textField3.textProperty()))
);

按照miKel的回答,您可以定义按钮的
禁用
属性,而无需导入
绑定
类:

button1.disableProperty().bind(
    textField1.textProperty().isEmpty() 
    .or(textField2.textProperty().isEmpty())
    .or(textField3.textProperty().isEmpty())
);

onAction
仅在按下Enter键时触发。所需的行为是否可能在每次更改
文本字段时更新按钮的状态?顺便说一句:
if
语句可以很容易地替换为
accept.setDisable(email.getText().isEmpty())更好的