How perform task on JavaFX TextField at onfocus and outfocus? How perform task on JavaFX TextField at onfocus and outfocus? java java

How perform task on JavaFX TextField at onfocus and outfocus?


I thought it might be helpful to see an example which specifies the ChangeListener as an anonymous inner class like scottb mentioned.

TextField yourTextField = new TextField();yourTextField.focusedProperty().addListener(new ChangeListener<Boolean>(){    @Override    public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue)    {        if (newPropertyValue)        {            System.out.println("Textfield on focus");        }        else        {            System.out.println("Textfield out focus");        }    }});

I hope this answer is helpful!


You can use the focusedProperty of Node to attach a ChangeListener.

Extending the answer from Brendan: from JavaFX8 (as it comes with Java 8), a lambda expression combined with a ternary operator can make it really compact:

textField.focusedProperty().addListener((obs, oldVal, newVal) ->     System.out.println(newVal ? "Focused" : "Unfocused"));


You will want to attach a ChangeListener to the FocusProperty of the TextField that you wish to monitor.

In JavaFX, you can attach notification events (Change or Invalidation Listeners) to any JavaFX property that an object may possess as long as the property meets the minimum definition for a JavaFX bean.

Refer to this post if your event handlers will be doing other things such as modifying Cancel or Default button settings: JavaFX 2 -- Setting the defaultButton property: mutually exclusive?

Here is some code to attach a Change Listener to a text box:

txtDx.focusedProperty().addListener(m_txtDxListener);

The Listener object has been stored in an instance field so that it may be used with both addListener() and removeListener(). For a short lived TextField, you can specify the listener object with an anonymous inner class.

Here is the private class that I wrote for my focus listener:

private class FocusPropertyChangeListener implements ChangeListener<Boolean> {    FocusPropertyChangeListener() { System.out.println("New FPCL instance"); }    @Override    public void changed(ObservableValue<? extends Boolean> ov,         Boolean oldb, Boolean newb) {        System.out.println("Focus change triggered");        if (ancEncEditor.isVisible() && !ancEncEditor.isDisabled()) {            boolean b = (newb != null && newb.booleanValue() == true);            System.out.println("txtDx focus change event triggered: DxAdd = " + b);            if (b) { btnDxAdd.setDefaultButton(true); }            else { btnWindowCommit.setDefaultButton(true); }            btnWindowCommit.setCancelButton(true);            btnDxAdd.setDefaultButton(b);        }    }}