Search code examples
javafxgridpane

JavaFX Custom ListCell HGrow


I have a ListView with a custom ListCellFactory. In my CustomListCell implemenation I use setGraphic to set the list item graphic to a GridPane but I am not able not let the GridPane fill the whole width of the ListView. The following is a short version of my code:

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);
        ...
    }
}

Even with the prefWidth bounding from another post my GridPane will not grow! No matter what combination of layout constraints I use it looks as follows:

Example View

The GridPane shall expand to the full width of the ListCell (I want to add a delete button at the buttom right corner). I'm getting crazy, please help!


Solution

  • With a little bit of css, you can check that the GridPane is actually using all the available space in the cell, but your controls are not:

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

    So you need to select the column you want to take all the available space, and force it to use it.

    Let's say you have one Label in the first cell, and one Button in the second, that should be aligned to the right. All you need to do is create a new ColumnConstraints for the second column of the grid, and set it to grow always and align the content to the right:

    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);
    }
    

    And you will have your custom list cell:

    Custom ListCell