I don't know how many people use this, but it's very
short and sweet in a Java class when creating an event handler.
Instead of creating an external event-handler class separately, just put this sort of a code in your constructor or any method called by the constructor and it will be far quicker (but less neater) than defining a separate class for that event handler..:cool:
The code below is for a button (btn1
) the title of which changes when it is clicked from "Click Me!" to "I was clicked!". It is placed inside the constructor of the class "TestClass
"...
TestClass() {
btn1.addActionListener(new ActionListener() {
public void actionListener(ActionEvent ae) {
btn1.setText("I was clicked!");
}
});
}
Similar handlers could be created, say, by using "Adapters" rather than "Listeners" also. When using Adapters, you don't have to override all the Listener methods..
Now, instead of this, an event handler class could have been created and an instance of it would have been created and supplied to the
addActionListener() method. :-D
Anyway, I would say that in more organised code the longer second method should be applied for the sake of tidyness and organised programming!
:sigh: