| 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 | import javax.swing.*; import java.awt.GridLayout; import java.awt.event.ActionListener; public class CalculatorView { private JButton[] button_array = new JButton[4]; private String[] button_name = {"+", "-", "*", "/"}; private JTextField input; public CalculatorView() { // 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(); input = new JTextField("0.0", 8); // Use GridLayout for equals positioning. JPanel action_buttons = new JPanel(new GridLayout(2,2)); for(int i = 0; i < button_name.length; i++) { button_array[i] = new JButton(button_name[i]); action_buttons.add(button_array[i]); } totalGUI.add(input); totalGUI.add(action_buttons); 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); } // 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); } |
| 52 53 54 55 56 57 58 59 | // 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); } |