package calculator; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class CalcController implements ActionListener { /** * String for sum command. */ public static final String SUM = "SUM"; /** * String for subtract command. */ public static final String SUBTRACT = "SUBTRACT"; /** * String for multiply command. */ public static final String MULTIPLY = "MULTIPLY"; /** * String for divide command. */ public static final String DIVIDE = "DIVIDE"; /** * String for clear command. */ public static final String CLEAR = "CLEAR"; private CalcModel model; private CalcView view; /** * Creates a controller with no view and no model. * */ public CalcController() { this.model = null; this.view = null; } /** * Invoked when an event occurs. * * @param event * The event. */ public void actionPerformed(ActionEvent event) { // Translates an event into something that the model can do. String action = event.getActionCommand(); if (action.equals(CalcController.CLEAR)) { this.getModel().clear(); } else { int userValue = 0; try { userValue = Integer.parseInt(this.getView().getUserValue()); } catch (NumberFormatException ex) { return; } if (action.equals(CalcController.SUM)) { this.getModel().sum(userValue); } else if (action.equals(CalcController.SUBTRACT)) { this.getModel().subtract(userValue); } else if (action.equals(CalcController.MULTIPLY)) { this.getModel().multiply(userValue); } else if (action.equals(CalcController.DIVIDE)) { if (userValue != 0) { this.getModel().divide(userValue); } } } int calcValue = this.getModel().getCalcValue(); this.getView().setCalcValue("" + calcValue); } /** * Returns the view of this controller. * * @return the view of this controller. */ public CalcView getView() { return this.view; } /** * Sets the view of this controller to the given view. * * @param view * the new view of this controller. * @pre. view != null */ public void setView(CalcView view) { this.view = view; } /** * Returns the model of this controller. * * @return the model of this controller. */ public CalcModel getModel() { return this.model; } /** * Sets the model of this controller to the given model. * * @param model * the new model of this controller. * @pre. model != null */ public void setModel(CalcModel model) { this.model = model; } }