5

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?

S.Pro
  • 633
  • 2
  • 12
  • 23

1 Answers1

8

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.

dic19
  • 17,821
  • 6
  • 40
  • 69
  • 1
    Thanks for your answer. I thought there could be a way to call the method directly out of the FXML, so there would be less code necessary. – S.Pro Jan 14 '15 at 07:33
  • 3
    You're welcome. It would be nice but: *"In general, a handler method should conform to the signature of a standard event handler; that is, it should take a single argument of a type that extends javafx.event.Event and should return void (similar to an event delegate in C#). The event argument often carries important and useful information about the nature of the event; however, it is optional and may be omitted if desired."* Extracted [from here](http://docs.oracle.com/javafx/2/api/javafx/fxml/doc-files/introduction_to_fxml.html#controller_method_event_handlers) (applies to JavaFX8 too) @S.Pro – dic19 Jan 14 '15 at 11:17