gpt4 book ai didi

java - 带有自定义 CellFactory 的 ListView 修剪不可见的节点

转载 作者:IT老高 更新时间:2023-10-28 20:38:57 24 4
gpt4 key购买 nike

我的布局问题

我对 ListView 有一点小问题而且我不确定是因为我缺少一些知识还是我的方法有缺陷。不得不承认,在许多可能的情况下,我还不清楚 JavaFX 如何处理布局。

ListView trims my attempt at layout

上面的屏幕截图显示了我使用完全相同的代码两次得到的结果,除了 在第二个上一个不可见的形状我用于连贯布局对调试可见.

CellFactory 所涉及的各种类延长 Group ,我尝试了其他一些Parent到目前为止没有太大的成功。


如何重现

而不是分享我的StarShape , StarRow和其他一些杂项类(如果需要,我很乐意)我写了一个重现该问题的示例。类扩展Application并覆盖 start(...)方法如下:

@Override
public void start(Stage primaryStage) throws Exception {
final StackPane root = new StackPane();
final Scene scene = new Scene(root, 400, 600);

final ListView<Boolean> listView = new ListView<>();
listView.setCellFactory(this::cellFactory);

for (int i = 0; i < 5 ; i++) {
listView.getItems().add(true);
listView.getItems().add(false);
}

root.getChildren().add(listView);

primaryStage.setScene(scene);
primaryStage.setTitle("ListView trims the invisible");
primaryStage.show();
}

在哪里 this::cellFactory

private ListCell<Boolean> cellFactory(ListView<Boolean> listView) {
return new ListCell<Boolean>() {
@Override
protected void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);

if (empty || item == null) {
setText(null);
} else {
final Rectangle tabShape = new Rectangle();
tabShape.setHeight(20);
tabShape.setWidth(40);
tabShape.setVisible(item);

final Label label = new Label(item.toString());
label.setLayoutX(40);

final Group cellRoot = new Group();
cellRoot.getChildren().add(tabShape);
cellRoot.getChildren().add(label);

setGraphic(cellRoot);
}
}
};
}

上面将显示 ListView<Boolean> true 前面有黑色形状项目(因为 tabShape.setVisible(item); 位)。 false元素看起来像普通的 Label物体仿佛在其Group 中的隐形形状不存在(但它存在)。


结束评论

对此进行调试,结果发现具有不可见形状的组被赋予负的 layoutX 属性值。因此Label控件没有像我希望的那样对齐。当我调用 setLayoutX 时不会发生这种情况和 setLayoutYListView 之外(不可见的形状会强制偏移),但它可能不是唯一会发生这种情况的地方。

发生了什么以及如何避免它?或者,我猜我正在接近这个错误,正确的方法是什么?换句话说,我应该问什么问题而不是这个?

最佳答案

取自 @dlatikay's comment ,而不是将占位符项目设置为不可见,您可以通过将其不透明度设置为 0.0 来使它们透明。

从您的问题应用于 MCVE,这将通过替换来完成:

tabShape.setVisible(item);

与:

tabShape.setOpacity(item ? 1.0 : 0.0);

在用户体验方面,您可以更进一步。您可以将它们设置为接近透明,而不是将“非 Activity ”星星设置为完全透明,就像在这个模型中一样(不透明度设置为 0.1):

mockup

我看到的好处是:

  1. 它不仅表示列表中某个项目的评分,还表示最高评分。
  2. 它避免了零星列表项的尴尬空白。

关于java - 带有自定义 CellFactory 的 ListView 修剪不可见的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43016854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com