Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

javafx - How to disable Button when TextField is empty?

In the following code I have a TextField and a Button. I need to disable the Button when ever the TextField is empty, so that I can avoid entering empty values to the database. How can I make the button disabled ?

    private VBox addVBox() {

    VBox vb1 = new VBox();
    vb1.setPadding(new Insets(15, 20, 25, 20));
    vb1.setSpacing(15);
    vb1.setStyle("-fx-background-color: #333333;");

    final Label label = new Label("Staff Details");
    label.setFont(Font.font("Arial", FontWeight.BOLD, 20));
    label.setTextFill(Color.WHITE);

    TableColumn sub = new TableColumn("Staff Name");
    sub.setMinWidth(400);
    sub.setCellValueFactory(
            new PropertyValueFactory<Staff, String>("subName"));

    table.setItems(data);
    table.getColumns().addAll(sub);

    addSubName = new TextField();
    addSubName.setPromptText("Staff Name");
    addSubName.setPrefSize(200, 30);

    final Button b2 = new Button("Add");
    b2.setFont(Font.font("Calibri", FontWeight.BOLD, 17));
    b2.setPrefSize(70, 30);
    b2.setStyle(" -fx-base: #0066ff;");
    b2.setTextFill(Color.BLACK);

     b2.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {

            msg = addSubName.getText();
            try {
                enterStaff();
            } catch ( ClassNotFoundException | SQLException ex) {
                Logger.getLogger(AddStaff.class.getName()).log(Level.SEVERE, null, ex);
            }

            data.add(new Staff(addSubName.getText()));
            addSubName.clear();
            }
     });

    hb.getChildren().addAll(addSubName, b2);
    hb.setSpacing(5);

    vb1.getChildren().addAll(label, table, hb);
    return vb1;

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...