总是当我尝试在 Java 中获取数组的宽度时,它只返回 0,我不知道为什么。有人可以向我解释它是如何正确完成的吗?
Label label = new Label();
label.setFont(Font.font(label.getFont().getFamily(), 8));
label.setText(""
+ a[i][j].getList().getFirst().getLength()
+ " mal "
+ intToColor(a[i][j].getList().getFirst()
.getColor()));
label.relocate((x1 + x2) / 2 - label.getWidth() / 2, (y1 + y2) / 2);
label.idProperty().set("trackName");
label.setTextFill(Color.web("GREEN"));
field.getChildren().addAll(path, label);
System.out.println(label.getLayoutBounds().getWidth());
System.out.println(label.getWidth());//... also i tested a lot of different getters but i couldn't get the label width (same problem with height)
希望你知道我必须做什么。
@汤姆森汤姆
做了这个:
label.prefWidth(-1);
label.prefHeight(-1);
label.impl_processCSS(true);
// label.resizeRelocate(x, y, width, height);
System.out.println(label.getWidth());
但它没有用 - 你能更准确地解释我需要做什么吗?
最佳答案
要获得您需要调用 prefWidth(-1) 和 prefHeight(-1) 的宽度,只有在通过 resizeRelocate 对控件进行布局后才会设置布局边界
要在舞台显示之前获得正确的宽度,您还需要调用 impl_processCSS(true) 这是一个 NONE 公共(public) API,但目前没有更好的方法 IIRC
HBox h = new HBox();
Label l = new Label("Hello");
h.getChildren().add(l);
Scene s = new Scene(h);
l.impl_processCSS(true);
System.err.println(l.prefWidth(-1)+"/"+l.prefHeight(-1));
关于java - 如何在 javafx 中获取 label.getWidth(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21074024/