JavaFX JDK 9.0.4 ListView celFactory添加空单元格

时间:2018-02-09 16:56:48

标签: java javafx javafx-9

为什么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);
    }
}

enter image description here

1 个答案:

答案 0 :(得分:4)

空单元格的null始终为item

字符串格式会将null格式化为文字字符串"null"(包含四个字符nul和{{的字符串1}})。因此,您的绑定将在所有空单元格中显示文本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());