Listening for Action
To Listen for an action like a mouse click or key press you use a Listener class.
There are several different types of Listener classes and this tutorial only talks about one
of them. To find out about the rest, consult a Swing Reference book like the one suggested
earlier. I like to use my Listeners as internal classes, so if you don't like that, TOO BAD!
We will be using ActionListener to learn how to use Listener objects.
ActionListener listens for a mouse click over a component. We will use it with a JButton to
do something when the JButton is clicked.
Here's the code to get a JFrame with a JPanel and a JButton:
JFrame frame = new JFrame("ActionListener Test");
JPanel panel = new JPanel();
JButton button1 = new JButton("Click Me!");
frame.setSize(256,256);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
panel.add(button1);
frame.pack();
frame.show();
Now we want to add a new ActionListener to JButton button1 :
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e1) {
// CODE TO RUN WHEN BUTTON CLICKED GOES HERE
}});
I realize that is probably a little simplistic, but we want to keep things
simplistic, don't we? Of course we do! So all this code does is make an internal class of
an ActionListener with it's method actionPerformed(ActionEvent e1) that runs when the
ActionListener detects (hears?) an action such as our button being clicked.
That's the basics of Action Listening, for more, go buy a good book. Get off the computer!
Go do something, ride your bicycle, or something! A book is better for your eyes anyway than
the RF Radiation coming from this screen! whew, there's my rant for this section.
Conclusion
I hope you had fun, Java is a neat language.
More people should use it, as it has a large and usefull API and it
runs on so many platforms. The interpreter has also gotten quite
fast, so speed is no longer a reason for not using it.
I recommend going to http://java.sun.com/ and using the API docs, they are essential!