Handle Keyboard Events in Java swing

Source: Internet
Author: User

During Java swing programming, you often need to handle Keyboard Events, such as shortcut keys. This section describes how to define Keyboard Events and how to handle these events.

In jdk1.2, different keyboard event handling methods are customized for jcomponent and text objects: In jcomponent, The registerkeyboardaction method is defined, this method is used to bind the keyboard events to be processed and the actions to process the events. The text class has a keymap object, which is similar to the processing method in jcomponent. This object stores the keyboard events to be processed and the corresponding behavior.

In jdk1.3, a new method is used to handle keyboard events. It integrates the two methods of jdk1.2. You do not need to differentiate whether the components to be processed are jcomponent or text components. It defines two new classes: inputmap and actionmap. They are simple tables or ing. An inputmap maps a keystroke to an object, and actionmap maps an object to an action ). Generally, the object corresponding to keystroke in inputmap is a string through which the corresponding behavior can be found in actionmap.

Both inputmap and actionmap have put methods. The PUT Method of inputmap can map keystroke to an object, while the PUT Method of actionmap can map an object to an action.

Each jcomponent component has three default inputmap and one default actionmap. They can be obtained by calling getinputmap (INT condition) and getactionmap. The three inputmaps are the inputmap (when_focused) when the component itself has focus, and the inputmap (when_ancestor_of_focused_component) when the component's ancestor has focus) and inputmap (when_in_focused_window) when the form in which the component is located has focus (parameters set in getinputmap to get these inputmaps ). The three inputmaps are described as follows:

1. inputmap when the component itself has focus: When the component has focus, press the keyboard key, and Java searches for the keystroke object corresponding to the keyboard event in the inputmap.

2. inputmap when the component's ancestor has the focus: When the component's ancestor has the focus, press the keyboard key to find the inputmap in Java.

3. inputmap when the window in which the component is located has focus: when the window in which the component is located has focus, press the keyboard and press the key to find the inputmap in Java.

When a key is pressed, this event is converted into a keystroke object, Java will find the corresponding inputmap of this jcomponent (for example, when the component's ancestor has focus, java finds out whether the keystroke exists in the inputmap with the focus of the jcomponent ancestor. If so, it retrieves the corresponding object (usually a string ), use this object to search in the actionmap of this jcomponent. If the corresponding action is found, Java will execute the actioncommitted MED method of this action (this method will be introduced later ). To handle keyboard events.

Each inputmap can have the parent attribute. The value of this attribute is an inputmap. When keystroke of a keyboard event cannot be found in an inputmap, Java will automatically search for it in the inputmap specified by its parent attribute, and then search up until it is found. The advantage of using parent is that some fixed keyboard mappings that do not require user modification can be stored in the inputmap specified by the parent attribute to avoid accidental modification; in addition, the default inputmap settings of multiple jcomponents have the same parent, so that you can share some keyboard binding settings. You can use the setparent () method of the inputmap class to set its parent attribute. Actionmap also has the same parent attribute and uses the same method.

The preceding section describes how to map a keyboard event to an action ).

Action is a class that implements the action interface. Seven methods are defined in the Action interface. Among them, the most critical is the actionreceivmed () method. This method describes the specific operation process of this behavior. Other methods include setenabled, isenabled, putvalue, getvalue, addpropertychangelistener, and removepropertychangelistener. They are used to set whether the behavior is available, determine the status of the available behavior, set and obtain some attributes of the behavior. The last two methods are used to allow other objects to be notified after the attributes of the Action object change.

Usually we use an abstract class abstractaction class that implements most of the methods of the Action interface as the base class, And reload the actionreceivmed method to implement our behavior.

We will use an example to illustrate how to perform actual operations.

First, write a specific behavior to handle the specified keyboard event:

Public class textaction extends actaction
{
Private string;
Public textaction (string)
{This. A = ;}
Public void actionreceivmed (actionevent parm1)
{
String B = parm1.getactioncommand (); // command string for getting Behavior
System. Out. println ("command =" + B );
System. Out. println ("prompt =" + this. );
}
}

Create four textaction objects:

Textaction whenfocusson = new textaction ("Focus son ");
Textaction whenfocusfather = new textaction ("Focus father ");
Textaction window = new textaction ("window ");
Textaction ancestor = new textaction ("ancestor ");

Then, add two panels named sonpanel and parentpanel to a form so that parentpanel is the ancestor of sonpanel. Add a button named son to sonpanel and a button named parent to parentpanel. Add several buttons outside fatherpanel.

Obtain the three inputmaps of the son component and create an inputmap named focusfatherim to make the inputmap a parent of focusim:

// Get default inputmap (when focus inputmap) and set a parent inputmap
Focusim = Son. getinputmap ();
Focusfatherim = new inputmap ();
Focusim. setparent (focusfatherim );

// Get when_ancestor_of_focused_component inputmap
Ancestorim = Son. getinputmap (when_ancestor_of_focused_component );

