Monday 26 November 2012

Java Programming -- Creating Front End

Java Programming -- Creating Front End

Structure 7.1 Introduction Objectives

 7.2 Applets

 7.2.1 Introduction

 7.2.2 Objectives

 7.2.3 What are Applets?

 7.2.4 The Applet Class

 7.2.5 The Applet and HTML

7.2.6 Life Cycle of an Applet

 7.2.7 The Graphics Class

7.2.8 Painting the Applet

 7.2.9 User Interfaces for Applet

 7.2.10 Adding Components to user interface

 7.2.11 AWT Controls Self Assessment Questions

 7.3 Event Handling

 7.3.1 Introduction

 7.3.2 Components of an Event

 7.3.3 Event Classes

 7.3.4 Event Listener

 7.3.5 Event-Handling

7.3.6 Adapter Classes
7.3.7 Inner Classes
7.3.8 Anonymous Classes Self Assessment Questions

 7.4 Summary
7.5 Terminal Questions

Java Programming Unit 7
 7.1 Introduction Internet as of today has become an inseparable part of life used widely for accessing libraries, getting information on latest happenings,transfering information, sending email and communicating with others. Java programs written to run on World Wide Web (WWW) are called as applets. Since applets are run on a different machine, security becomes a critical issue. Another probable disadvantage of applets would be the slight flickering that would be inevitable in animations but there is light at the end of the tunnel since a separate buffer can be used for the images which can then be superimpose on to the window or canvas. Objectives In this chapter, you will learn about the:  The Applet Classes.Ø  The Life Cycle of an applet.Ø  Creating an appletØ  Handling different types of event.Ø

7.2 Applets
7.2.1 Introduction Today Internet has become an inevitable part of life. It is used for accessing libraries, getting information on latest happening, to transfer information, send email and communicate with others. Java has become a prime language today in making web pages interactive and user friendly. Java programs written to run on World Wide Web (WWW) are called as applets. Since applets are run on a different machine, security becomes a critical issue.

7.2.2 Objectives In this unit you will learn how to write applets and how to include them in web pages. It is possible to change the colors, font of the text, set different  background colors for different applets and make them look more attractive. Applets can be added to web pages by using the applet tag in the HTML document. You will also learn to add graphics to applets. Example is given to explain how to make the applets interactive.

7.2.3 What are Applets? An applet is a Java program that can be embedded in a web page. Java applications are run by using a Java interpreter. Applets are run on any browser that supports Java. Applets can also be tested using the appletviewer tool included in the Java Development Kit. In order to run an applet it must be included in a web page, using HTML tags. When a user browsers a web server and runs it on the user’s system. Applets have certain restrictions put on them.  They can not read or write files on the user’s system.·  They can not load or run any programs stored on the user’s system.· All applets are subclasses of the Applet class in the java.applet package. Applets do not have main () method. All applets must be declared public. An applet displays information on the screen by using the paint method. This method is available in java.wat.Component class. This method takes an instance of the class Graphics as parameter. The browser creates an instance of Graphics class and passes to the method paint (). Graphics class provides a method drawString to display text. It also requires position to be specified as arguments.

7.2.4 The Applet Class The java.applet package is the smallest package in the Java API. The Applet class is the only class in the package. An applet is automatically loaded and executed when you open a web page that contains it. The Applet class has over 20 methods that are used to display images, play audio files, and respond when you interact with it. The applet runs in a web page that is loaded in a web browser. The environment of the applet is known as the context of the applet. You can retrieve the context using the getAppletContext () method. The life cycle of an applet is implemented using init (), start (), stop (), and destroy (). Use javac to compile applets and appletviewer to execute them. You can view applets in any browser that is Java-enabled.

7.2.5 The Applet and HTML The Applet tag is used to embed an applet in an HTML document the Applet tag takes zero or more parameters. The Applet Tag The Applet tag is written the Body tag of an HTML document. Syntax The most commonly used attributes of the Applet tag are CODE, HEIGHT, WIDTH, CODEBASE and ALT. You can send parameters to the applet using the PARAM tag. The PARAM tag must be written between Example

