Up to this point, you have been taught to create private inner classes for event handlers. For example, suppose we wanted to add an event handler to a JavaFX Button.
Button btn = new Button("Click me");
You've been taught to create a private inner class to handle the event:
private class MyHandler implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World");
}
}
An instance of MyHandler is passed to the Button's setOnAction method.
Button btn = new Button("Click me");
btn.setOnAction(new MyHandler());
This approach works well when you want a single event handler to handle multiple GUI elements. It also works well when the code inside the handle method is long.
As a precursor to anonymous classes, you have already seen and used anonymous objects.
// The anonymous object is: new Color(255, 0, 0)
pen.setColor(new Color(255, 0, 0));
An anonymous class is a class that that is declared, defined, and instantiated at the same time, without giving it a name. Using an anonymous class is useful when you only need to use the class once.
Button btn = new Button();
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
}
);
The general syntax for anonymous classes is: Note: The parameters are the constructor parameters of the superclass, if needed.
new Class(${parameters}) {
//body of the class
}
Class with Properties:
Object o = new Object(){
String s = "I love anonymous classes!";
@Override
public String toString(){
return s;
}
}
Another Example:
Button button = new Button();
button.setOnMouseClicked(new EventHandler<MouseEvent>(){
public void handle(MouseEvent me) {
System.out.println("Mouse exited");
}
}
);
Robotics Example:
// robotControlLoop is a timer
// parameters for scheduleAtFixedRate are (TimerTask, int, int)
robotControlLoop.scheduleAtFixedRate(
new TimerTask(){
@Override
public void run() {
Scheduler.getInstance().run(); //runs the bot
}
},
0,20);
Advantages You can put your event-listening code in a separate class/file to separate the creation of a GUI element from how it responds thereby breaking your program into distinct parts with different roles.
Disadvantages When creating your own EventHandler, you are likely writing a separate class that is not reusable in other programs. In object-oriented programming, you should write reusable classes whenever possible. When you create your own EventHandler class, you end up using it as a template class, changing only the handle() method with each different use. That's a lot of code for something used only once. Reusing code as a template (where you copy the same code but replace a section of it for a specific use) is known as “boilerplate code.” Java 7 introduced Anonymous classes to avoid this problem.
Last modified: March 09, 2023