gpt4 book ai didi

带按钮的 JavaFX-8 TableView 渲染了太多按钮?

转载 作者:行者123 更新时间:2023-12-02 05:21:25 26 4
gpt4 key购买 nike

我想创建一个 TableView,每行都有 Button 来删除特定行。因此,我创建了一个扩展 TableCell 的类,其中包含一个 Button。所以我将列的 CellFactory 设置如下:

clmRemoveButtons.setCellFactory(c -> new RemovingCell(clients));

一切正常。我能够删除行并且按钮显示正确,但有一个问题。整栏都有按钮。数据的 ObservableList 中有多少项并不重要。包含项目的行中的按钮可以正常工作,但是当我单击超出此范围的按钮时,我会收到 IndexOutOfBoundsException (这是正确的,因为此时没有要删除的数据)。

所以我的问题是,我做错了什么以及如何避免这个问题?

最诚挚的问候

编辑:RemovingCell的代码(注意:HoverButton是一个使用一些设置(大小等)扩展JavaFX Button的控件,所以没有什么特别。

public class RemovingCell extends TableCell<Client, Client> {
private HoverButton hb = new HoverButton(Color.RED);

public RemovingCell(ObservableList<Client> data) {
super();
setAlignment(Pos.CENTER);
try {
ImageView imgv = new ImageView(new Image(new FileInputStream(
"img/Remove.png")));
imgv.setFitWidth(15);
imgv.setPreserveRatio(true);
imgv.setSmooth(true);
hb.setGraphic(imgv);
hb.setTooltip(ControlFactory.getTooltip("Klient entfernen"));
hb.setOnAction(event -> {
data.remove(getTableRow().getIndex());
});
setGraphic(hb);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

最佳答案

大于包含表中所有数据所需的

TableView 会用空单元格填充额外的空间。在决定是否在其中包含按钮之前,您的 TableCell 需要检查单元格是否为空。您可以使用单元格 emptyProperty() 上的监听器或与其绑定(bind)来执行此操作:

public class RemovingCell extends TableCell<Client, Client> {
private HoverButton hb = new HoverButton(Color.RED);

public RemovingCell(ObservableList<Client> data) {
super();
setAlignment(Pos.CENTER);
try {
ImageView imgv = new ImageView(new Image(new FileInputStream(
"img/Remove.png")));
imgv.setFitWidth(15);
imgv.setPreserveRatio(true);
imgv.setSmooth(true);
hb.setGraphic(imgv);
hb.setTooltip(ControlFactory.getTooltip("Klient entfernen"));
hb.setOnAction(event -> {
data.remove(getTableRow().getIndex());
});

// conditionally set the graphic:
// setGraphic(hb);

emptyProperty().addListener( (obs, wasEmpty, isNowEmpty) -> {
if (isNowEmpty) {
setGraphic(null);
} else {
setGraphic(hb);
}
});

setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

通过绑定(bind)你可以做到

graphicProperty().bind(Bindings.when(emptyProperty())
.then((Node)null)
.otherwise(hb));

而不是将监听器添加到emptyProperty()。两者之间的选择只是风格问题。

关于带按钮的 JavaFX-8 TableView 渲染了太多按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26481500/

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