Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   Java Event Handling (Part-3) (http://www.go4expert.com/articles/java-event-handling-part-3-t21918/)

techgeek.in 27Apr2010 22:04

Java Event Handling (Part-3)
 

So far

  1. Java Event Handling (Part-1)
  2. Java Event Handling (Part-2)
In this article I will discuss about the events generated by entering input through keyboard and when characters are entered in text fields and text areas.

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.

Here are two of its constructors:
  1. KeyEvent(Component src, int type, long when, int modifiers, int code)
  2. 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 areas follows:
  1. char getKeyChar( )
  2. int getKeyCode( )
If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED.

When a KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED.

Now I will discuss about the corresponding listener interface for the keyboard generated events.

The KeyListener Interface



This interface defines three methods. They are as follows:
  1. void keyPressed(KeyEvent ke)
  2. void keyReleased(KeyEvent ke)
  3. void keyTyped(KeyEvent ke)
The keyPressed( ) and keyReleased( ) methods are invoked when a key is pressed and released, respectively. The keyTyped( ) method is invoked when a character has been entered. For example, if a user presses and releases the A key, three events are generated in sequence: key pressed, typed, and released. If a user presses and releases the HOME key, two key events are generated in sequence: key pressed and released.

When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed( ) event handler. When the key is released, a KEY_RELEASED event is generated and the keyReleased( ) handler is executed. If a character is generated by the keystroke, then a KEY_TYPED event is sent and the keyTyped( ) handler is invoked. Thus, each time the user presses a key, at least two and often three events are generated. If all you care about are actual characters, then you can ignore the information passed by the key press and release events. However, if your program needs to handle special keys, such as the arrow or function keys, then it must watch for them through the keyPressed() handler.

There is one other requirement that our program must meet before it can process keyboard events: it must request input focus. To do this, call requestFocus( ), which is defined by Component. If you donít, then your program will not receive any keyboard events.

Example:

The following program demonstrates keyboard input. It echoes keystrokes to the applet window and shows the pressed/released status of each key in the status window.
Code:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet>
*/
public class SimpleKey extends Applet implements KeyListener
{
        String msg = "";
        int X = 10, Y = 20;        // output coordinates

        public void init()
        {
                addKeyListener(this);
                requestFocus();        // request input focus
        }

        public void keyPressed(KeyEvent ke)
        {
                showStatus("Key Down");
        }

        public void keyReleased(KeyEvent ke)
        {
                showStatus("Key Up");
        }

        public void keyTyped(KeyEvent ke)
        {
                msg += ke.getKeyChar();
                repaint();
        }

        // Display keystrokes.

        public void paint(Graphics g)
        {
                g.drawString(msg, X, Y);
        }
}

The Output would be as follows:

http://www.go4expert.com/images/arti...dling/eh3a.jpg

Another Example:

If we want to handle the special keys, such as the arrow or function keys, we need to respond to them within the keyPressed( ) handler. They are not available through keyTyped( ). To identify the keys, you use their virtual key codes.

Following is an example which demonstrates some virtual key codes.
Code:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEvents" width=300 height=100>
</applet>
*/
public class KeyEvents extends Applet implements KeyListener
{
        String msg = "";
        int X = 10, Y = 20;        // output coordinates

        public void init()
        {
                addKeyListener(this);
                requestFocus();        // request input focus
        }

        public void keyPressed(KeyEvent ke)
        {
                showStatus("Key Down");
                int key = ke.getKeyCode();
                switch(key)
                {
                case KeyEvent.VK_F1:
                        msg += "<F1>";
                        break;

                case KeyEvent.VK_F2:
                        msg += "<F2>";
                        break;

                case KeyEvent.VK_F3:
                        msg += "<F3>";
                        break;

                case KeyEvent.VK_PAGE_DOWN:
                        msg += "<PgDn>";
                        break;

                case KeyEvent.VK_PAGE_UP:
                        msg += "<PgUp>";
                        break;

                case KeyEvent.VK_LEFT:
                        msg += "<Left Arrow>";
                        break;

                case KeyEvent.VK_RIGHT:
                        msg += "<Right Arrow>";
                        break;
                }
                repaint();
        }

        public void keyReleased(KeyEvent ke)
        {
                showStatus("Key Up");
        }

        public void keyTyped(KeyEvent ke)
        {
                msg += ke.getKeyChar();
                repaint();
        }

        // Display keystrokes.
        public void paint(Graphics g)
        {
                g.drawString(msg, X, Y);
        }
}

Output would be as shown below:

http://www.go4expert.com/images/arti...dling/eh3b.jpg

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.

This class has just one constructor which is as follows:

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. We must use other methods associated with the text component to retrieve that information. We should think of a text event notification as a signal to a listener that it should retrieve information from a specific text component.

Now I will discuss about the corresponding listener interface for the text field and text area generated events.

The TextListener Interface



This interface defines the textChanged( ) method that is invoked when a change occurs in a text area or text field. Its general form is shown here:

void textChanged(TextEvent te)

The WindowEvent Class



There are ten 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:
  1. WINDOW_ACTIVATED -- The window was activated.
  2. WINDOW_CLOSED -- The window has been closed.
  3. WINDOW_CLOSING -- The user requested that the window be closed.
  4. WINDOW_DEACTIVATED -- The window was deactivated.
  5. WINDOW_DEICONIFIED -- The window was deiconified.
  6. WINDOW_GAINED_FOCUS -- The window gained input focus.
  7. WINDOW_ICONIFIED -- The window was iconified.
  8. WINDOW_LOST_FOCUS -- The window lost input focus.
  9. WINDOW_OPENED -- The window was opened.
  10. WINDOW_STATE_CHANGED -- The state of the window changed.
WindowEvent is a subclass of ComponentEvent. It defines several constructors.

The first is:

WindowEvent(Window src, int type)

Here, src is a reference to the object that generated this event. The type of the event is type.

Java 2, version 1.4 adds the next three constructors.
  1. WindowEvent(Window src, int type, Window other)
  2. WindowEvent(Window src, int type, int fromState, int toState)
  3. WindowEvent(Window src, int type, Window other, int fromState, int toState)
Here, other specifies the opposite window when a focus event occurs. The fromState specifies the prior state of the window and toState specifies the new state that the window will have when a window state change occurs. 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( )

Java 2, version 1.4, adds methods that return the opposite window (when a focus event has occurred), the previous window state, and the current window state. These methods are shown here:
  1. Window getOppositeWindow()
  2. int getOldState()
  3. int getNewState()
Now I will discuss about the corresponding listener interfaces for window generated events.

The WindowFocusListener Interface



WindowFocusListener was added by Java 2, version 1.4. This interface defines two methods: windowGainedFocus( ) and windowLostFocus( ). These are called when a window gains or losses input focus. Their general forms are shown here.
  1. void windowGainedFocus(WindowEvent we)
  2. void windowLostFocus(WindowEvent we)

The WindowListener Interface



This interface defines seven methods. The windowActivated( ) and windowDeactivated() methods are invoked when a window is activated or deactivated, respectively. If a window is iconified, the windowIconified( ) method is called. When a window is deiconified, the windowDeiconified( ) method is called. When a window is opened or closed, the windowOpened( ) or windowClosed( ) methods are called, respectively. The windowClosing( ) method is called when a window is being closed. The general forms of these methods are as follows:
  1. void windowActivated(WindowEvent we)
  2. void windowClosed(WindowEvent we)
  3. void windowClosing(WindowEvent we)
  4. void windowDeactivated(WindowEvent we)
  5. void windowDeiconified(WindowEvent we)
  6. void windowIconified(WindowEvent we)
  7. void windowOpened(WindowEvent we)
Next comes the event generated when a check box is clicked or a list item is clicked etc
For these types of events we have the ItemEvent Class.

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 will be described in the later articles.)

