Re: Button event



You can also write a generic action listener which will invoke a method
on an object:

public class GenericActionListener implements ActionListener {

protected Method method;
protected Object object;

public GenericActionListener(Object object, String methodName) {
this.object = object;
try {
method = object.getClass().getMethod(methodName, null);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}

// this invokes the method
public void actionPerformed(ActionEvent e) {
try {
method.invoke(object, null);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}

So, if you have a controller class (say, GUIController), create methods
like "save", "open", "close", etc. in it:

public class GUIController {
...
public void save() {
...
}
...
}

Then, for your buttons, simply do this:

// assuming you have a variable for the GUIController called
"guiController"
// (or you can use "this" if your GUI is itself the controller
JButton saveButton = new JButton(...);
saveButton.addActionListener(new GenericActionListener(guiController,
"save"));

When the button is clicked, the method guiController.save() will be
invoked. It's a nice way to keep your code clean, IMO.

You can also extend GenericActionListener to use methods that have
arguments. I'm just showing the bare bones.

- Natasha -

jaap wrote:
Hello

I'm a real noob with java. I worked for 4 years with php but now I have
to use java.
I'm looking for a clean way to get an action behind a button/menuitem. I
already found the class actionListener. but the method actionpreformed
is not very clean if you want to give 20 buttons an action. The way I
know is 20 times else if. There must be an better method.

I will try to use my GUI like an interface. It does'nt have to include
much code in my opinion. I think it have to be only some field and
button delcarations.

thx for your help

greetz
Jaap

.