On 27/06/2012 6:21 PM, Patricia Shanahan wrote:
> On 6/27/2012 2:44 PM, bilsch wrote:
> ...
>> The listeners all call a statement in the second file:
>>
>> public void actionPerformed(ActionEvent event)
>>
>> so I don't understand how a button listener can be different from
>> another button listener.
>
> You can write several different implementing classes for an interface
> such as ActionListener. You can then create different instances of the
> same implementing class.
>
> For example, you could have a NumberKeyListener class that implements
> ActionListener, and takes a constructor parameter that tells it the
> value associated with its button. On the other hand, I would have a
> different class for dealing with backspace.
>
> Code like:
>
> one.addActionListener(new NumberKeyListener(1));
> two.addActionListener(new NumberKeyListener(2));
>
> would get rid of a lot of checking which button was pressed.
Another option uses the ActionEvent the listener gets passed, a
parameter that's frequently ignored:
public void actionPerformed (ActionEvent e) {
JButton btn = (JButton)(e.getSource());
String btnTxt = btn.getText();
// btnTxt should be "0", "1", ..., or "9".
// Do something with it.
}
Of course, this action listener will blow up if used on something other
than a JButton. You also might not like the results if you later
localize the button labels using a ResourceBundle or something.

In
the event that that sort of thing is likely, the numeric-parameter
approach Patricia suggested is more robust. Another possibility is:
private static Map<JButton,Integer> buttonMap;
....
for (int i = 0; i < 10; i++) {
JButton btn = new JButton("" + i);
btn.addActionListener(new NumberKeyListener());
buttonMap.add(btn,i);
}
....
public void actionPerformed (ActionEvent e) {
int btnNum = buttonMap.get(e.getSource());
}
Note: will throw NPE if attached to something other than a button that's
in buttonMap. Also, for buttonMap to be visible in actionPerformed,
NumberKeyListener needs to be a nested class of the class with the rest
of this code.