Command Buttons and Event Handlers

Each command button has associated with it common method that is triggered when the user selects that button. BreezySwing provides a default event handler method named buttonClicked that does nothing. However, an application normally overrides this method by defining a method with the same name in the application window’s class. Here is the code for associating this event handler method with the command button in the tax calculator program:

JButton convertButton = addButton ("Compute", 4,1,2,1);

public void buttonClicked(JButton buttonObj){
    double income = incomeField.getNumber();
    int numDependents = dependentsField.getNumber();
    double exemptionAmount = exemptionField.getNumber();
    double tax = (income - numDependents * exemptionAmount) * .15;
    taxField.setPrecision(2);
    taxField.setNumber(tax);
}

The JButton argument to the buttonClicked method is the button where the click occurred. If an application has more than one command button, the programmer uses an if/else statement in the buttonClicked method to determine which button was clicked and to take the appropriate action. For example, a program to convert between degrees Fahrenheit and degrees Celsius might have two command buttons:

The temperature conversion program includes a single event handler for the two command buttons:


port javax.swing.*;
import BreezySwing.*;

public class TemperatureConvert extends GBFrame{
    JLabel degreesFahrenheitLabel      = addLabel ("Degrees Fahrenheit", 1,1,1,1);
    DoubleField degreesFahrenheitField = addDoubleField (32.0,           1,2,1,1);
    JLabel degreesCelsiusLabel         = addLabel ("Degrees Celsius",    2,1,1,1);
    DoubleField degreesCelsiusField    = addDoubleField (0.0,            2,2,1,1);
    JButton fToCButton                 = addButton ("F to C",            3,1,1,1);
    JButton cToFButton                 = addButton ("C to F",            3,2,1,1);

    // Use if/else statement to determine which button is clicked

    public void buttonClicked(JButton buttonObj){
        double fahrenheit, celsius;
        if (buttonObj == fToCButton){
            fahrenheit = degreesFahrenheitField.getNumber();
            celsius = (fahrenheit  - 32) * 5.0 / 9.0;
            degreesCelsiusField.setNumber (celsius);
        }
        else {
            celsius = degreesCelsiusField.getNumber();
            fahrenheit = celsius * 9.0 / 5.0 + 32;
            degreesFahrenheitField.setNumber (fahrenheit);
        }           
    }

    public static void main(String[] args){
        JFrame frm = new TemperatureConvert();
        frm.setTitle ("Temperature Conversion");
        frm.setSize (500, 100);
        frm.setVisible (true);
   }
}

© Ken Lambert. All rights reserved.