1

为什么 CellFactory 会在这个列表中添加这么多空元素?我明确设置了一个只有“a”和“b”的可观察数组
我不认为绑定有问题......有什么建议吗?

package at.kingcastle.misc;

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class MainSpielwiese  extends Application {
    @Override
    public void start(Stage primaryStage) {
        ListView<String> lv = new ListView<>();
        lv.setItems(FXCollections.observableArrayList(new String[] {"a", "b"}));

        StackPane root = new StackPane();
        root.getChildren().add(lv);

        Scene scene = new Scene(root, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.show();

        lv.setCellFactory(list -> {
            ListCell<String> cell = new ListCell<>();
            ContextMenu contextMenu = new ContextMenu();
            cell.textProperty().bind(Bindings.format("%s", cell.itemProperty()));
            return cell;
        });
    }

    public static void main(String[] args) {
        launch(args);
    }
}

在此处输入图像描述

4

1 回答 1

4

空单元格始终nullitem.

字符串格式将格式化null为文字字符串"null"(包含四个字符nul和的字符串l)。因此,您的绑定将"null"在所有空单元格中显示文本。

由于您在此列中有字符串数据,您可以这样做

cell.textProperty().bind(cell.itemProperty());

当单元格为空时,它将文本设置为 null而不是文字字符串。"null"

更一般地说(即对于不是的数据类型String,所以你不能使用上面的绑定),你可以做类似的事情

cell.textProperty().bind(Bindings.
    when(cell.emptyProperty()).
    then("").
    otherwise(Bindings.format("%s", cell.itemProperty())));

或者

cell.textProperty().bind(Bindings.createStringBinding(() -> {
    if (cell.isEmpty()) {
        return "" ;
    } else {
        return String.format("%s", cell.getItem());
    }
}, cell.itemProperty(), cell.emptyProperty());

或者

cell.textProperty().bind(new StringBinding() {
    {
        bind(cell.textProperty(), cell.emptyProperty());
    }
    @Override
    public String computeValue() {
        return cell.isEmpty() ? "" : String.format("%s", cell.getItem()) ;
    }
});
于 2018-02-09T17:13:03.597 回答