About the action of a button

I added a button on my program and want to catch the event listener. I found there are two ways to do this:

1.

JButton button =new JButton("button");

button.addActionListener(new ActionListener(){

publicvoid actionPerformed(ActionEvent e){

//...

}

});

2

JButton button =new JButton("button");

button.setModel(new MyButtonModel());

class MyButtonModelextends DefaultButtonModel{

protectedvoid fireActionPerformed(ActionEvent e){

//...

}

}

I don't know which one is better. And what's the different between these tow?

[1279 byte] By [youhaodiyia] at [2007-11-27 9:04:33]
# 1

interesting article here:

http://thor.prohosting.com/~javarox/swing/swingtut2.html

I've seen your first example used everywhere. I've not seen the second example used, but then I've not been at Java for long. My guess is that it may be useful for more complex Swing apps where the data model of basic components need to be changed -- though I could easily be wrong, and hopefully if I am, someone will correct this.

petes1234a at 2007-7-12 21:37:52 > top of Java-index,Desktop,Core GUI APIs...
# 2

I never worked with ButtonModels but I think it's like this:

Methods like fireActionPerformed inform all registered listeners that an event occured (as the API doc says). If you have to do something in that class itself, which fires the event, you can override that method to avoid registering to itself. But I think this is rarly the case with buttons/ button models. I suggest just to use ActionListeners/ Actions normally .

-Puce

Message was edited by:

Puce

Pucea at 2007-7-12 21:37:52 > top of Java-index,Desktop,Core GUI APIs...
# 3

1) is a standard way of handling the button press (one of several standard ways, actually). You could define your class to implement ActionListener and use addActionListener(this), for example. Or you could create a concrete subclass of ActionListener, and pass a new one of those to addActionListener(). Or you could create a class that extends AbstractAction, and pass that to your JButton constructor.

fireActionPerformed() is how the button actually causes the ActionListener in 1) to be called. I dare say you probably don't want/need to override how that action gets called; you just want to respond to it.

Stick with 1).

mbmerrilla at 2007-7-12 21:37:52 > top of Java-index,Desktop,Core GUI APIs...