How to prevent a label font size from resizing its parent?

Viewed 116

I have a label inside a stackpane. This label represents the users font selection, and the size of the labels font is bound.

enter image description here

When the desired font size becomes too big, the label cuts itself off horizontally, but it pushes down vertically:

enter image description here

Setting pref/max height of the parent stackpane or the label does not prevent it growing vertically. How can I prevent this behaviour?

Minimal Example:

import javafx.application.Application;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class Demo extends Application {

    private SimpleDoubleProperty fontSize = new SimpleDoubleProperty(12);

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage)
    {
        Label label = new Label("font name");
        label.setStyle("-fx-background-color: #ffeded;");
        label.prefWidth(120);
        label.maxWidth(120);
        label.prefHeight(32);
        label.maxHeight(32);
        fontSize.addListener((observable, oldValue, newValue) -> {
                label.setFont(new Font(Font.getDefault().getName(), (Double) newValue));
        });

        StackPane sp = new StackPane(label);
        sp.setStyle("-fx-background-color: #ff9595;");
        sp.setAlignment(Pos.CENTER);
        sp.prefWidth(120);
        sp.maxWidth(120);
        sp.prefHeight(32);
        sp.maxHeight(32);

        Slider slider = new Slider();
        slider.setMin(8);
        slider.setMax(72);
        slider.setValue(12);
        fontSize.bind(slider.valueProperty());


        VBox box = new VBox(sp, slider);

        Scene scene = new Scene(box, 350, 200);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Indent Demo");
        primaryStage.show();
    }
}

Expected behaviour: The label will cut off its text when it tries to grow outside the bounds of 120 x 32.

0 Answers
Related