Resize JavaFX Label if overrun

Simsala picture Simsala · Jan 26, 2016 · Viewed 8.9k times · Source

I have a Label in a GridPane in a TitledPane. I want it to downsize stepwise by 0.05em if it is overrun so the three dots ("Long Labe...") dont show up -> "Long Label" in small.

An isOverrun()-method for the Label would be great but JavaFX doesnt supply that and life isn't a wishconcert.
So my workarround so far:

    Bounds tpBounds = tPane.getBoundsInLocal();
    Bounds lblBounds = label.getBoundsInLocal();
    Double fontSize = 1.0;

    while (tpBounds.getWidth() < lblBounds.getWidth() && fontSize > 0.5) {
        fontSize = fontSize-0.05;
        label.setStyle("-fx-font-size: "+fontSize+"em;");

        System.out.println(fontSize+" "+tpBounds.getWidth()+" "+lblBounds.getWidth());
    }

The problem: during the while loop, bounds.getWidth() is always showing the original width. The "new" width with the new fontsize is not refreshing quick enough to get catched by the while-condition, so the fontsize is getting lower and lower.
Any Solutions?

edit
I ask more commonly: Is it really THAT HARD to make a Label downsize itself, till it fits without truncating?!

Answer

Andr&#233; picture André · Mar 4, 2017

One other way which is working is:

.setMinHeight(Region.USE_PREF_SIZE)

Simple and much easier than calculate it.