How to disable Button when TextField is empty?

拜拜、爱过 提交于 2019-11-26 22:46:50

The other way can be using bindings:

final TextField textField1 = new TextField();
final TextField textField2 = new TextField();
final TextField textField3 = new TextField();

BooleanBinding bb = new BooleanBinding() {
    {
        super.bind(textField1.textProperty(),
                textField2.textProperty(),
                textField3.textProperty());
    }

    @Override
    protected boolean computeValue() {
        return (textField1.getText().isEmpty()
                && textField2.getText().isEmpty()
                && textField3.getText().isEmpty());
    }
};

Button btn = new Button("Button");
btn.disableProperty().bind(bb);

VBox vBox = new VBox();
vBox.getChildren().addAll(textField1, textField2, textField3, btn);

Similar to Uluk's answer, but using the Bindings fluent API:

btn.disableProperty().bind(
    Bindings.isEmpty(textField1.textProperty())
    .and(Bindings.isEmpty(textField2.textProperty()))
    .and(Bindings.isEmpty(textField3.textProperty()))
);

Also note that, this new overloaded method of Bindings is added in JavaFX-8 and not avaliable in JavaFX-2.

use textProperty() Listener for TextField

try this...

Button b1 = new Button("DELETE");
b1.setFont(Font.font("Calibri", FontWeight.BOLD, 17));
b1.setPrefSize(100, 30);
b1.setStyle(" -fx-base: #ffffff;");
b1.setTextFill(Color.BLACK);

b1.setDisable(true); // Initally text box was empty so button was disable

txt1.textProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> ov, String t, String t1) {
            //System.out.println(t+"====="+t1);
           if(t1.equals(""))
               b1.setDisable(true);
           else
               b1.setDisable(false);
        }
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!