我希望在每一行中创建一个带有Buttons的Buttons,以删除特定的行。因此,我创建了一个扩展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();
}
}
}发布于 2014-10-21 11:57:09
大于包含表中所有数据的TableView,用空单元格填充额外的空间。在决定是否在单元格中包含按钮之前,TableCell需要检查单元格是否为空。您可以在单元格的emptyProperty()上使用侦听器,或者绑定到它:
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();
}
}
}有了绑定,你就能做到
graphicProperty().bind(Bindings.when(emptyProperty())
.then((Node)null)
.otherwise(hb));而不是将侦听器添加到emptyProperty()。两者之间的选择只是一个风格问题。
https://stackoverflow.com/questions/26481500
复制相似问题