// Get when_in_focused_window inputmap
Windowim = Son. getinputmap (when_in_focused_window );
Add the keyboard bindings to these inputmap files:
Focusim. Put (keystroke. getkeystroke ('F'), "actionfocusson ");
Focusfatherim. Put (keystroke. getkeystroke ('F'), "actionfocusfather ");
Ancestorim. Put (keystroke. getkeystroke ('A'), "actionancestor ");
Windowim. Put (keystroke. getkeystroke ('W'), "actionwindow ");
Obtain the default actionmap of the son component and bind the created behavior to a specific object (string:
AM = Son. getactionmap ();

Am. Put ("actionfocusson", whenfocusson );
Am. Put ("actionfocusfather", whenfocusfather );
Am. Put ("actionancestor", ancestor );
Am. Put ("actionwindow", window );

Run the program and the corresponding results:

1. Click son. If you press 'F', 'F', 'A', and 'w', the program will output the data accordingly. This is because the focus is on the son button, and the three inputmaps of the son button component are valid. So their corresponding events will happen.

2. Click the parent button, and then press 'w', the program will have the corresponding output. However, when you press 'F', 'F', and 'A', the program does not respond. This is because the parent button has focus, which is not the ancestor of the son button, and the window where Son is located has focus, so only the inputmap with focus in the window where the component is located is valid.

3. Click another button (the button outside parentpanel) and press 'W'. The program will output the corresponding data. However, when you press 'F', 'F', and 'A', the program does not respond. This is because these buttons have focus. They are not the ancestor of son buttons, and son's window has focus, so only the inputmap with focus in the window where the component is located is valid.

Appendix: main program code:

Import java. AWT .*;
Import javax. Swing .*;
Import com. Borland. jbcl. layout .*;
Import java. AWT. event. actionevent;
Import java. AWT. event. actionlistener;
Import com. Sun. java. Swing. plaf. motif .*;

Public class eventpanel extends jpanel implements actionlistener
{
Jbutton btnyellow = new jbutton ();
Jbutton btnblue = new jbutton ();
Jbutton btnred = new jbutton ();
Jpanel parentpanel = new jpanel ();
Jpanel sonpanel = new jpanel ();
Xylayout xylayout1 = new xylayout ();
Jbutton son = new jbutton ();
Jbutton parent = new jbutton ();
Public eventpanel ()
{
Try {
Jbinit ();
} Catch (exception ex)
{Ex. printstacktrace ();}
}
Void jbinit () throws exception
{
Btnyellow. settext ("yellow ");
Btnyellow. setbounds (New rectangle (35, 23, 97, 29 ));
This. setlayout (null );
Btnblue. setbounds (New rectangle (154, 21, 97, 29 ));
Btnblue. settext ("blue ");
Btnred. setbounds (New rectangle (272, 24, 97, 29 ));
Btnred. settext ("red ");
Parentpanel. setborder (borderfactory. createraisedbevelborder ());
Parentpanel. setbounds (New rectangle (27, 68,358,227 ));
Parentpanel. setlayout (xylayout1 );
Sonpanel. setborder (borderfactory. createloweredbevelborder ());
Son. settext ("son ");
Parent. settext ("parent ");
This. Add (btnyellow, null );
This. Add (btnblue, null );
This. Add (btnred, null );
This. Add (parentpanel, null );
Parentpanel. Add (sonpanel, new xyconstraints (58, 22,229,125 ));
Sonpanel. Add (son, null );
Parentpanel. Add (parent, new xyconstraints (150,167,-1,-1 ));
Btnyellow. addactionlistener (this );
Btnred. addactionlistener (this );
Btnblue. addactionlistener (this );

Inputmap focusim, focusfatherim, ancestorim, windowim;
Actionmap am;
// Create four textaction for diff Purpose
Textaction whenfocusson = new textaction ("Focus son ");
Textaction whenfocusfather = new textaction ("Focus father ");
Textaction window = new textaction ("window ");
Textaction ancestor = new textaction ("ancestor ");
// Get default inputmap (when focus inputmap) and set a parent inputmap
Focusim = Son. getinputmap ();
Focusfatherim = new inputmap ();
Focusim. setparent (focusfatherim );
// Get when_ancestor_of_focused_component inputmap
Ancestorim = Son. getinputmap (when_ancestor_of_focused_component );
// Get when_in_focused_window inputmap
Windowim = Son. getinputmap (when_in_focused_window );
// Put the keystroke to the inputmap
Focusim. Put (keystroke. getkeystroke ('F'), "actionfocusson ");
Focusfatherim. Put (keystroke. getkeystroke ('F'), "actionfocusfather ");
Ancestorim. Put (keystroke. getkeystroke ('A'), "actionancestor ");
Windowim. Put (keystroke. getkeystroke ('W'), "actionwindow ");
// Get the actionmap
AM = Son. getactionmap ();
Am. Put ("actionfocusson", whenfocusson );
Am. Put ("actionfocusfather", whenfocusfather );
Am. Put ("actionancestor", ancestor );
Am. Put ("actionwindow", window );
}
Public void actionreceivmed (actionevent E)
{
// This code is used to change the backgracolor
Object source = E. getsource ();
Color color = NULL; // = getbackground ();
If (Source = btnyellow) color = color. Yellow;
Else if (Source = btnred) color = color. Red;
Else if (Source = btnblue) color = color. blue;
Setbackground (color );
Repaint ();
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.