The question seems simple, but there is a specific way I have to implement my code that is causing confusion. So in step #3 I need to register the source object with the event h
to register ButtonHandler
with btn1 as pointed out by @c0der
btn1.setOnAction(new ButtonHandler());
Use the setOnAction
method of the Button class to define what will happen when a user clicks the button.
This snippet of code explain how we use anynomous class in method :
button.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
label.setText("Accepted");
}
});
We can override handle method in custom class and add it like this :
button.setOnAction(new CustomHandle());
You should know that ActionEvent
is an event type that is processed by EventHandler. An EventHandler object provides the handle method to process an action fired for a button.
You can use the Button class to set as many event-handling methods as you need to cause the specific behavior or apply visual effects.In this case we use button.addEventHandler(EventType,EventObject)
.
button.addEventHandler(MouseEvent.MOUSE_ENTERED,
new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent e) {
button.setEffect(shadow);
}
});