Recognizing and handling user actions, such as when the user presses a button like add or delete, is based on the general Java Applet Event and Listener mechanisms.
First, certain Applet components, such as Buttons, ScrollBars, Mouse movements, etc. generate Java Events when the user presses, moves, or otherwise interacts with one of these components. Java supports different types of events for different components. In the current context, we will be concerned only with Action events, but the mechanisms for other kinds of events are similar.
Second, when an object, such as a Button, is defined which can generate an event, it must be associated with a particular class that will be notified when that object generates an event. This is referred to as adding a Listener.
Third, when a class is defined that will be notified that a component has generated a particular kind of event, it must implement a Java Interface appropriate for that particular kind of event. Implementing an Interface, of course, involves implementing one or more methods that will be used by the JVM to notify the class that such an event has been generated.
Adding a Listener
// define buttons buttonAdd = new JButton ( "Add" ); buttonAdd.setBackground ( getColorYellow() ); buttonAdd.addActionListener ( this );
publicclass AppletAB extends JApplet implements ActionListener{
public void actionPerformed (ActionEvent e) {
String userAction = e.getActionCommand(); int userActionMapped = UserAction.mapUserAction( userAction );if ( userActionMapped == UserAction.ERROR ) {
txtareaMessage.setText( "Error: Unrecognized userAction." ); return;
}
// prepare dataBean and requestBean BeanPerson personBean = mapDataToDataBean(); RequestBean requestBean = new RequestBean(); requestBean.setDataBean( personBean ); requestBean.setUserAction( userAction );// send request to server ResponseBean responseBean = sendRequest( requestBean ); // handle logout condition if ( userActionMapped == UserAction.LOGOUT ) { sendLogout(); return; } // map data from responseBean to form BeanPerson personBeanNew = (BeanPerson)responseBean.getDataBean(); mapDataBeanToData( personBeanNew ); return;
} // end action