[英]How to set own resize priority in Javafx's HBox
我有带有标签的Hbox。 这个盒子有时更小,有时更大。 是否有任何方法可以强制其子项(标签)调整大小,例如:label1首先调整大小,如果不能缩小,则label2调整大小,如果不能缩小,label3调整大小等?
不,只有3种不同的调整大小行为。
NEVER
SOMETIMES
和 ALWAYS
显然,这NEVER
是您所需要的,并且您不能以剩余的2个调整大小优先级的3种不同方式来制作3个孩子。
您需要自己实现这种布局:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.