package calculator; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.math.BigInteger; public class CalcController implements ActionListener { /** * String for open command. */ public static final String OPEN = "OPEN"; /** * String for save command. */ public static final String SAVE = "SAVE"; /** * 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.OPEN)) { File f = this.getView().getOpenFile(); this.getModel().open(f); BigInteger lastUserValue = this.getModel().getLastUserValue(); this.getView().setUserValue(lastUserValue.toString()); } else if (action.equals(CalcController.SAVE)) { File f = this.getView().getSaveFile(); this.getModel().save(f); } else if (action.equals(CalcController.CLEAR)) { this.getModel().clear(); } else { BigInteger userValue = null; try { userValue = new BigInteger(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.equals(BigInteger.ZERO)) { this.getModel().divide(userValue); } } } BigInteger calcValue = this.getModel().getCalcValue(); this.getView().setCalcValue(calcValue.toString()); } /** * 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; } }