Skip to content

SegmentedControl - support stretching to fit width #150

@dlemmermann

Description

@dlemmermann

I am using the SegmentedControl like this for our application but it took quite some fiddling around to make it behave this way.

Image

As you can see I wanted the control to span the entire width of the parent container.

The code required looks like this:

public class CustomSegmentedControl extends SegmentedControl {

    public CustomSegmentedControl() {
        setMinHeight(Region.USE_PREF_SIZE);
        setMaxWidth(Double.MAX_VALUE);
        getSegments().addListener((Observable it) -> {
            getSegments().forEach(button -> {
                HBox.setHgrow(button, Priority.ALWAYS);
                button.setMaxWidth(Double.MAX_VALUE);
                button.setMinWidth(Region.USE_PREF_SIZE);
                button.setAlignment(Pos.CENTER);
            });
        });

        skinProperty().subscribe(skin -> {
            if (skin != null) {
                HBox labelBox = (HBox) lookup(".labels");
                labelBox.prefWidthProperty().bind(widthProperty());
                HBox.setHgrow(labelBox, Priority.ALWAYS);
            }
        });
    }
}

The skin listener is needed because the HBox that contains the labels is a child of a simple "Pane". If the parent were an HBox I could save that listener. But even then the code requires know-how. Ideally there is a propery or a styling hack that would allow app developers to make it stretch by itself.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions