Click here to Skip to main content
15,886,067 members
Articles / Programming Languages / Java
Tip/Trick

Quick event handler in a Java class

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
19 Jan 2011CPOL 10.8K   1
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)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralNothing new. Pin
Igor Kushnarev19-Jan-11 19:52
professionalIgor Kushnarev19-Jan-11 19:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.