register Listener For JavaFX Window Focus - Java JavaFX

Java examples for JavaFX:Window

Description

register Listener For JavaFX Window Focus

Demo Code


    //package com.java2s;
    import javafx.beans.InvalidationListener;

    import javafx.beans.value.ChangeListener;

    import javafx.scene.Node;

    import javafx.stage.Window;

    public class Main {
        public static void registerListenerForWindowFocus(Node n, InvalidationListener l) {

    ChangeListener<Window> windowListener = (observable, oldValue, newValue) -> {
        if (oldValue != null) {
            oldValue.focusedProperty().removeListener(l);
        }//from w ww  . j  ava 2s  .c om
        if (newValue != null) {
            newValue.focusedProperty().addListener(l);
        }
    };

    n.sceneProperty().addListener((observable, oldValue, newValue) -> {
        if (oldValue != null) {
            oldValue.windowProperty().removeListener(windowListener);
        }
        if (newValue != null) {
            newValue.windowProperty().addListener(windowListener);
            if (newValue.getWindow() != null) {
                newValue.getWindow().focusedProperty().addListener(l);
                l.invalidated(newValue.getWindow().focusedProperty());
            }
        }
    });
    if (n.getScene() != null) {
        n.getScene().windowProperty().addListener(windowListener);
    }
}
    }

Related Tutorials