JavaFX - FlowPane 自动调整大小

JavaFX - FlowPane Autosize

这是我的问题:我想要一个水平方向且宽度适合其内容的 Pane(如 FlowPane),但如果宽度太高,Pane 会包裹其内容。我不想用 children 宽度来计算 'prefWidth' 或 'prefWrappingLength',因为它们很多。

在线程 中,他们提供了环绕文本的解决方案,但没有提供布局的解决方案。

你有什么建议吗?

对于那些正在寻找答案的人,这是我最终所做的,忽略了大量 children 约束:

class RuleBox extends FlowPane {
    int maxWrapLength;
    int margin = 30;

    RuleBox(int maxWrapLength) {
        super();
        this.maxWrapLength = maxWrapLength;
        getChildren().addListener((ListChangeListener<? super Node>) observable -> actualizeWrapLength(observable.getList()));
    }

    private void actualizeWrapLength(ObservableList<? extends Node> list) {
        new Thread(() -> {
            try { Thread.sleep(50);
            } catch (InterruptedException ignored) {}
            Platform.runLater(() -> {
                int totalWidth = 0;
                for(Node n : list) {
                    if(n instanceof Control) totalWidth+=((Control)n).getWidth();
                    else if(n instanceof Region) totalWidth+=((Region)n).getWidth();
                }
                if(totalWidth+margin>maxWrapLength) setPrefWrapLength(maxWrapLength);
                else setPrefWrapLength(totalWidth+margin);
            });
        }).start();
    }

    void actualizeWrapLength() {
        actualizeWrapLength(getChildren());
    }
}

这是一个非常肮脏的代码,尤其是 Thread.sleep(50) 曾经有 children 的最终宽度。所以如果有人拥有更好的解决方案,请提供!