7.2.6 Life Cycle of an Applet
You can describe the life cycle of an applet through four methods. These methods are:  
 The init () method.   
 The start () method.    
 The stop () method.    
 The destroy () method.   

The init () method
The init () method is called the first time an applet is loaded into the memory of a computer. You can initialize variables, and add components like buttons and check boxes to the applet in the init () method.

The start () method
The start () method is called immediately after the init () method and every time the applet receives focus as a result of scrolling in the active window. You can use this method when you want to restart a process, such as thread animation, every time the applet receives the focus.

The stop () method
The stop () method is called every time the applet loses the focus. You can use this method to reset variables and stop the threads that are running.

The destroy () method
The destroy () method is called by the browser when the user moves to another page. You can use this method to perform clean-up operations like closing a file. The following diagram depicts the life cycle of an applet. It is not mandatory to use any or all the methods of the applet. These methods are called automatically by the Java environment, and hence, must be declared public. None of the methods accept parameters.

For example, public void init () { } All but the most trivial applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods—init( ), start( ), stop( ), and destroy( ) – are defined by Applet.
Another, paint( ), is defined by the AWT Component class. Default implementations for all of these methods are provided. Applets do not need to override those methods they do not use. However, only very simple applets will not need to define all of them.

These five methods can be assembled into the skeleton shown here:
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/* */
 public class AppletSkel extends Applet
{
// Called first.
public void init() {
// initialization
}
 /* Called second, after init(). Also called whenever the applet is restarted. */
public void start()
{
// start or resume execution
 }
 // Called when the applet is stopped.
public void stop()
{
// suspends execution
}
/* Called when applet is terminated. This is the last method executed. */
public void destroy()
 {
 // perform shutdown activities
 }

7.2.7 The Graphics Class
The Graphics class is an abstract class that represents the display area of the applet. It is apart of the java.awt package. It is used for drawing on the display are of the applet. The Graphics class provides methods to draw a number of graphical figure including  Tex  t  Lines    Circle and ellipse.    Rectangle and polygons.    Images.   A few of the methods are given below.

public abstract void drawString (String text, int x, int y)
public abstract void drawLine (int x1, int y1, int x2, int y2)
public abstract void drawRect (int x1, int y1, int width, int height)
public abstract void fillRect (int x, int y1, int width, int height)
public abstract void clearRect (int x, int y1, int width, int height)
public abstract void draw3DRect (int x1, int y1, int width, int height, boolean raised)
public abstract void drawRoundRect (int x1, int y1, int width, int height, int arcWidth, int arcHeight )
public abstract void fillRoundRect (int x1, int y1, int width, int height, int arcWidth, int arcHeight )
public abstract void drawOval (int x1, int y1, int width, int height)
public abstract void fillOval (int x, int y1, int width, int height)

You cannot create an object of the Graphics class since it is abstract. You can use the method getGraphics () to obtain an object of the class.

7.2.8 Painting the Applet
When you scroll to an applet, the screen has to be refreshed to show the new content. Windows handles this by marking the area (rectangle ) that has to be refreshed. The area is then painted to display the result of scrolling. This is handled by the update () and paint () methods. The update () method The update () method takes a Graphics class object as a parameter. When the applet area needs to be redrawn, the Windows system starts the painting process. The update () method is called to clear the screen and calls the paint () method. The screen is then refreshed by the system. The paint () method The paint () method draws the graphics of the applet in the drawing area. The method is automatically called the first time the applet is displayed on the screen and every time the applet receives the focus. The paint () method can be triggered by invoking the repaint () method. The paint () method of the applet takes an object of the Graphics class as a parameter.

Example
Step 1: Coding
Step 2: Compiling and Executing
Step 3: Output

The repaint () method: You can call the repaint () method when you want the applet area to be redrawn. The repaint () method calls the update () method to signal that the applet has to be updated. The default action of the update () method is to clear the applet area and call the paint () method. You can override the update () method if you do not want the applet area o be cleared. The following program uses the paint () and repaint () methods to check when the init (), start (), and stop () methods of an applet are called. As a general rule, an applet writes to its window only when its update( ) or paint( ) method is called by the AWT. This raises an interesting question: How can the applet itself cause its window to be updated when its information changes? For example, if an applet is displaying a moving banner, what mechanism does the applet use to update the window each time this banner scrolls? Remember, one of the fundamental architectural constraints imposed on an applet is that it must quickly return control to the AWT run-time system. It cannot create a loop inside paint( ) that repeatedly scrolls the banner, for example. This would prevent control from passing back to the AWT. Given this constraint, it may seem that output to your applet's window will be difficult at best. Fortunately, this is not the case. Whenever your applet needs to update the information displayed in its window, it simply calls repaint( ). The repaint( ) method is defined by the AWT. It causes the AWT run-time system to execute a call to your applet's update( ) method, which, in its default implementation, calls paint( ). Thus, for another part of your applet to output to its window, simply store the output and then call repaint( ). The AWT will then execute a call to paint( ), which can display the stored information. For example, if part of your applet needs to output a string, it can store this string in a String variable and then call repaint( ). Inside paint( ), you will output the string using drawString( ).

The repaint( ) method has four forms.
Let's look at each one, in turn. The simplest version of repaint( ) is shown here:
void repaint( )
This version causes the entire window to be repainted. The following version specifies a region that will be repainted:
void repaint(int left, int top, int width, int height)
import java.awt.*;
import java.applet.*;
 /* */
 public class Test extends Applet
{
 int initcounter=0;
int startcounter=0;
int stopcounter=0;
int destroycounter=0;   
 public void init() { initcounter++; repaint ();
}
public void start()
 {
 startcounter++; repaint ();
}
public void stop()
{
 stopcounter++; repaint ();
} public void destroy()
 { destroycounter++; repaint ();
} public void paint (Graphics g)
{
g.drawString ("init has been invoked " + String.valueOf(initcounter) +"times",20,20);
g.drawString ("start has been invoked " + String.valueOf(startcounter) +"times",20,35);
g.drawString ("stop has been invoked " + String.valueOf(stopcounter) +"times",20,50);
g.drawString ("destroy has been invoked " + String.valueOf(destroycounter) +"times",20,65);
}
}

7.2.9 User Interfaces for Applet The Abstract windowing Toolkit, also called as AWT is a set of classes, enabling the user to create a user friendly, graphically user interface (GUI). It will also facilitate receiving user input from the mouse and keyboard. The AWT classes are part of the java.awt package. The user interface consists of the following three:  Components – Anything that can be put on the user interface. ThisØ includes buttons, check boxes, pop-up menus, text fields.  Containers – This is a component that can contain other components.Ø  Layout manager – These define how the components will be arranged in aØ container. The statement import java.awt.*; imports all the components, containers and layout managers necessary for designing the user interface.

The AWT supplies the following components.  
 Labels (java.awt.Label)·  
 Buttons (java.awt.Button)·  
Checkboxes (java.awt.Checkbox)·  
Single- line text field (java.awt.TextField)·  
Larger text display and editing areas (java.awt.TextArea)·  
Pop-up lists of choices (java.awt.Choice)·  
Lists (java.awt.List)·  
Sliders and scrollbars (java.awt.Scrollbar )·  
Drawing areas (java.awt.Canvas)·  
Menus (java.awt.Menu, java.awt.MenuItem, java.awt.CheckboxMenuItem )·    
Containers (java.awt.Panel, java.awt.Window and its subclasses)·

7.2.10 Adding Components to user interface Because all applets are containers, components can be added directly to the applet windows. The following steps add a component:  Create the component by creating an object of that class.·  Call the Container’s adds method to add the component.· Labels Labels display non editable text. To create a label use one of the following:  label () – create an empty label.·  label (String) – creates a label with the given string.·  label (String, int ) – creates a label with the given string and· right, left or center alignment. Buttons Clickable buttons can be created from the Button class. You can create a button by using either of the following:  Button () – Creates a button without any label. Use setLabel (String)· to display a text on the button.  Button (String) – Creates a button with the given string as the label.· Checkboxes They are labeled or unlabeled boxes that can be either checked off or empty. They are used for selecting some option. Use one of the following to create them.  Checkbox () – Creates a checkbox without any label.·  Checkbox (String) – Creates a labeled checkbox.· When many checkboxes are there any number of them can be checked or unchecked. Checkboxes can be organized into groups so that only one of them can be checked at a time. The following statements a checkbox group:
CheckboxGroup mygroup = new CheckboxGroup ();  
To create a checkbox, belonging to this group, use the following statement.
Checkbox c1 = new Checkbox (―Manipal‖, mygroup,true);

The following program creates label, checkbox and buttons. TextFields TextField is an editable component. Text field can be created by using one of the following:  TextField () – Creates an empty text field.· TextField (String) – Creates a text field with the specified string.·  TextField (String,int ) – Creates a text field with the specified· String and specified width. The TextField class has several useful methods:  The getText () method returns the text in the field.·  The setText (String ) method fills the field with the string.·  The setEditable (boolean) methods decides whether the filed hould be· editable or not depending upon the Boolean value. The is Editable () method returns a Boolean value indicating wheteher· the filed is editable or not. Text Areas These are editable text fields having more than one line of input. Use one of the following to create a text area.  TextArea () – Creates an empty text area.·  TextArea (rows,character) – Creates a text area of rows specified and· width to accommodate the character specified.  TextArea (String)·  TextArea (String,rows,character)· The methods available in case of Text filed can also be used here. In addition to that the following methods could be used:  The insert (String, charindex) method inserts the indicated string at· the position indicated by the second argument.  The replace (string, startpos,endpos) method replaces the txt between· the given integer positions with the indicated string.

7.2.11 AWT Controls
 GUI Category Control AWT Class Name Basic Controls Button Combo box List Menu Slider Toolbar Text Field Button ComboBox List Menu,MenuBar,MenuItem Slider Toolbar TextField,PasswordField,TextArea Uneditable Display Label Tooltip Progress bar Label ToolTip ProgressBar Editable Display Table Text Tree Color chooser File chooser Table TextPane,TextArea Tree ColoChooser FileChooser Space-Saving Containers Scroll pane Split pane Tabbed pane ScrollPane,ScrollBar SplitPane TabbedPane Top-Level Containers Frame Applet Dialog Frame Applet Dialog

Self Assessment Questions  
What is an applet?·  
Applet class is defined under which packages?·  
What are the different attribute of an applet tag?·  
What are the use of update and paint method?·


7.3 Event Handling

7.3.1 Introduction Event-handling is essential to GUI programming. The program waits for a user to perform some action. The user controls the sequence of operations that the application executes through a GUI. This approach is called event-driven programming.  Error! 7.3.2 Components of an Event An event comprises of three components:  Event Object – When the user interacts with the application by   pressing a key or clicking a mouse button, an event is generated. The operating system traps this event and the data associated with it, for example, the time at which the event occurred, the event type (like a keypress or a mouse click). This data is then passed on to the application to the application to which the event belongs. In Java, events are represented by objects that describe the events themselves. Java has a number of classes that describe and handle different categories of event.  Event Source – An event source is an object that generates an event.   For example, if you click on a button, an ActionEvent object is generated. The object of the ActionEvent class contains information about the event.   Event-handler – An event-handler is a method that understands the   event and processes it. The event-handler method takes an Event object as a parameter.

7.3.3 Event Classes
The EventObject class is at the top of the event class hierarchy. It belongs to the java.util package. Most other event classes are present in the java.awt.event package. The hierarchy of the event classes is show below. The java.util.EventObject and the java.awt.AWTEvent classes do not belong to the java.awt.event package. The hierarchy of the JDK 1.2 event classes is given below.

The getSource () method of the EventObject class returns the object that initiated the event. The getID () method returns the event ID that represents the nature of the event. For example, if a mouse event occurs, you can find out whether the event was a click, a drag, a move, a press, or a release from the event object.  Let us see when various events are generated:  An ActionEvent object is generated when a component is activated.    An AdjustmentEvent object is generated when scrollbars and other   adjustable elements are used.  A ContainerEvent object is generated when components are added to or   removed from a container.

A FocusEvent object is generated when a component receives focus for   input.  An ItemEvent object is generated when an item from a list, a choice,   or a check box is selected.  A KeyEvent object is generated when a key on the keyboard is pressed.    A MouseEvent object is generated when the mouse is used.    A PaintEvent object is generated when a component is painted.    A TextEvent object is generated when the text of a text component is   modified.

7.3.4 Event Listener An object delegates the task of handling an event to an event listener. When an event occurs, an event object of the appropriate type (as given above) is created. This object is passed to the listener. A listener must implement the interface that has the method for event-handling. A component can have multiple listeners. A listener can be removed using the removeActionListener () method.  

Example 7.3.5 Event-Handling
When an event occurs, it is sent to the component from where the event originated. The component registers a listener, which contains event-handler. Event-handler receives and process events. Every event has a corresponding listener interface that specifies the methods that are required to handle the event. Event object are reported to registered listener. To enable a component to handle events, you must register an appropriate listener for the component.  

Example
class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent evt)
{
Button source = (Button)evt.getSource();
Source.setLable (―Button clicked’’);
{
 }

How does the above application work?  The execution begins with the main () method.v  An object of the MYFrame class is created in the main () method.v  The constructor of the MYFrame class is called.v The super () method calls the constructor of the base class (Frame)v and sets the title of the window.  A button object is created and placed at the center of the window.v  A listener object is created.v  The addActionListener () method registers the listener object for thev button.  The application waits for the user to interact with it.v  When the user clicks on the button-v  The ActionEvent event is generated.·  An ActionEvent object is created and is delegated to the registered· listener object for processing.  The listener object contains the actionPerformed () method, which· processes the ActionEvent.  In the actionPerformed () method, the reference to the event source is· retrived using the getSource () method.  Finally, the label of the button is changed using the setLabel ()· method. The ActionEvent Class An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is selected. The ActionEvent class defines four integer constants that can be used to identify any modifiers associated with an action event: ALT_MASK,
CTRL_MASK,
META_MASK, and
SHIFT_MASK.
In addition, there is an integer constant, ACTION_PERFORMED, which can be used to identify action events. ActionEvent has these two constructors:
ActionEvent(Object src, int type, String cmd)  
ActionEvent(Object src, int type, String cmd, int modifiers)

Here, src is a reference to the object that generated this event. The type of the event is specified by type, and its command string is cmd. The argument modifiers indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. You can obtain the command name for the invoking ActionEvent object by using the getActionCommand( ) method, shown here:

String getActionCommand( )

For example, when a button is pressed, an action event is generated that has a command name equal to the label on that button. The getModifiers( ) method returns a value that indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. Its form is shown here: int getModifiers( ) The AdjustmentEvent Class An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events. The AdjustmentEvent class defines integer constants that can be used to identify them. The constants and their meanings are shown here: BLOCK_DECREMENT The user clicked inside the scroll bar to decrease its value. BLOCK_INCREMENT The user clicked inside the scroll bar to increase its value. TRACK The slider was dragged. UNIT_DECREMENT The button at the end of the scroll bar was clicked to decrease its value. UNIT_INCREMENT The button at the end of the scroll bar was clicked to increase its value. In addition, there is an integer constant, ADJUSTMENT_VALUE_ CHANGED, that indicates that a change has occurred. AdjustmentEvent has this constructor: AdjustmentEvent(Adjustable src, int id, int type, int data) Here, src is a reference to the object that generated this event. The id equals ADJUSTMENT_VALUE_CHANGED. The type of the event is specified by type, and its associated data is data. The getAdjustable( ) method returns the object that generated the event. Its form is shown here: Adjustable getAdjustable( ) The type of the adjustment event may be obtained by the getAdjustmentType( ) method. It returns one of the constants defined by AdjustmentEvent. The general form is shown here: int getAdjustmentType( ) The amount of the adjustment can be obtained from the getValue( ) method, shown here: int getValue( ) For example, when a scroll bar is manipulated, this method returns the value represented by that change. The ComponentEvent Class A ComponentEvent is generated when the size, position, or visibility of a component is changed.

There are four types of component events.
The ComponentEvent class defines integer constants that can be used to identify them. The constants and their meanings are shown here: COMPONENT_HIDDEN The component was hidden. COMPONENT_MOVED The component was moved. COMPONENT_RESIZED The component was resized. COMPONENT_SHOWN The component became visible. ComponentEvent has this constructor: ComponentEvent(Component src, int type) Here, src is a reference to the object that generated this event. The type of the event is specified by type. ComponentEvent is the superclass either directly or indirectly of ContainerEvent, FocusEvent, KeyEvent, MouseEvent, and WindowEvent. The getComponent( ) method returns the component that generated the event. It is shown here:  Component getComponent( ) The ContainerEvent Class A ContainerEvent is generated when a component is added to or removed from a container. There are two types of container events. The ContainerEvent class defines int constants that can be used to identify them: COMPONENT_ADDED and COMPONENT_REMOVED. They indicate that a component has been added to or removed from the container.

ContainerEvent is a subclass of ComponentEvent and has this constructor:
ContainerEvent(Component src, int type, Component comp)
Here, src is a reference to the container that generated this event. The type of the event is specified by type, and the component that has been added to or removed from the container is comp. You can obtain a reference to the container that generated this event by using the getContainer( ) method, shown here: Container getContainer( ) The getChild( ) method returns a reference to the component that was added to or removed from the container. Its general form is shown here: Component getChild( )

The FocusEvent Class
A FocusEvent is generated when a component gains or loses input focus. These events are identified by the integer constants FOCUS_GAINED and FOCUS_LOST. FocusEvent is a subclass of ComponentEvent and has these constructors:   
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryFlag)

