gpt4 book ai didi

java - 如何在Javafx的HBox中设置自己的调整大小优先级

转载 作者:行者123 更新时间:2023-11-30 02:38:28 24 4
gpt4 key购买 nike

我有 Hbox,里面有标签。这个盒子有时较小,有时较大。有没有办法强制它的子级(标签)调整大小,例如:label1 首先调整大小,如果不能更小,则 label2 调整大小,如果不能更小,则 label3 调整大小等?

最佳答案

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

  • 从不
  • 有时
  • 始终

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

关于java - 如何在Javafx的HBox中设置自己的调整大小优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42438834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com