// // FILE: AddingFrame.java // AUTHOR: Stuart Reges // DATE: 1999/08/27 // COMMENT: Class AddingFrame provides the user interface // for a graphical adding machine. // // MODIFIED: 2012/09/10 by Eugene Wallingford // CHANGE: Updated constructor // to name the window for CS 2530. // Changed updateDisplay() // to send the accumulator a displayValue() message. // Changed constructor // to use class that implements an interface. // import javax.swing.*; import java.awt.*; import java.awt.event.*; public class AddingFrame extends CloseableFrame { private Accumulator myAccumulator; // accumulator for math private JTextField myText; // text display public AddingFrame() { // create frame and accumulator setSize(200, 250); setTitle("CS 2530 Adder"); Container contentPane = getContentPane(); myAccumulator = new BasicAccumulator(); // create and add text field for current display myText = new JTextField("0", 20); contentPane.add(myText, "North"); myText.setHorizontalAlignment(JTextField.RIGHT); // create and add button panel for adding machine JPanel buttons = createButtonPanel(); contentPane.add(buttons, "Center"); // create and add clear button at the bottom JButton clear = new JButton("Clear"); clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myAccumulator.clear(); updateDisplay(); } }); contentPane.add(clear, "South"); } private JPanel createButtonPanel() // post: creates a panel of buttons with digits placed as // in an adding machine, with minus and plus buttons // surrounding 0 in the bottom row. Adds listeners // to each button to modify accumulator and update // the display. { JPanel buttons = new JPanel(); buttons.setLayout(new GridLayout(4, 3)); digitButton(buttons, 7); digitButton(buttons, 8); digitButton(buttons, 9); digitButton(buttons, 4); digitButton(buttons, 5); digitButton(buttons, 6); digitButton(buttons, 1); digitButton(buttons, 2); digitButton(buttons, 3); JButton minus = new JButton("-"); minus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myAccumulator.minus(); updateDisplay(); } }); buttons.add(minus); digitButton(buttons, 0); JButton plus = new JButton("+"); plus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myAccumulator.plus(); updateDisplay(); } }); buttons.add(plus); return buttons; } private void digitButton(JPanel buttons, final int value) // post: adds a single digit button to the buttons panel // and adds a listener that calls the accumulator // with that digit value. { JButton b = new JButton("" + value); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myAccumulator.addDigit(value); updateDisplay(); } }); buttons.add(b); } private void updateDisplay() // post: updates the text display to the current display // value returned by the accumulator { myText.setText("" + myAccumulator.displayValue()); } }