Here, src is a reference to the component that generated this event. The type of the event is specified by type. The argument temporaryFlag is set to true if the focus event is temporary. Otherwise, it is set to false. (A temporary focus event occurs as a result of another user interface operation. For example, assume that the focus is in a text field. If the user moves the mouse to adjust a scroll bar, the focus is temporarily lost.) The isTemporary( ) method indicates if this focus change is temporary. Its form is shown here: boolean isTemporary( ) The method returns true if the change is temporary. Otherwise, it returns false. The InputEvent Class The abstract class InputEvent is a subclass of ComponentEvent and is the superclass for component input events. Its subclasses are KeyEvent and MouseEvent.

The InputEvent class defines the following eight integer constants that can be used to obtain information about any modifiers associated with this event:
ALT_MASK
BUTTON2_MASK
META_MASK
ALT_GRAPH_MASK
BUTTON3_MASK SHIFT_MASK
BUTTON1_MASK CTRL_M

The isAltDown( ), isAltGraphDown( ), isControlDown( ), isMetaDown( ), and isShiftDown( ) methods test if these modifiers were pressed at the time this event was generated. The forms of these methods are shown here:

boolean isAltDown( )
boolean isAltGraphDown( )
boolean isControlDown( )
boolean isMetaDown( )
boolean isShiftDown( )

