For all programmers who are skilled in C-style languages, and beginners who fish for new experience with these!

Report article RSS Feed Listening to events in Java.

A short article showing how to handle events (click on a button, mouse move, ...) in Java.

Posted by moci on Nov 2nd, 2010
Basic Client Side Coding.

Working with events in Java is, to me, different from other languages I’ve seen. If you’ve ever worked with Visual Basic or Visual C#, and specially for me ActionScript 3 then you will have written event handlers like so:

function someHandler(event:EventType) {}

That’s it! In Java however you’re working with classes. As Java tries to be a full OO language you more or less always need to use a class for everything – which is a good thing most of the time! But in this case I had to take 5 extra minutes to get my handlers working! Here’s how.
You can ‘listen’ to these events in 3 different ways Classes, Inner Classes, Anonymous Classes.
A separate class

With this method you will create a separate class for each kind of event. The drawback of this method is the fact that you will lose all connection to the variables used in the main application. A solution for this problem is just to add your main application class as a parameter. Almost every parameter for a function is a reference (this means: if you change something to that parameter it will change everywhere – look up ‘by value’ and ‘by reference’ if you want to learn more about this exciting topic).
Here is an example of a small application class and a listener class.

java code:
//Main application class
public class ClassEvents extends JFrame {

  public static void main(String[] args) {
    new ClassEvents();
  }
 
  public ClassEvents() {
    JButton button = new JButton();
    button.setText("Click me");
    button.addActionListener(new ExternalEventListener());
    this.add(button);
   
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setPreferredSize(new Dimension(320, 240));
    this.pack();
    this.setVisible(true);
  }

}

//External listener class
public class ExternalEventListener implements ActionListener {

  @Override
  public void actionPerformed(ActionEvent arg0) {
    System.out.println("External class sais YO!");
  }

}
 

Via the ‘ActionEvent’ parameter you can check for the ‘target’ of this event. In this case a button.

An inner clas

This is the way I prefer to deal with events, inner classes are classes that you write inside of another class! This way you will remain inside the ‘parent’ class and be able to use all of the functions and parameters this class has to offer (think of this as the ‘function’ solution most other languages offer – actually the next method probably resembles the ‘function’ solution more…). Here’s how the inner class method works.

java code:
//Main application class
public class InnerClassEvent extends JFrame {
  private String message = "Inner class sais YO!";

  public static void main(String[] args) {
    new InnerClassEvent();
  }
 
  public InnerClassEvent() {
    JButton button = new JButton();
    button.setText("Click me");
    button.addActionListener(new InnerEventListener());
    this.add(button);
   
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setPreferredSize(new Dimension(320, 240));
    this.pack();
    this.setVisible(true);
  }
 
  //Inner listener class
  class InnerEventListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent arg0) {
      System.out.println(message);
    }

  }
}
 

Great isn’t it! Just add an inner class which can be treated like a real object, but it can still get all the variables and functions you created in the parent class. Another area where inner classes are a good solution is threads, but that’s for another article.

An anonymous inner class
You could argue that the inner class method and this method are practically the same – and you would be right. For me this method makes things a bit too chaotic when you’ve got listeners all over the place. With this method you are essentially creating an inline class (so creating a class inside a function). The problem here is that you might lose track of where this class was created when you’re scrolling through pages of code. Here’s an example of this method.

java code:
//Main application class
public class AnonymousEventListener extends JFrame {
  private String message = "Anonymous class sais YO!";
 
  public static void main(String[] args) {
    new AnonymousEventListener();
  }
 
  public AnonymousEventListener() {
    JButton button = new JButton();
    button.setText("Click me");
    button.addActionListener(new ActionListener() {
      //Anonymous listener class
      @Override
      public void actionPerformed(ActionEvent e) {
        System.out.println(message);
      }
    });
    this.add(button);
   
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setPreferredSize(new Dimension(320, 240));
    this.pack();
    this.setVisible(true);
  }
}
 

You create a new instance of the listener and its function right inside another function. I would probably forget I did that the next time I opened up this project. (In a bigger project of course).

Conclusion
Java has a “different” approach to events, I haven’t used it enough to say that it’s better… for now all I can say is that it’s another way of doing the same thing. And because you’re always inside an actual object you’ve got benefits of for example variables inside the listener or functions that only the listener needs (and would otherwise just add to the main application code, without any real purpose).

It’s up to you and your project to know what kind of method you’ll be using, but now you know the options. And because I’m not an expert and I only recently used these methods I’m probably skipping a few other ways of doing this.

Have a good coding day.

Post a Comment
click to sign in

You are not logged in, your comment will be anonymous unless you join the community today (totally free - or sign in with your social account on the right) which we encourage all contributors to do.

2000 characters limit; HTML formatting and smileys are not supported - text only

Established
Jul 20, 2010
Privacy
Public
Subscription
Open to all members
Contact
Send Message
Email
Members Only
Membership
Join this group
Group Watch
Track this group
Tutorial
Browse
Tutorials
Report Abuse
Report article
Related Groups
Curly Bracket Programming Realm
Curly Bracket Programming Realm Hobbies & Interests group with 74 members
Indie Devs
Indie Devs Hobbies & Interests group with 1,095 members