I don't really see any valid reason for doing this: you're basically asking for a controller to invoke user events on the view, instead of doing what it normally does and update the model.
So I guess the closest thing I could come up with would be something like this. Suppose you had (using the canonical JavaFX example), a Person
class:
public class Person {
private final StringProperty firstName = new SimpleStringProperty() ;
private final StringProperty lastName = new SimpleStringProperty() ;
private final StringProperty email = new SimpleStringProperty() ;
public StringProperty firstNameProperty() {
return firstName ;
}
public final String getFirstName() {
return firstNameProperty().get();
}
public final void setFirstName(String firstName) {
firstNameProperty().set(firstName);
}
// etc etc
}
and then an editor of some kind. You can create a map in the editor mapping each text field to an action to perform, and then register a single event handler with each text field that invokes the corresponding action. Your button could iterate through the map and call all the actions:
public class PersonEditor {
private TextField firstNameTextField ;
private TextField lastNameTextField ;
private TextField emailTextField ;
private Button okButton ;
public PersonEditor(Person person) {
// create controls, do layout, etc etc...
// map textfields to an action on the person:
Map<TextField, Consumer<String>> actions = new HashMap<>();
actions.put(firstNameTextField, person::setFirstName);
actions.put(lastNameTextField, person::setLastName);
actions.put(emailTextField, person::setEmail);
// set individual event handlers on each text field:
actions.entrySet().forEach(entry -> {
TextField tf = entry.getKey();
tf.setOnAction(e -> entry.getValue().accept(tf.getText()));
});
// event handler for button:
okButton.setOnAction(e -> {
// invoke action on each text field:
actions.entrySet().forEach(entry -> entry.getValue().accept(entry.getKey().getText()));
// do other stuff if needed...
}
}
}
.fireEvent(new ActionEvent())
to fire myTextField
s action handler. I did have to iterate through everyTextField
and callfireEvent
on each one though. I haven't used aButton
to do that before. I guess its the possibility of a start.okButton.setDefaultButton(true);
. It really is that easy.