The getModifiers( ) method returns a value that contains all of the modifier flags for this event. Its signature is shown here: int getModifiers( ) The ItemEvent Class An ItemEvent is generated when a check box or a list item is clicked or when a checkable menu item is selected or deselected. (Check boxes and list boxes are described later in this book.) There are two types of item events, which are identified by the following integer constants: DESELECTED The user deselected an item. SELECTED The user selected an item. In addition, ItemEvent defines one integer constant, ITEM_STATE_CHANGED, that signifies a change of state. ItemEvent has this constructor: ItemEvent(ItemSelectable src, int type, Object entry, int state)    Here, src is a reference to the component that generated this event. For example, this might be a list or choice element. The type of the event is specified by type. The specific item that generated the item event is passed in entry. The current state of that item is in state. The getItem( ) method can be used to obtain a reference to the item that generated an event. Its signature is shown here: Object getItem( ) The getItemSelectable( ) method can be used to obtain a reference to the ItemSelectable object that generated an event. Its general form is shown here: ItemSelectable getItemSelectable( ) Lists and choices are examples of user interface elements that implement the ItemSelectable interface. The getStateChange( ) method returns the state change (i.e., SELECTED or DESELECTED) for the event. It is shown here: int getStateChange( )

The KeyEvent Class
A KeyEvent is generated when keyboard input occurs. There are three types of key events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two events are generated when any key is pressed or released. The last event occurs only when a character is generated. Remember, not all key presses result in characters. For example, pressing the SHIFT   key does not generate a character. There are many other integer constants that are defined by KeyEvent. For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and letters. Here are some others:
VK_ENTER
VK_ESCAPE
VK_CANCEL
VK_UP
VK_DOWN
VK_LEFT
VK_RIGHT
VK_PAGE_DOWN
VK_PAGE_UP
VK_SHIFT
VK_ALT
VK_CONTROL

