2

我有 Hbox,里面有标签。这个盒子有时更小,有时更大。有什么方法可以强制它的子项(标签)调整大小,例如: label1 首先调整大小,如果它不能更小然后 label2 调整大小,如果它不能更小 label3 调整大小等?

4

1 回答 1

3

不,只有 3 种不同的调整大小行为。

  • NEVER
  • SOMETIMES
  • ALWAYS

NEVER显然不是您需要的,并且您不能以 3 种不同的方式制作 3 个孩子,而剩下的 2 个调整大小优先级。

您需要自己实现这种布局:

public class HLayout extends Pane {

    @Override
    protected void layoutChildren() {
        final double w = getWidth();
        final double h = getHeight();
        final double baselineOffset = getBaselineOffset();

        List<Node> managedChildren = getManagedChildren();
        int size = managedChildren.size();

        // compute minimal offsets from the left and the sum of prefered widths
        double[] minLeft = new double[size];
        double pW = 0;
        double s = 0;
        for (int i = 0; i < size; i++) {
            minLeft[i] = s;
            Node child = managedChildren.get(i);
            s += child.minWidth(h);
            pW += child.prefWidth(h);
        }

        int i = size - 1;
        double rightBound = Math.min(w, pW);
        // use prefered sizes until constraint is reached
        for (; i >= 0; i--) {
            Node child = managedChildren.get(i);
            double prefWidth = child.prefWidth(h);
            double prefLeft = rightBound - prefWidth;
            if (prefLeft >= minLeft[i]) {
                layoutInArea(child, prefLeft, 0, prefWidth, h, baselineOffset, HPos.LEFT, VPos.TOP);
                rightBound = prefLeft;
            } else {
                break;
            }
        }
        // use sizes determined by constraints
        for (; i >= 0; i--) {
            double left = minLeft[i];
            layoutInArea(managedChildren.get(i), left, 0, rightBound-left, h, baselineOffset, HPos.LEFT, VPos.TOP);
            rightBound = left;
        }
    }

}

请注意,您可能还应该覆盖计算首选项大小的实现。

示例使用:

@Override
public void start(Stage primaryStage) {
    HLayout hLayout = new HLayout();

    // fills space required for window "buttons"
    Region filler = new Region();
    filler.setMinWidth(100);
    filler.setPrefWidth(100);

    Label l1 = new Label("Hello world!");
    Label l2 = new Label("I am your father!");
    Label l3 = new Label("To be or not to be...");
    hLayout.getChildren().addAll(filler, l1, l2, l3);

    Scene scene = new Scene(hLayout);

    primaryStage.setScene(scene);
    primaryStage.show();
}
于 2017-02-24T14:07:02.943 回答