为什么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);
}
}
答案 0 :(得分:4)
空单元格的null
始终为item
。
字符串格式会将null
格式化为文字字符串"null"
(包含四个字符n
,u
,l
和{{的字符串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());