The VK constants specify virtual key codes and are independent of any modifiers, such as control, shift, or alt. KeyEvent is a subclass of InputEvent and has these two constructors:
KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)

Here, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the key was  pressed is passed in when. The modifiers argument indicates which modifiers were pressed when this key event occurred. The virtual key code, such as VK_UP, VK_A, and so forth, is passed in code. The character equivalent (if one exists) is passed in ch. If no valid character exists, then ch contains CHAR_UNDEFINED. For KEY_TYPED events, code will contain VK_UNDEFINED. The KeyEvent class defines several methods, but the most commonly used ones are getKeyChar( ), which returns the character that was entered, and getKeyCode( ), which returns the key code. Their general forms are shown here: char getKeyChar( ) int getKeyCode( ) If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED. When a KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED. The MouseEvent Class There are seven types of mouse events.
The MouseEvent class defines the following integer constants that can be used to identify them: MOUSE_CLICKED The user clicked the mouse. MOUSE_DRAGGED The user dragged the mouse. MOUSE_ENTERED The mouse entered a component.    
MOUSE_EXITED The mouse exited from a component.
MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.

MouseEvent is a subclass of InputEvent and has this constructor: MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup) Here, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which modifiers were pressed when a mouse event occurred. The coordinates of the mouse are passed in x and y. The click count is passed in clicks. The triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform. The most commonly used methods in this class are getX( ) and getY( ). These return the X and Y coordinates of the mouse when the event occurred. Their forms are shown here: int getX( ) int getY( ) Alternatively, you can use the getPoint( ) method to obtain the coordinates of the mouse. It is shown here:    


 Point getPoint( ) It returns a Point object that contains the X, Y coordinates in its integer members: x and y. The translatePoint( ) method changes the location of the event. Its form is shown here: void translatePoint(int x, int y) The getClickCount( ) method obtains the number of mouse clicks for this event. Its signature is shown here: int getClickCount( ) The isPopupTrigger( ) method tests if this event causes a pop-up menu to appear on this platform. Its form is shown here: boolean isPopupTrigger( ) The TextEvent Class Instances of this class describe text events. These are generated by text fields and text areas when characters are entered by a user or program. TextEvent defines the integer constant TEXT_VALUE_CHANGED. The one constructor for this class is shown here: TextEvent(Object src, int type) Here, src is a reference to the object that generated this event. The type of the event is specified by type. The TextEvent object does not include the characters currently in the text component that generated the event. Instead, your program must use other methods associated with the text component to retrieve that information. This operation differs from other event objects discussed in this section.
 For  this reason, no methods are discussed here for the TextEvent class. Think of a text event notification as a signal to a listener that it should retrieve information from a specific text component.

