Anonymous inner classes
On the previous page, we looked at the notion of
listeners
in Swing. Recall the part of our code to handle the button click looks as follows:
public static void main(String[] args) {
...
ActionListener listener = new MyListener();
butt.addActionListener(listener);
...
}
class MyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "You clicked me!");
}
}
A problem with this pattern is that it's a little clumsy. To get round some
of the clumsiness, the compiler allows us to use a shorthand called an
anonymous inner class. The code looks as follows:
public static void main(String[] args) {
...
butt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "You clicked me!");
}
});
}
The class is an inner class because it's defined inside another
class (our "main" class in this case). And it's anonymous because we
don't actually define it as a subclass with a name that we'll re-use to
create multiple instances. Behind the scenes, the compiler will
expand this code to look something like the first example above.
It will generate some class that implements ActionListener and put our
actionPerformed() method inside the generated class definition,
then create an instance of that class. But to us the programmer, it allows
us to write slightly more succinct code, and keep the "nitty-gritty" of
the button handler next to the rest of the code that sets up the button.
Using the IDE to help you with listeners
If you're using an IDE such as Eclipse (and it's strongly recommended that
you do use one for Swing programming), then the IDE can help you with the
syntactic messiness of listeners. See the Swing components
overview, where we give a list of common listeners and an illustration
of how Eclipse can help you write them.
Next: text fields and labels
Armed with this knowledge for writing event handlers
slightly more easily, we go on to look at two more types of component:
text fields and labels.
Then, we begin to look at how to determine where in the window
a component is placed, with component layouts.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.