// CalcController.java - Controller // Handles user interaction with listeners. // Calls View and Model as needed. // Fred Swartz -- December 2004 // Paolo Bucci -- November 2009 (modified) import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class CalcController { // ... The Controller needs to interact with both the Model and View. private CalcModel m_model; private CalcView m_view; // ========================================================== constructor /** Constructor */ public CalcController(CalcModel model, CalcView view) { this.m_model = model; this.m_view = view; // ... Initialize view this.m_view.setTotal(this.m_model.getValue()); // ... Add listeners to the view. view.addMultiplyListener(new MultiplyListener()); view.addClearListener(new ClearListener()); } // //////////////////////////////////////// inner class MultiplyListener /** * When a multiplication is requested. 1. Get the user input number from the * View. 2. Call the model to multiply by this number. 3. Get the result * from the Model. 4. Tell the View to display the result. If there was an * error, tell the View to display it. */ private class MultiplyListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String userInput = ""; try { userInput = CalcController.this.m_view.getUserInput(); CalcController.this.m_model.multiplyBy(userInput); CalcController.this.m_view.setTotal(CalcController.this.m_model .getValue()); } catch (NumberFormatException nfex) { CalcController.this.m_view.showError("Bad input: '" + userInput + "'"); } } } // end inner class MultiplyListener // ////////////////////////////////////////// inner class ClearListener /** * 1. Reset model. 2. Reset view. */ private class ClearListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { CalcController.this.m_model.reset(); CalcController.this.m_view.setTotal(CalcController.this.m_model .getValue()); } } // end inner class ClearListener }