The WindowEvent Class There are seven types of window events. The WindowEvent class defines integer constants that can be used to identify them. The constants and their meanings are shown here: WINDOW_ACTIVATED The window was activated.
WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window be closed.
WINDOW_DEACTIVATED The window was deactivated.
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_ICONIFIED The window was iconified.
WINDOW_OPENED The window was opened.

WindowEvent is a subclass of ComponentEvent and has this constructor: WindowEvent(Window src, int type) Here, src is a reference to the object that generated this event. The type of the event is type. The most commonly used method in this class is getWindow( ). It returns the Window object that generated the event. Its general form is shown here: Window getWindow( )

7.3.6
Adapter Classes The Java programming language provides adapter classes that implement the corresponding listener interfaces containing more than one method. The methods in these classes are empty. The listener class that you define can extend the Adapter class and override the methods that you need. The Adapter class used for the WindowListener interface in the WindowAdapter class. You can rewrite the previous code in the following manner.
        The following is a list of Adapter classes and listener interfaces:
Event Category Interface Name Adapter Name Method

Window WindowListener WindowAdapter
void windowClosing (WindowEvent e)
void windowOpening (WindowEvent e)
void windowActivated (WindowEvent e)
void windowDeactivated (WindowEvent e)
void windowClosed (WindowEvent e)
void windowIconified (WindowEvent e)
void windowDeiconified (WindowEvent e)

