将arraylist size属性绑定到Java FX按钮

时间:2018-09-22 23:46:17

标签: javafx arraylist observable

假设我在相同的控制器中有一个可观察的列表和一个按钮

private ObservableList<NameItem> _selectedList = _database.getONameList();

@FXML
private Button nextButton;

我如何做到只有在ObservableList大于0时才启用按钮,否则将其禁用?我可以使用绑定属性来设置它吗?

我尝试使用以下命令:https://stackoverflow.com/a/38216335/5709876

但是它对我不起作用。

1 个答案:

答案 0 :(得分:4)

实际上,只需几个简单的绑定就可以很容易地做到这一点。

首先,您要创建一个绑定到IntegerBinding大小的ObservableList

IntegerBinding listSize = Bindings.size(_selectedList);

然后创建一个新的BooleanBinding绑定到listSize绑定是否大于0:

BooleanBinding listPopulated = listSize.greaterThan(0);

现在,您需要做的就是使用disableProperty方法将按钮的listPopulated绑定到not()属性的相反位置(因为listPopulated将是{{1 }}(如果项目在列表中),您实际上想将true传递到按钮的false):

disableProperty

以下是MCVE的快速演示:

button.disableProperty().bind(listPopulated.not());

在上面的示例中,“提交”按钮被禁用,直到您使用“添加项目”按钮将项目添加到import javafx.application.Application; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; import javafx.beans.binding.IntegerBinding; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class Main 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); // Create an empty ObservableList ObservableList<String> list = FXCollections.observableArrayList(); // Create a binding to extract the list's size to a property IntegerBinding listSizeProperty = Bindings.size(list); // Create a boolean binding that will return true only if the list has 1 or more elements BooleanBinding listPopulatedProperty = listSizeProperty.greaterThan(0); // Create the button we want to enable/disable Button button = new Button("Submit"); // Bind the button's disableProperty to the opposite of the listPopulateProperty // If listPopulateProperty is false, the button will be disabled, and vice versa button.disableProperty().bind(listPopulatedProperty.not()); // Create another button to add an item to the list, just to demonstrate the concept Button btnAddItem = new Button("Add Item"); btnAddItem.setOnAction(event -> { list.add("New Item"); System.out.println(list.size()); }); // Add the buttons to the layout root.getChildren().addAll(btnAddItem, button); // Show the Stage primaryStage.setScene(new Scene(root)); primaryStage.show(); } } 为止。

编辑:正如Lukas在下面的注释中所指出的那样,这些Bindings也可以全部链接在一起以简化操作(这两种方法都同样有效;这取决于您是否更易读,真的):

ObservableList

  

另一种方法

执行此操作的另一种方法是使用button.disableProperty().bind(Bindings.size(list).greaterThan(0).not()) ,该功能可在列表更改时启用或禁用按钮:

ListChangeListener

这实际上与第一种方法具有完全相同的作用,但是您需要先设置按钮的初始状态,然后监听器才能为您更新按钮的状态。

相关问题