JavaFX - FlowPane Autosize

946 Views Asked by At

Here's my problem: I would like to get a Pane with horizontal orientation and a width fitting with his content (like FlowPane), but if the width is too high, the Pane wraps its content. I don't want to calculate the 'prefWidth' or 'prefWrappingLength' by the children width because they are plentiful.

In the thread JavaFX FlowPane Autosize, they are giving solutions for wrapping text, but not for layouts.

Have you some tips for me?

1

There are 1 best solutions below

0
On BEST ANSWER

For those who are looking for an answer, here's what I finally did, ignoring the plentiful children constraint:

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());
    }
}

This is a pretty dirty code, especially for the Thread.sleep(50) used to have the final width of children. So if someone owns a better solution, please give it!