Action ActionListenr
void actionPerformed (ActionEvent e )

Item ItemListener
void itemStateChanged (ItemEvent e)

Mouse Motion MouseMotion Listener MouseMotion Adapter
void mouseDragged (MouseEvent e)
void mouseMoved (MouseEvent e)

Mouse Button MouseListener MouseAdapter
void mousePressed (MouseEvent e)
void mouseReleased (MouseEvent e)
void mouseEntered (MouseEvent e)
void mouseExited (MouseEvent e)
void mouseClicked (MouseEvent e)

Key KeyListener KeyAdapter
void keyPressed (KeyEvent e)
void keyReleased (KeyEvent e)
void keyTyped (KeyEvent e)

Focus FocusListener
void focusGained (FocusEvent e)
void focusLost (FocusEvent e)

Component ComponentListener Component Adapter
void componentMoved (ComponentEvent e)
void componentResized (ComponentEvent e)
void componentHidden (ComponentEvent e)
void componentShown (ComponentEvent e)

7.3.7 Inner Classes Inner classes are classes that are declared within other classes. They are also known as nested classes and provide additional clarity to programs. The scope of an inner class is limited to the class that encloses it. The objects of the inner class can access the members of the outer class. outer class can access the members of the inner class through an object of the inner class. Syntax class { class { } // other attributes and methods }

7.3.8 Anonymous Classes Sometimes, the classes that you declare in a method do not need a name since you do not need them anywhere else in the program. You can create nameless classes for this purpose. Classes that are not named are called anonymous classes. Example public void methodOne () { OKButton.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent action) { //process event } } );    }

       In the above code, the class declaration is the argument of the addActionListener () method. You cannot instantiate an object of the anonymous class elsewhere in the code. An anonymous class cannot have a constructor as the class does not have a name. An anonymous class can be a subclass of another class. It can implement an interface.

 Self Assessment Questions
 What is an Event?·  
What do you mean by event listener and event handling?·  
What is an inner class?·

7.4 Summary  
The Applet class is the only class of the java.applet package.    
An applet runs in a Webpage.    
An applet can be executed using the appletviewer or a Java-enabled browser
 The Applet tag is used to embed an applet in a Web page.    
The init () method is called the first time the applet is loaded into 
 the memory of a computer.  The start () method is called immediately after the init () method and   
every time the applet receives focus as a result of scrolling in the active window.  The stop () method is called every time the user moves on to another web page.
 The destroy () method is called just before the browser is shut down.    
You can use the method getGraphics () to obtain an object of the   
Graphics class.  The update () method clears the screen and calls the paint () method.    
The paint () method draws the graphics of the applet in the drawing area.
 The repaint () method calls the update () method to signal that the applet’s redrawn in the drawing area.  An application does not require a browser for execution.   
 An application starts with the main () method.     
Typically, GUI programs wait for the user to perform some action.    
The components of an event are:    
Event Object·  Event Source·  Event Handler·  To handle window-related events, you need to register the listener object that implements the WindowListener interface.  
Inner classes, also called nested classes, are classes that are   declared within other classes.  The classes that are not named within a program are called anonymous   classes.  An anonymous class cannot have a constructor as the class has no name.   

7.5 Terminal Questions
1. What are the restrictions on an applet?
 2. What is the life cycle of an applet class?
3. What are the different components of an event?
4. What are the uses of an adapter class?
 5. Write an applet program for an online shopping form?
6. Write an applet program to change the background colour of an applet window as soon as you click on a button?

No comments:

Post a Comment