Search code examples
javajavafxnullpointerexceptionbooleanscene

BooleanProperty whose value depends on if a node is added to a Scene


I'm working on a slide menu for JavaFX, and in the definition of it I constantly make use of the getScene() method for referencing the height and width of the scene to which the node is added.

The problem is that the slide menu is defined before the scene does, returning a NullPointerException.

I think that a workaround for this would be creating a BooleanProperty with a listener that each time that the value of the property changes, would check if it's true or false, executing the lines of code that involve a call to the getScene() method or not, respectively.

How could I achieve this? I thought that I could do this by saying

BooleanProperty hasScene = new SimpleBooleanProperty();
hasScene.set(getScene());
hasScene.set(Boolean.valueOf(getScene()));
hasScene.set((boolean) getScene());

but it's not possible to cast from Scene to Boolean.

Any ideas? Thanks in advance.


Solution

  • hasScene.bind(sceneProperty().isNotNull());