The Deep End

go to! email!

Tuesday, March 08, 2005

Java Apps: Events, Button-Clicks, and How to Make Your Program Work

Although adding buttons is fun and looks cool, it's a whole lot better when you can click on them and have things actually happen.

When the user clicks on a button (or moves a mouse or presses a key) it's called an Event. The general terminology is that an event gets "fired" (when you click that button) and to "catch" the event, you'll need to do a lot of stuff.

Firstly, your program will have to implement the ActionListener interface--this means that you have to have an actionPerformed() method somewhere in the class that is your app. The parameter to actionPerformed is an ActionEvent which is basically the event that's just occurred.

If you just have one button, then the actionPerformed method is all you'll need. Just type in the code that you want "performed" when the event fires--like
System.out.println("I've just been pressed!");

However, there are a few more things that you have to do:

1. Don't forget to put implements ActionListener next to your class name, and import the package java.awt.event.*.
2. When you create a button that you want actionPerformed to trap the events for, write this:
JButton btn = new JButton("Click Me, I'm Fatal");
This makes sense because you want to be "listening" for an event, and because this (which is your class) implements ActionListener, it is an ActionListener. It's also where the actionPerformed method is; it's all tied together!

If you have more than one button that you want to handle events for, use addActionListener(this) as usual, but in the actionPerformed method you'll need to write something like:
public void actionPerformed(ActionEvent e){
String action = e.getActionCommand();
if(action.equals("Click Me, I'm Fatal")){
else if(action.equals("I'm Another Button!")){
getActionCommand() returns the name of the Component.

There are lots of other events other than ActionEvent--like KeyEvent or MouseEvent, but they're pretty easy to understand once you've gotten ActionEvent. You'll have to add KeyListeners, MouseListeners, etc. and implement the MouseListener/KeyListener interfaces, but there are Java Tutorials for that.


Post a Comment

<< Home