Model-View-Controller - Part 5

Oh no! The boss has arrived and is very under whelmed by the GUI I created in the third section. Luckily, with the MVC structure, I can take out the first GUI and put in another without changing any of the underlying controls or data or methods.

The new plan is to have a number pad where we can put in numbers, so as to stop the users having to type it in.

I've had to change the name of the class here to CalculatorView_2, because I can't have two instances of the same file on my website! This would mean changing all the CalculatorView class calls to CalculatorView_2 in the Controller and main class. Just pretend for this that it's still called CalculatorView :)

In the new View class, I've created a panel of numbered buttons which are linked to a actionListener within the View class. This deals with the updating of the view, which is fine as it does not affect the data within the Model.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class CalculatorView_2 implements  ActionListener
{
    private JButton[] button_array = new JButton[4];
    private JButton[] numbered_array = new JButton[11];
    private String[] button_name = {"+", "-", "*", "/"};
    private String[] numbered_name = {"1", "2", "3", "4", "5", "6", "7", "8",
                                      "9", "0", "."};
    private JTextField input;
    private boolean new_amount = true, decimal = true;

    public CalculatorView_2()
    {
        // Create and show the GUI.
        createAndShowGUI();
    }

    // Create the content pane which displays the buttons and widgets on-screen.
    private JPanel createContentPane()
    {
        JPanel totalGUI = new JPanel(new BorderLayout(10, 10));

        input = new JTextField("0.0", 8);
        input.setEditable(false);

        // Use GridLayout for equals positioning.
        JPanel action_buttons = new JPanel(new GridLayout(4,1));

        for(int i = 0; i < button_name.length; i++)
        {
            button_array[i] = new JButton(button_name[i]);
            action_buttons.add(button_array[i]);
        }

        // *** NEW ***
        // Added a panel for the numbered buttons on the page.

        JPanel number_buttons = new JPanel(new GridLayout(4,3));

        for(int i = 0; i < numbered_name.length; i++)
        {
            numbered_array[i] = new JButton(numbered_name[i]);
            numbered_array[i].addActionListener(this);
            numbered_array[i].setActionCommand(numbered_name[i]);
            number_buttons.add(numbered_array[i]);
        }

        totalGUI.add(input, BorderLayout.PAGE_START);
        totalGUI.add(number_buttons, BorderLayout.CENTER);
        totalGUI.add(action_buttons, BorderLayout.LINE_END);
        
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    // As before, we create the frame and add the created content pane.
    private void createAndShowGUI()
    {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] Calculator [=]");

        // Set the content pane.
        frame.setContentPane(createContentPane());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    // This is the new ActionPerformed that deals with adding the amount to
    // the calculator input correctly.
    public void actionPerformed(ActionEvent ae)
    {
        String temp = ae.getActionCommand();

        // If the calculator is ready for a new amount, clear the TextField
        // and toggle the flag.
        if(new_amount)
        {
            input.setText("");
            new_amount = false;
        }

        // If the button pressed is a decimal point, be sure that there is no
        // exisiting decimal point, then add it to the screen.
        if(temp.equals("."))
        {
            if(decimal)
            {
                decimal = false;
                input.setText(input.getText()+""+temp);
            }
        }
        // Else add the number to the screen.
        else
        {
            input.setText(input.getText()+""+temp);
        }
    }

    // Here we add the ActionListener passed by the Controller to each of the buttons
    public void buttonActionListeners(ActionListener al)
    {
        for(int i = 0; i < button_name.length; i++)
        {
            button_array[i].setActionCommand(button_name[i]);
            button_array[i].addActionListener(al);
        }
    }

    // Gets the text from the Text Box and converts it into a Double.
    public double getFieldText()
    {
        try{
            return Double.parseDouble(input.getText());
        }
        catch(NumberFormatException nfe)
        {
            System.out.println("Error");
            return -1;
        }
    }

    // Sets the text displayed on the Text Box.
    public void setFieldText(String message)
    {
        input.setText(""+message);
        new_amount = true;
        decimal = true;
Picture of CalculatorView

As you can see, the GUI is quite different (or at least a little more advanced) than the previous example in section 3. I've used a Border Layout on the bottom JPanel to get the effect you see, along with a separate JPanel for the numbered buttons (in a Grid Layout) and for the command buttons (another GridLayout).

To start, we've introduced two boolean flags to determine when a new value is ready to be entered, and when there is already a decimal point in the number.
15
    private boolean new_amount = true, decimal = true;
We've changed the JTextField to be un-editable, so as to prevent any abnormal inputs from the user.
28
29
        input = new JTextField("0.0", 8);
        input.setEditable(false);
We simply create the JButtons in the same fashion as before, adding a ActionCommand onto each to make updating the JTextField much simpler.
43
44
45
46
47
48
49
50
51
        JPanel number_buttons = new JPanel(new GridLayout(4,3));

        for(int i = 0; i < numbered_name.length; i++)
        {
            numbered_array[i] = new JButton(numbered_name[i]);
            numbered_array[i].addActionListener(this);
            numbered_array[i].setActionCommand(numbered_name[i]);
            number_buttons.add(numbered_array[i]);
        }
Finally, we add an actionPerformed method to deal with the users interaction with the numbered buttons, making sure they are properly displayed on the screen.
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
    // This is the new ActionPerformed that deals with adding the amount to
    // the calculator input correctly.
    public void actionPerformed(ActionEvent ae)
    {
        String temp = ae.getActionCommand();

        // If the calculator is ready for a new amount, clear the TextField
        // and toggle the flag.
        if(new_amount)
        {
            input.setText("");
            new_amount = false;
        }

        // If the button pressed is a decimal point, be sure that there is no
        // exisiting decimal point, then add it to the screen.
        if(temp.equals("."))
        {
            if(decimal)
            {
                decimal = false;
                input.setText(input.getText()+""+temp);
            }
        }
        // Else add the number to the screen.
        else
        {
            input.setText(input.getText()+""+temp);
        }
    }
Hopefully from all this you have realised the sheer power of a good design and structure behind the code you work on. It will make things less complicated, easier to explain, easier to DO and will even save you time in the long run!

I really hope this site has been of use to you. If it has, has not, or you have any comments please e-mail me by hitting the contact me button at the bottom of the page.

Good luck!
Back Top Next
Email Me
Code Style


Required Lessons

External Links

Created and Edited by Stuart Davidson
All Rights Reserved ©

Valid XHTML 1.0 Strict