Search code examples
nodesjavafx-8pane

How can I determine the layering of panes in JavaFX


I would like to persist a workspace and then restore it when the user opens the window a second time.

For example I have the following:

//Create the workspace there the panes will live
Pane workspace = new Pane();
//Create the layers - assume there is code to allow these to be dragged and moved
Pane layer1 = new Pane();
Pane layer2 = new Pane();
Pane layer3 = new Pane();

workspace.getChildren().addAll(layer1, layer2, layer3);

I know I can select which layer is on top by doing the following:

layer2.toFront();

However what I can't seem to find is the ability to determine which layer is currently on top.

i.e.

layer1.setOnToFront(event -> {});
layer1.setOnToBack(event -> {});

or even

boolean onTop = layer1.isOnTop();

Is there a way to determine where a node is so when the workspace is open, the front pane can be made visible again?

Thanks!


Solution

  • The rendering order (back to front) of nodes in a Pane, is based upon the index of the node in the pane's child list.

    So you can determine the index of a given node using the following function:

    int idx = pane.getChildren().indexOf(layerX);
    

    You can determine the top node using:

    Node top = 
        pane.getChildren.size() > 0
            ? pane.getChildren().get(pane.getChildren().size() - 1)
            : null;
    

    You can listen for changes in node order using a ListChangeListener:

    pane.getChildren().addListener(new ListChangeListener<Item>() {
        public void onChanged(Change<Item> c) {
            while (c.next()) {
                // process the next change.
            }
        }
    });