我有一个Label需要显示ObservableList. 我有IntegerBinding设置,但我还需要Label根据列表中的元素数量调整 的措辞。
对于下面的 MCVE,如果列表中只有一个元素,则应显示“列表包含 1 个项目”。但是如果列表为空或包含多个项目,则“项目”需要是复数形式:“列表包含 3 个项目”。
我尝试使用三元运算符和 a 来这样做BooleanBinding,但两者都没有任何效果,因为三元表达式似乎只计算一次。单击“添加”按钮不会更改Label.
编码
import javafx.application.Application;
import javafx.beans.binding.Bindings;
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.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
ObservableList<String> items = FXCollections.observableArrayList();
private IntegerBinding listSize = Bindings.size(items);
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
// Simple Interface
VBox root = new VBox(10);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(10));
Label label = new Label();
// Bind the label to display a size-aware notification
label.textProperty().bind(
Bindings.concat("The list contains ", listSize,
((items.size() != 1) ? " items!" : " item!"))
);
// Button to add items
Button button = new Button("Add");
button.setOnAction(event -> items.add("new item"));
root.getChildren().addAll(label, button);
// Show the stage
primaryStage.setScene(new Scene(root));
primaryStage.setTitle("Sample");
primaryStage.show();
}
}
当列表的大小发生变化时,我是否需要包含一个侦听器?
慕的地6264312
猛跑小猪
相关分类