如果溢出则调整 JavaFX 标签的大小

Sim*_*ala 2 label resize javafx ellipsis overrun

我在 TitledPane 的 GridPane 中有一个标签。如果超出范围,我希望它逐步缩小 0.05em,这样三个点(“长标签...”)就不会显示 -> “长标签”小。

Label 的 isOverrun() 方法会很棒,但 JavaFX 不提供该方法,而且生活也不是一场愿望音乐会。
所以到目前为止我的解决方法:

    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());
    }
Run Code Online (Sandbox Code Playgroud)

问题:在 while 循环期间,bounds.getWidth() 始终显示原始宽度。新字体大小的“新”宽度刷新速度不够快,无法被 while 条件捕获,因此字体大小越来越小。
有什么解决方案吗?

编辑
我更常问:缩小标签本身,直到它适合而不被截断,真的那么难吗?

小智 6

另一种有效的方法是:

.setMinHeight(Region.USE_PREF_SIZE)
Run Code Online (Sandbox Code Playgroud)

简单,比计算容易得多。