Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Quick event handler in a Java class

0.00/5 (No votes)
19 Jan 2011CPOL 10.9K  
Quick event handler in a Java class
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:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)