import javax.swing.*; import java.awt.*; import java.awt.event.*; // the ButtonListener handles each button press public class ButtonListener implements ActionListener { // each button listener stores which button it is listening to // it also stores the calculator object so it can tell it when // the buttons are pressed private ButtonType button; private Calculator calc; // given the button we are listening for, and the calculator object public ButtonListener(ButtonType button, Calculator calculator) { this.button = button; this.calc = calculator; } @Override public void actionPerformed(ActionEvent e) { // check which button we are listening for switch (button) { case N0: case N1: case N2: case N3: case N4: case N5: case N6: case N7: case N8: case N9: // for any of the digits, find out what digit it is // then add it to the calculator String stringDigit = button.name().substring(1); int digit = Integer.parseInt(stringDigit); calc.addDigit(digit); break; // for the other buttons, call the appropriate calculator method case DOT: calc.setDot(); break; case PLUS: calc.setOperator('+'); break; case MINUS: calc.setOperator('-'); break; case TIMES: calc.setOperator('*'); break; case DIVIDE: calc.setOperator('/'); break; case SQRT: calc.sqrt(); break; case EQUALS: calc.equals(); break; case CLEAR: calc.clear(); break; } } }