import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CalculatorGui { // just returns the name which should be used for a button public static String buttonName(ButtonType b) { switch (b) { // all the numbered ones just return the number part case N0: case N1: case N2: case N3: case N4: case N5: case N6: case N7: case N8: case N9: // return the name's substring starting at 1 return b.name().substring(1); // the rest case DOT: return "."; case PLUS: return "+"; case MINUS: return "-"; case TIMES: return "×"; case DIVIDE: return "÷"; case SQRT: return "√"; case EQUALS: return "="; case CLEAR: return "C"; } throw new IllegalArgumentException("Invlaid button type " + b.name()); } public static void main(String args[]) { // create the calculator object which handles calculations Calculator calc = new Calculator(); // create and set up the window. JFrame frame = new JFrame("Calculator"); // make the program close when the window closes frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // we need a "panel" for the grid buttons JPanel grid = new JPanel(); // create a grid layout for the 16 buttons other than clear and equals GridLayout layout = new GridLayout(4, 4); grid.setLayout(layout); // add those first 16 buttons to it for (int i = 0; i < 16; i++) { // find this button type ButtonType b = ButtonType.values()[i]; // create a GUI button for it with the right name String name = buttonName(b); JButton button = new JButton(name); // create a listener for it ButtonListener listener = new ButtonListener(b, calc); button.addActionListener(listener); // add it to the grid grid.add(button); } // now we create a vertical box layout for the textbox, grid of buttons // and the row of buttons at the bottom BoxLayout mainLayout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS); frame.getContentPane().setLayout(mainLayout); // add the calculator display line to the layout frame.getContentPane().add(calc); // add the grid frame.getContentPane().add(grid); // now create another panel and layout for displaying the two buttons at bottom JPanel bottom = new JPanel(); BoxLayout bottomLayout = new BoxLayout(bottom, BoxLayout.X_AXIS); // create the bottom two buttons and listeners for them JButton clear = new JButton(buttonName(ButtonType.CLEAR)); ButtonListener clearListener = new ButtonListener(ButtonType.CLEAR, calc); clear.addActionListener(clearListener); JButton equals = new JButton(buttonName(ButtonType.EQUALS)); ButtonListener equalsListener = new ButtonListener(ButtonType.EQUALS, calc); equals.addActionListener(equalsListener); // add them to the bottom panel bottom.add(clear); bottom.add(equals); // add the bottom row to the window frame.getContentPane().add(bottom); // display the window. frame.pack(); frame.setVisible(true); } }