Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY


418


staticJButton subtract; // Subtract button
staticJButton clear; // Clear button

// Define event listener for numeric buttons
static classNumericHandler implements ActionListener
{
public voidactionPerformed(ActionEvent event)
// Handle events from the buttons in calcPane
{
double secondOperand; // Holds input value
String whichButton; // Holds the button's name
// Get the operand
secondOperand =
Double.parseDouble(inputField.getText());
whichButton = event.getActionCommand(); // Get the button's name

if(whichButton.equals("+")) // When the name is "add"
result = result + secondOperand; // add the operand
else // Otherwise
result = result – secondOperand; // subtract the operand

register.setText(""+ result); // Display result
inputField.setText(""); // Clear input
}
}

static class ClearHandler implementsActionListener
{
public voidactionPerformed(ActionEvent event)
// Handle events from the Clear button in calcPane
{
result = 0.0; // Set result back to zero
register.setText("0.0"); // Reset result in register
inputField.setText(""); // Clear input
}
}

public static voidmain(String[] args)
{
operation = newNumericHandler(); // Instantiate a NumericHandler
clearOperation = newClearHandler(); // Instantiate a ClearHandler
result = 0.0; // Initialize result

// Instantiate labels and initialize input field
resultLabel = newJLabel("Result:");
register = newJLabel("0.0", JLabel.RIGHT);
entryLabel = newJLabel("Enter #:");
inputField = newJTextField("", 10 );
Free download pdf