In JavaFX how do I determine if the node gaining focus is a child node of myself?


Question

I'm working with a TableView in JavaFX. What I'd like to do is keep track of edits made to the table. When the user navigates away from the table, I want to check if there have been any edits, and if so, prompt the user to ask if they want to save their changes.

I have the TableView working, and I can track edits, and I can determine when the TableView loses focus (using a focusedProperty change listener).

However, the problem is that when a cell is clicked to edit, the focusedProperty change listener for the table fires (the editing cell gains focus, the table itself loses it). What I really want is a way to tell if, when focus changes, is it changing to a child node of the table (such as a column or cell) or something outside of the table (selecting a different tab on the parent GUI). But I don't want to have to add listeners to every other possible node one could click.

If I knew how to get the currently-focused item (haven't seen how to do that), I could call getParent() recursively and check if the TableView is in that list, and if so, I'd know it's a child. But I haven't seen a generic way to just get the currently focused node within an app.

There's no good generic way to iterate through children of the table, because getChildrenUnmodifiable() returns me Node() types (I suppose I could cast each to determine if they each had more children), or I'd have to go to TableColumns then cells from there (and check graphic for each cell).

I'd probably go with iterating through children recursively, casting as needed, and checking isFocused() at this point, barring a better solution. But I'm hoping someone here might have a better solution to this problem, and preferably a more generic solution.

1
3
7/18/2013 6:33:37 PM

I went with the search from a Node, casting to children and checking if the focused node was a child. It's not elegant - it certainly feels like there should be a better way. But here's the method I used to do so:

private boolean isChildFocused(javafx.scene.Parent parent)
{
    for (Node node : parent.getChildrenUnmodifiable())
    {
        if (node.isFocused())
        {
            return true;
        }
        else if (node instanceof javafx.scene.Parent)
        {
            if (isChildFocused((javafx.scene.Parent)node))
            {
                return true;
            }
        }
    }
    return false;
}

It seems to work fine (at least using a TableView as the root level parent), calling this when the focusedProperty() of the parent changes to false (via property change listener).

6
7/19/2013 2:48:54 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon