1

I made a calculator in Java, but some of the code is very repetitive. Here is what I used to add an ActionListener

    one.addActionListener(handlerOne);
    two.addActionListener(handlerOne);
    three.addActionListener(handlerOne);
    four.addActionListener(handlerOne);
    five.addActionListener(handlerOne);
    six.addActionListener(handlerOne);
    seven.addActionListener(handlerOne);
    eight.addActionListener(handlerOne);
    nine.addActionListener(handlerOne);
    zero.addActionListener(handlerOne);

    add.addActionListener(handlerOne);
    subtract.addActionListener(handlerOne);
    multiply.addActionListener(handlerOne);
    divide.addActionListener(handlerOne);
    sqrt.addActionListener(handlerOne);
    exp.addActionListener(handlerOne);
    equals.addActionListener(handlerOne);
    cls.addActionListener(handlerOne);
    modulus.addActionListener(handlerOne);

Is there any way to shorten this up?

WillumMaguire
  • 537
  • 2
  • 10
  • 21
  • 1
    I would replace the `ActionListener` by an `Action`. Also see [this answer](http://stackoverflow.com/a/12463553/1076463). – Robin Oct 29 '12 at 14:45

4 Answers4

4

You could put all your components (buttons) in a List an attach the listener by some code like

for( Component c : componentsList ) {
  c.addActionListener(yourListener);
}
t3chris
  • 1,390
  • 1
  • 15
  • 25
1

Use a JButton[] for all or some (only digit buttons maybe) of your buttons. Then iterate over that array and add ActionListener to the buttons:

JButton[] buttons = new JButton[10]; // For digit buttons.

int i = 0;

for(JButton button: buttons)
   buttons[i++].addActionListener(handlerOne);

Similarly you can use a JButton[] for the operator buttons. By using different arrays, you can avoid possible confusions, I think.

Juvanis
  • 25,802
  • 5
  • 69
  • 87
0

Create a method that will create buttons and assign a listener to it. You still end up with a bunch of calls, but at least all the button creation and initialization code will reside in the same method, so it will be easier for you to modify it for every button.

Laf
  • 7,965
  • 4
  • 37
  • 52
0

There may be another alternative - add all your button to a single container and add your listener to that container.

Germann Arlington
  • 3,315
  • 2
  • 17
  • 19