JavaFX自定义ListCell HGrow

时间:2015-01-10 17:59:26

标签: javafx gridpane

我有一个带有自定义ListCellFactory的ListView。在我的CustomListCell实现中,我使用setGraphic将列表项图形设置为GridPane,但我无法让GridPane填充ListView的整个宽度。以下是我的代码的简短版本:

class MyListCell extends ListCell<MyObject>
{
    private final GridPane _myComponent;

    public MyListCell()
    {
        ...
        setContentDisplay(ContentDisplay.GRAPHIC_ONLY); // does not help
        //this.setPrefWidth(0); // does not help
        myComponent.prefWidthProperty().bind(this.widthProperty()); // does not help
    }

    ...

    @Override
    protected void updateItem(MyObject item, boolean empty)
    {
        ...
        setGraphic(_myComponent);
        ...
    }
}

即使使用another post的prefWidth限制,我的GridPane也不会增长!无论我使用什么布局约束的组合,它看起来如下:

Example View

GridPane将扩展到ListCell的整个宽度(我想在右下角添加一个删除按钮)。我疯了,请帮忙!

1 个答案:

答案 0 :(得分:1)

使用一点css,您可以使用单元格中的所有可用空间检查GridPane实际,但您的控件不是:

public MyListCell(){
    ... 
    _myComponent.setStyle("-fx-border-color: black;");
}

因此,您需要选择要占用所有可用空间的列,并强制它使用它。

假设您在第一个单元格中有一个Label,在第二个单元格中有一个Button,它应该与右侧对齐。您需要做的就是为网格的第二列创建一个新的ColumnConstraints,并将其设置为始终增长并将内容与右侧对齐:

private final Label label = new Label();
private final Button button = new Button("Click");

public MyListCell(){
    _myComponent.add(label, 0, 0);
    ColumnConstraints c1 = new ColumnConstraints();

    _myComponent.add(button, 1, 0);
    ColumnConstraints c2 = new ColumnConstraints();
    c2.setHgrow(Priority.ALWAYS);
    GridPane.setHalignment(button, HPos.RIGHT);

    _myComponent.getColumnConstraints().addAll(c1,c2);
}

您将拥有自定义列表单元格:

Custom ListCell

相关问题