我有一个扩展BorderPane的自定义节点:
package main.resources.nodes;
import ...
public class DragNode extends BorderPane {
public DragNode () {
setNodes();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/main/resources/fxml/DragNode.fxml"));
fxmlLoader.setController(this);
fxmlLoader.setRoot(this);
try {
fxmlLoader.load();
} catch (IOException e) {
e.printStackTrace();
}
}
private void setNodes() {
Circle inpNode = new Circle();
this.getChildren().add(inpNode);
inpNode.setRadius(10.0);
inpNode.setCenterX(this.getBoundsInParent().getMaxX());
inpNode.setCenterY(this.getBoundsInParent().getMaxY() / 2.0);
System.out.println(this.getBoundsInParent()); // Prints 'BoundingBox [minX:0.0, minY:-5.0, ... ]'
System.out.println(this.getParent()); // Prints null
System.out.println(this.getChildren()); // Prints 1
}
}
我想创建一个位于DragNode的右中间边的圆圈 - 所以是BorderPane的右边缘。
当我将圆圈的位置设置为this.getBoundsInLocal()。getMaxX或inpNode.getBoundsInParent()。getMaxX时,它似乎永远不会返回正确的值。
如何获得该类正在扩展的BorderPane的宽度?
提前致谢。我希望这个问题有道理!
答案 0 :(得分:2)
推荐的方法是使用Nodes
或直接使用SceneBuilder
添加所有fxml
,而不是代码。
在这里你必须等
FXMLLoader
来初始化fxml 布局或否则您可能会遇到问题:
public class DragNode extends BorderPane implements Initializable{
public DragNode () {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/main/resources/fxml/DragNode.fxml"));
fxmlLoader.setController(this);
fxmlLoader.setRoot(this);
try {
fxmlLoader.load();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
//call it here so you are sure fxml layout has been initialized
setNodes();
}
private void setNodes() {
Circle inpNode = new Circle();
this.getChildren().add(inpNode);
inpNode.setRadius(10.0);
inpNode.setCenterX(this.getBoundsInParent().getMaxX());
inpNode.setCenterY(this.getBoundsInParent().getMaxY() / 2.0);
System.out.println(this.getBoundsInParent()); // Prints 'BoundingBox [minX:0.0, minY:-5.0, ... ]'
System.out.println(this.getParent()); // Prints null
System.out.println(this.getChildren()); // Prints 1
}
}