javafx – Focus event not fxml

Question:

In the fxml file of a GUI we can direct code to a method when a certain event occurs.
For action events, it would be something like this:

<Button fx:id="btn1" onAction="#actionPause" />

But what about if the object was focused?
In my case, I'm looking for this to use in a TextField to remove its default content and change its style.

Please stick to resolutions for fxml files.

Answer:

Unfortunately you can't do this directly in fxml. Events that can be set directly in FXML are: setOnAction, Drag & Drop (Drag and Drop), Keyboard, Mouse, Rotation, Slide and Zoom.

But in your code you can do the following:

public class FXMLDocumentController implements Initializable{

@FXML
// Link entre o controlador e a interface
private TextField idtextfield;

// ... Algum código

public void initialize(URL url, ResourceBundle rb){
    /* Adicionando um listener para capturar mudanças de foco
    *  Obs.: O primeiro componente de cima para baixo normalmente recebe o foco
    *  da aplicação, então tenha cautela 
    */
    idtextfield.focusedProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            // newValue terá o valor do foco atual, oldValue o valor anterior
            // Se estiver com o foco o valor será true
            System.out.println(newValue);
         }
    });

See the full list of events available in FXML by searching for setOn: TextField (JavaFX 8)

Scroll to Top