JavaFx добавляет дочерний узел в пользовательский узел

У меня есть собственный узел, который расширяет 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, которую расширяет класс?

Заранее спасибо. Я надеюсь, что вопрос имеет смысл!

1 ответ

Решение

Рекомендуемый способ добавить все 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
    }
}
Другие вопросы по тегам