我有内部标签的hbox。这个盒子有时更小,有时更大。是否有任何方法可以强制其孩子(标签)进行调整大小,例如:Label1首先调整大小,如果不能更小,则Label2的大小,如果它不能较小的Label3进行调整,那么?
不,只有3种不同的调整行为。
-
NEVER
-
SOMETIMES
和 -
ALWAYS
NEVER
显然不是您需要的,您不能以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;
}
}
}
请注意,您可能还应该覆盖计算pref尺寸的实现。
示例使用:
@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();
}