1

这是我的问题:我想得到一个水平方向的窗格,宽度适合他的内容(如 FlowPane),但如果宽度太高,窗格会包裹其内容。我不想按孩子的宽度计算“prefWidth”或“prefWrappingLength”,因为它们很多。

在线程JavaFX FlowPane Autosize中,他们提供了包装文本的解决方案,但不提供布局。

你有什么建议给我吗?

4

1 回答 1

0

对于那些正在寻找答案的人,这就是我最终所做的,忽略了丰富的孩子限制:

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)曾经拥有最终宽度的孩子。因此,如果有人拥有更好的解决方案,请提供!

于 2017-05-30T07:29:29.627 回答