There are two types of item events, which are identified by the following integer constants:
  1. DESELECTED -- The user deselected an item.
  2. SELECTED -- The user selected an item.
In addition, ItemEvent defines one integer constant, ITEM_STATE_CHANGED which signifies a change of state.

ItemEvent has one 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( )

Now I will discuss about the corresponding listener interfaces for such generated events.

The ItemListener Interface



This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes.
Its general form is shown here:
void itemStateChanged(ItemEvent ie)

Next are the events generated on pressing a button etc. For such events we have the following class.

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 three constructors:
  1. ActionEvent(Object src, int type, String cmd)
  2. ActionEvent(Object src, int type, String cmd, int modifiers)
  3. ActionEvent(Object src, int type, String cmd, long when, 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. The when parameter specifies when the event occurred.
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( )

Java 2, version 1.4 added the method getWhen( ) that returns the time at which the event took place. This is called the eventís timestamp. The getWhen( ) method is shown here.

long getWhen( )

Timestamps were added by ActionEvent to help support the improved input focus subsystem.

Now I will discuss about the corresponding listener interfaces for such generated events.

The ActionListener Interface



This interface defines the actionPerformed( ) method that is invoked when an action event occurs.

Its general form is shown here:

void actionPerformed(ActionEvent ae)

Example on this event is postponed until I discuss about the different controls line Button, CheckBox, TextField, TextArea etc

shabbir 3May2010 13:15

Re: Java Event Handling (Part-3)
 
Nominate this article for Article of the month - Apr 2010


All times are GMT +5.5. The time now is 01:11.