Event Handling


The GUI must be able to handle user input. The way Java (and most languages) handles user input is based on the event model, in which the GUI receives user actions and calls methods in response. Specifically, the developer decides which GUI components will listen for events and the specific events for which these components will listen. The developer then writes appropriate listener classes for these events. Each listener class must implement the appropriate interface corresponding to the event type, either directly or by extending an adapter. Within each listener class, the developer writes the code for the methods that will be called when the appropriate event occurs.

The following example illustrates the search button in a GUI listening for an event. The certification assignment requires that you write a search algorithm. (A generic algorithm is discussed in Chapter 7, "Databases and Atomicity," as part of the database topic.) However, you must also decide how the user can initiate a search. The following code shows one approach to performing a search on a database caused by a user clicking the search button and illustrates how to handle this click-button event:

 //in the GUI building section: searchButton = new JButton("Search Seats"); searchButton.setToolTipText("Search the database now"); searchButton.addActionListener( new SearchButtonHandler()); //Later in the GUI class, //you can use an inner class that implements ActionListener //to respond to user clicks on the search button. public class SearchButtonHandler implements ActionListener {     String criteria = "",            previousCriteria = "",            seatCriteria = "";     public void actionPerformed( ActionEvent e )     {         // Finds the criteria from combo box,         // which eliminates typing errors.         seatCriteria = (String)searchComboBox                          .getSelectedItem();         criteria = ((JLabel)searchLabelName.elementAt(0))                        .getText()                        + "='" + searchCriteria +"',";         if (!criteria.equalsIgnoreCase(previousCriteria))         {             try             {                  resultSet = database.search(criteria);             } catch(RemoteException rex)             {                  System.out.print(rex);             } catch(DatabaseException dex)             {                  System.out.print(dex);             }             previousCriteria = criteria;             //process the resultSet         }     } } 


JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 187

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