假设我在同一个控制器类中有一个ObservableList
和一个Button
:
private ObservableList<NameItem> _selectedList = _database.getONameList();
@FXML
private Button nextButton;
如何才能使Button
仅在ObservableList
不为空时启用?有没有绑定属性可以用来设置它?
发布于 2018-09-23 08:56:38
实际上,只需几个简单的绑定就可以相当容易地做到这一点。
首先,您需要创建一个绑定到ObservableList
大小的IntegerBinding
IntegerBinding listSize = Bindings.size(_selectedList);
然后创建一个绑定到listSize
绑定是否大于0的新BooleanBinding
:
BooleanBinding listPopulated = listSize.greaterThan(0);
现在,您需要做的就是使用not()
方法将按钮的disableProperty
绑定到listPopulated
属性的相反位置(因为如果列表中的项都是true
,那么您希望将false
实际传递给按钮的disableProperty
):
button.disableProperty().bind(listPopulated.not());
下面是一个快速MCVE演示:
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();
}
}
在上面的示例中,"Submit“按钮是禁用的,直到您使用"Add Item”按钮将项目添加到ObservableList
中。
编辑:正如卢卡斯在下面的评论中指出的那样,这些绑定也可以链接在一起来简化事情(这两种方法都是同样有效的;它只是取决于你觉得哪种方法更具可读性,真的):
button.disableProperty().bind(Bindings.size(list).greaterThan(0).not())
另一种方法
另一种方法是使用ListChangeListener
,它可以在列表更改时随时启用或禁用按钮:
list.addListener((ListChangeListener<String>) c -> {
// If the size of the list is less than 1, disable the button; otherwise enable it
button.setDisable(c.getList().size() < 1);
});
这实际上与第一个方法做了完全相同的事情,但是您需要自己设置按钮的初始状态,然后侦听器才能为您更新它。
https://stackoverflow.com/questions/52461801
复制相似问题