Search code examples
javafxfocushtml-editor

How do I listen for HTMLEditor getting or losing focus?


I need to track when an HTMLEditor element in JavaFX gets focus or loses it. I used a listener for textArea, but it doesn't work in this case.

        htmlEditor.focusedProperty().addListener(((obs, oldValue, newValue) ->{
        if (newValue) { 
           // focus received
           
        }else{ 
           //focus is lost
        }
    }));

Solution

  • I did face the same issue while adding a ChangeListener to the focused Property where the listener was not being invoked. However, there is another possible workaround for this. You can simply access your Scene's focus owner Node and add a ChangeListener to it to detect the old and new focused Node which in your case is an HTMLEditor control which is a Node of type WebView. The code would look something like this:

    scene.focusOwnerProperty().addListener((observableValue, oldNode, newNode) -> {
                if(newNode instanceof WebView)
                {
                    System.out.println("HTML Editor focused");
                    // do something when HTMLEditor gets focused
                }
                else if(oldNode instanceof WebView) {
                    System.out.println("HTML Editor focus lost");
                    // do something when HTMLEditor loses focused
                }
            });