Example - Calc Main, Example - Calc GUI, Example - Calc Extensions
This is the source for the graphical user interface of a simple calculator. It shows how a listener can be shared by many buttons, which then get the "action command" from the button and decide what to do with it. All the numeric buttons share one listener and all operators share another.
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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
/** CalcGUI.java - Subclass of JPanel for Calc GUI
@author Fred Swartz
@version 2004-04-20 Rodenbach
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
////////////////////////////////////////////////////////// class CalcGUI
class CalcGUI extends JPanel {
//=============================================== instance variables
//--- Component referenced during execution
private JTextField _displayField; // display result / input.
//--- Variables representing state of the calculator
private boolean _startNumber = true; // true: num key next
private int _resultValue = 0; // result so far
private String _previousOp = "="; // previous operation
//========================================= static (class) variables
private static final Font BIGGER_FONT =
new Font("monspaced", Font.PLAIN, 20);
//====================================================== constructor
public CalcGUI() {
//--- Display field
_displayField = new JTextField("0", 12);
_displayField.setHorizontalAlignment(JTextField.RIGHT);
_displayField.setFont(BIGGER_FONT);
//--- Clear button
JButton clearButton = new JButton("CLEAR");
clearButton.setFont(BIGGER_FONT);
clearButton.addActionListener(new ClearListener());
//--- One listener for all numeric keys.
ActionListener numListener = new NumListener();
//--- Layout numeric keys in a grid. Generate the buttons
// in a loop from the chars in a string.
String buttonOrder = "789456123 0 ";
JPanel buttonPanel = new JPanel(new GridLayout(5, 3));
for (int i = 0; i < buttonOrder.length(); i++) {
String keyTop = buttonOrder.substring(i, i+1);
if (keyTop.equals(" ")) {
buttonPanel.add(new JLabel(""));
} else {
JButton b = new JButton(keyTop);
b.addActionListener(numListener);
b.setFont(BIGGER_FONT);
buttonPanel.add(b);
}
}
//--- One ActionListener to use for all operator buttons.
ActionListener opListener = new OpListener();
//--- Create panel with gridlayout to hold operator buttons.
// Use array of button names to create buttons in a loop.
JPanel opPanel = new JPanel(new GridLayout(5, 1));
String[] opOrder = {"+", "-", "*", "/", "="};
for (int i = 0; i < opOrder.length; i++) {
JButton b = new JButton(opOrder[i]);
b.addActionListener(opListener);
b.setFont(BIGGER_FONT);
opPanel.add(b);
}
//--- Layout the top-level panel.
this.setLayout(new BorderLayout());
this.add(_displayField, BorderLayout.NORTH );
this.add(buttonPanel , BorderLayout.CENTER);
this.add(opPanel , BorderLayout.EAST );
this.add(clearButton , BorderLayout.SOUTH );
}//end constructor
//====================================================== action_clear
/** Called by Clear btn action listener and elsewhere.*/
private void action_clear() {
_startNumber = true;
_displayField.setText("0");
_resultValue = 0;
_previousOp = "=";
}
/////////////////////////////////////// inner listener class OpListener
/** Listener for all op buttons. */
class OpListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// The calculator is always in one of two states.
// 1. A number must be entered -- this operator is wrong.
// 2. An operator must be entered -- we're ok.
if (_startNumber) { // Error: needed number, not operator
action_clear();
_displayField.setText("ERROR");
} else {
_startNumber = true; // Next thing must be a number
try {
// Get value from display field, convert, do prev op
// If this is the first op, _previousOp will be =.
String displayText = _displayField.getText();
int currentValue = Integer.parseInt(displayText);
if (_previousOp.equals("=")) {
_resultValue = currentValue;
} else if (_previousOp.equals("+")) {
_resultValue += currentValue;
} else if (_previousOp.equals("-")) {
_resultValue -= currentValue;
} else if (_previousOp.equals("*")) {
_resultValue *= currentValue;
} else if (_previousOp.equals("/")) {
_resultValue /= currentValue;
}
_displayField.setText(""+_resultValue);
} catch (NumberFormatException ex) {
action_clear();
_displayField.setText("Error");
}
//--- set _previousOp for the next operator.
_previousOp = e.getActionCommand();
}//endif _startNumber
}//endmethod
}//end class
//////////////////////////////////// inner listener class ClearListener
// Action listener for numeric keys
class NumListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String digit = e.getActionCommand(); // Get text from button
if (_startNumber) {
// This is the first digit, clear field and set
_displayField.setText(digit);
_startNumber = false;
} else {
// Add this digit to the end of the display field
_displayField.setText(_displayField.getText() + digit);
}
}
}//end class
//////////////////////////////////// inner listener class ClearListener
class ClearListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
action_clear();
}
}
}//endclass CalcGUI
|