Event Handlers


If you were to run the code developed in the previous section and press the Compute button, nothing would happen because we have not built in the code that will detect and respond to when the button is pressed. Before we do that, we need to back up and discuss the concept of events.

When you interact with a GUI you expect that something will happen. For example, when you press the Compute button, you expect the application to run. For this to happen, there has to be a mechanism that (a) detects when the button has been pressed and (b) calls the appropriate method or block of code to respond to that action.

The way Java implements this functionality is by using what are known as events. An event is an instance of an event class. Though not limited to GUI applications, events are typically used to encapsulate some sort of GUI interaction. Almost everything you do around a GUI window will generate events. If you move the mouse across the window you will generate MouseEvents . If you press a JButton you will generate an ActionEvent . If you change the selected value of a JList you will generate a ListSelectionEvent . The system takes care of all of the event generation for you.

Now that we are generating events, we need to be able to respond to them. Java does this using what is known as a delegation model. All this means is that the event handling is disconnected from the event source. When an event is generated, the system checks to see if there are any event handlers of the appropriate type registered to the event source. If there are, the system sends the event object to one of the methods defined by the event handler. To define event handlers, Java uses a type of interface known as an event listener interface. These interfaces declare methods that respond to a given type of event. An instance of a class that implements one of these interfaces is an event listener.

A GUI component registers an event listener by adding the event listener to a list maintained by the component. A component can register any number of event listeners. A JButton might register both an ActionListener and a MouseListener , for example. One great feature of the delegation model is that you can pick and choose which events you will respond to. For example, the JComboBox object of the AtmGUI class will generate an ItemEvent when the selected item changes. We don't need to do anything with this event, so we simply ignore it.

This has been a brief overview of the Java event model. We haven't discussed all of the possible event classes and event listener interfaces, nor have we covered things like user -defined event classes or how to manipulate the event dispatching thread. For more information on events and event handling, see Java Event Handling by Grant Palmer.

Now that we know a little bit about events, let's add event handling capability to the AtmGUI class. The component we want to do this for is the Compute button. When this button is pressed, we want a USatm76 object to be created and the corresponding atmospheric conditions to be written into the JTextArea . Whenever a JButton is pressed, an ActionEvent is generated. We need to create an ActionListener class, register the ActionListener with the JButton , and implement the actionPerformed() method of the ActionListener to respond to the event.

The first thing to do is to create an ActionListener class. This is done simply by defining a class that implements the ActionListener interface and the actionPerformed() method defined in that interface. Under the delegation model, any class can serve as an ActionListener . We could define the ActionListener to be a separate class from AtmGUI or an inner class of AtmGUI . To keep things simple, we will define the AtmGUI class itself to be the ActionListener .

 public class AtmGUI extends JFrame                              implements ActionListener 

The ActionListener interface declares one method named actionPerformed() . Because the AtmGUI class now implements the ActionListener interface, it must also implement the actionPerformed() method. The first thing actionPerformed() does is create a USatm76 object using the current values of the JComboBox and JTextField components . The value of the JTextField component is converted to a value of type double . The previous contents of the JTextArea are cleared using the setText() method. The current atmospheric results are then written into the JTextArea using the append() method. The actionPerformed() method source code follows .

 public void actionPerformed(ActionEvent event) {   String units = (String)comboBox.getSelectedItem();   double altitude =                Double.parseDouble(textField.getText());   atm = new USatm76(units, altitude);   String label[] = atm.getLabels();   textArea.setText("");   textArea.append("geometric altitude    = " +                    atm.getAltitude()+label[0]);   textArea.append("\ngeopotential altitude = " +             atm.getGeoPotentialAltitude()+label[1]);   textArea.append("\ntemperature           = " +                    atm.getTemperature()+label[2]);   textArea.append("\npressure              = " +                    atm.getPressure()+label[3]);   textArea.append("\nmolar mass            = " +                    atm.getMolarMass()+label[4]);   textArea.append("\ndensity               = " +                    atm.getDensity()+label[5]); } 

The final thing to do is to have the Compute button register the ActionListener by calling the addActionListener() method on it. Because the AtmGUI class itself is serving as the ActionListener , the method is passed the this reference.

 runButton.addActionListener(this); 

This code is placed in the AtmGUI code listing after the Compute button is created.



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net