Listeners are how anything gets done in Swing. Clicking on stuff causes
Events. Events are sort of like little messages that get sent around
inside your program. If you want, you can watch all these messages and try
to filter out the ones you want. That would be a colossal waste of time, on
top of being really, really inefficient. There are better ways to do things.
Namely, Event Listeners.
Event Listeners are functions you define that will be called when Events
happen. The JFC/Swing core tells each Component - like JButtons and JMenus -
when an Event they would be interested in occurs. This is how JButtons know to
make themselves look "clicked". You can also ask a JButton to tell you when
it gets clicked by registering an Event Listener with it. If you were to write
Java code with Emacs, there would be 3 steps involved in registering an
Event Listener with a JButton:
1 - Define the listener:
There are different kinds of Events, so there are different kinds of
Listeners. JButton generates an ActionEvent when it is clicked, so we
create a class that implements the ActionListener interface...
class AnActionListener implements ActionListener{
public void actionPerformed(ActionEvent actionEvent){
System.out.println("I was selected.");
}
}
2 - Create an instance of the listener
Ok, this is pretty simple...
ActionListener actionListener = new AnActionListener();
3 - Register the listener with a component
Start out by pretending you already have a JButton and you want that
listener function we wrote in step 1 to get called when J. Random User
clicks on it. You do this by registering it with the JButton.
Essentially you ask the JButton to add it to the list of functions it
calls when it decides to generates an ActionEvent, like so...
JButton button = new JButton();
... // other code
button.addActionListener(actionListener);
Visual Age to the Rescue!
Most programs have lots of buttons. And Menus. And List boxes. And Other
Stuff (tm). Writing Event Listeners for all of these would be tedious and
error-prone. Debugging Event Listeners isn't much fun either. That's why
we have Visual IDE's (Integrated Development Environments). In VAJ, you
can draw some buttons and other components, then do some pointy-clicky stuff
and VAJ will create and manage all those Event Listeners for you. Most of
the time you don't even have to write any code! Ok, I'm getting a little
too excited, that's it for Listeners.
Back to the Tutorial
|