XZ6H
XZ6H

Reputation: 1789

javafx Check if an object exists in scene

I'm new to both java and javafx. How can I check if any object like Rectangle or Button exists in the Stack Pane or in the scene ? Tried searching in google but couldn't find anything related to the same.

Upvotes: 2

Views: 8884

Answers (2)

Markus Weninger
Markus Weninger

Reputation: 12648

It seems to me that you are also searching for a way to check if a certain Node is a direct or indirect child of another Node or Scene.


Following a method that checks if a certain Node is a direct or indirect child of another Node. For that, it traverses the parent, the grandparent, and so on, and checks if it encounters the parent in question:

public static boolean isChildOf(Node nodeInQuestion, Node parentInQuestion) {
    Node cur = nodeInQuestion.getParent();
    while (cur != null) {
        if (cur == parentInQuestion) {
            return true;
        }
        cur = cur.getParent();
    }
    return false;
}

To check if a given Node is the root or an indirect child of a Scene, we can use a similar approach. This method traverses the node's parent chain up to the node's root and then compares the node's root to the scene's root (which is true if the node in question is part of the scene):

public static boolean isChildOf(Node nodeInQuestion, Scene sceneInQuestion) {
    Node rootOfNode = nodeInQuestion;
    while (rootOfNode.getParent() != null) {
        rootOfNode = rootOfNode.getParent();
    }
    return sceneInQuestion.getRoot() == rootOfNode;
}

Upvotes: 1

AlmasB
AlmasB

Reputation: 3407

To check if a Node (could be Button, Rectangle or any other UI node) is a direct child of another node (parent assumed, StackPane in your question) you can do the following:

stackPane = ...
if (stackPane.getChildren().contains(node)) {
    // node is a direct child of stackPane
}

Alternatively, you can call node.getParent() to obtain a reference to the parent node, if there is one.

Finally, by calling node.getScene() != null you can check if a node is part of a scene.

For full documentation refer to JavaFX API.

Upvotes: 6

Related Questions