Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX8 - FXML How to call method with parameters in onAction-tag?

How is it possible to call a method with parameters out of FXML?

In Java I use this code:

textfield.setOnAction(event -> {
    endEdit(false);
});

In FXML I know I can call a method like this:

<TextField onAction="#endEdit">

So how can I call the method endEdit(Boolean) in FXML with the parameter false?

like image 415
S.Pro Avatar asked Jan 13 '15 12:01

S.Pro


1 Answers

You could just encapsulate the endEdit(...) method call in a @FXML annotated method that handles the action event. Something like this:

public class FXMLController implements Initializable {

    @FXML
    protected void handleTextFieldAction(ActionEvent e) {
        endEdit(false);
    }

    private void endEdit(boolean flag) {
        System.out.println("Flag value: " + flag);
        // Your implementation here
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }  
}

Then in your FXML file bind the text field's onAction property to this handleTextFieldAction(...) method like this:

<TextField onAction="#handleTextFieldAction" />

If the boolean flag actually depends on some conditions that have to be evaluated then you can process them within handleTextFieldAction(...) method and call endEdit(...) with the appropriate value.

like image 83
dic19 Avatar answered Sep 20 '22 10:09

dic19