简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM