user3668541 user3668541 - 2 months ago 17
Java Question

JavaFx add child to custom node

I have a custom node that extends 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
}
}


I would like to create a circle that is on the right middle edge of the DragNode -- so the right middle edge of the BorderPane.

When I set the circle's position to be this.getBoundsInLocal().getMaxX or inpNode.getBoundsInParent().getMaxX it never seems to return the right value.

How do I get the width of the BorderPane that the class is extending?

Thanks in advance. I hope the question makes sense!

Answer

Recomended way is to add the all the Nodes using SceneBuilder or directly with fxml and not in the code.

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
    }
}