This is in a javafx program and it runs.
button.setOnAction(_ ->{
int side = 0;
Random rand = new Random();
side = rand.nextInt(2);
if(side == 0){
//code here
else{
//code here
}
});
A long version of this functionality would be to create the class that implements the EventHandler. Then create a instance of that class for the button.setOnAction. I do not understand how the lambda works the same as the longer code below. How does it know to use the EventHandler functional interface. I watched many YouTube videos that do not go into the details which is why I ask here.
class Handler implements EventHandler<ActionEvent>{
@Override
public void handle(ActionEvent actionEvent) {
int side = 0;
Random rand = new Random();
side = rand.nextInt(2);
if(side == 0){
}
else{
}
}
}
button.setOnAction
isbutton.setOnAction(EventHandler<ActionEvent>)
.EventHandler
is created at runtime.EventHandler<ActionEvent>
is the functional interface being implemented is explained by Elliott's comment—it can infer the type from the context.setOnAction
method, at a fundamental level, simply takes the object passed to it as an argument—which must be an implementation ofEventHandler<ActionEvent>
—and adds it to a collection. Whenever the button receives anActionEvent
, the code will iterate that collection and invoke each appropriate handler'shandle
method. Research the observer pattern for more information.