我有一个扩展 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 的宽度?
提前致谢。我希望这个问题有意义!
最佳答案
推荐的方法是使用 SceneBuilder
或直接使用 fxml
添加所有节点
,而不是在代码中。
Althought here you have to wait
FXMLLoader
to initialize the fxml layout or otherwise you may have problems:
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
}
}
关于JavaFx 将子节点添加到自定义节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39652188/