当 TableView 为空时禁用按钮

Disable Button when TableView is empty

菜鸟又需要帮助了。 :)

我有一个名为 tblTabela 的 TableView 和一个名为 btnIzracunaj 的按钮。我需要的是将 Button disable 属性 与 TableView 绑定,这样当 TableView 没有内容时 Button 被禁用。

当 TextFields 为空时,我对另一个 Button 进行了类似的绑定,如下所示:How to disable Button when TextField is empty?

    BooleanBinding bb = new BooleanBinding() {
{
    super.bind(txtPovrsina.textProperty(),
            txtPrvi.textProperty(),
            txtDrugi.textProperty());
}

@Override
protected boolean computeValue() {
    return (txtPovrsina.getText().isEmpty()
            || txtPrvi.getText().isEmpty()
            || txtDrugi.getText().isEmpty());
}

};
btnDodaj.disableProperty().bind(bb);

但我的问题是 TableView,我不知道如何设置 属性 进行绑定。 属性的TableView应该用什么? 我试过了,它没有 return 错误,但也没有按预期工作。我确定应该有其他东西而不是 getItems() 但无法弄清楚是什么。 :(

    BooleanBinding ee = new BooleanBinding() {
{
    super.bind(tblTabela.getItems());
}

@Override
protected boolean computeValue() {
    return (tblTabela.getItems().isEmpty());
}

};
btnIzracunaj.disableProperty().bind(ee);

提前致谢。

像这样将按钮的禁用 属性 绑定到可观察列表:

button.disableProperty().bind(Bindings.size(list).isEqualTo(0));

示例代码:

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {

        ObservableList<String> list = FXCollections.observableArrayList();

        HBox root = new HBox();

        // add button
        Button addButton = new Button("Add");
        addButton.setOnAction(e -> {

            list.add("Text");

            System.out.println("Size: " + list.size());

        });

        // remove button
        Button removeButton = new Button("Remove");
        removeButton.setOnAction(e -> {

            if (list.size() > 0) {
                list.remove(0);
            }

            System.out.println("Size: " + list.size());

        });

        root.getChildren().addAll(addButton, removeButton);

        // bind to remove button
        removeButton.disableProperty().bind(Bindings.size(list).isEqualTo(0));

        Scene scene = new Scene(root, 800, 600);

        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
}
button.disableProperty().bind(Bindings.isEmpty(list));