Keyboard event processing in java swing

zhaozj2021-02-16  56

Sender: TTLINK (Skywalker), the letter area: Java Title: Java Swing Keyboard Event Processing Send Station: Sun and Moonlight (December 20, 2002 01:05:26 Friday), station letters

Http://www.cn-java.com/target/news.php?news_id=1455

During the Java Swing programming, the keyboard events are often required, such as processing shortcuts, etc. Here is how to define keyboard events and how to handle these events.

In JDK1.2, the objects of the JComponent and Text classes have customized different processing keyboard events: In JComponent, the RegisterKeyboardAction method is defined, using this method to use this method to process the keyboard events that need to be processed, and the behavior of the process. Together. The TEXT class has a KeyMap object, similar to the processing method in the JComponent, which saves the keyboard event and the corresponding behavior that needs to be processed.

In JDK1.3, a new method is used to handle keyboard events, which integrates two methods of JDK1.2. It is not necessary to distinguish between the JComponent or the component of the Text type. It defines two new classes: InputMap and ActionMap. They are all simple tables or mappings. An INPUTMAP corresponds to an object, and ActionMap corresponds to an action. Objects corresponding to Keystroke in INPUTMAP are a string that can be found in ActionMap in ActionMap.

There is a PUT method in InputMap and ActionMap. InputMap's PUT method can correct keyStroke to an object, and ActionMap's PUT method can correspond to a behavior.

In each JComponent component, there will be three default inputmap and a default actionMap. They can get getting GetInputMap (int condition) and getActionMap (). When the three are InputMap InputMap (WHEN_FOCUSED) when the component itself has the focus, when the form InputMap (WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) when components with the ancestors of the focus and where the assembly has a focus InputMap (WHEN_IN_FOCUSED_WINDOW) (in the brackets in order to obtain these InputMap, parameters should be set in GetInputMap). The following explains the three INPUTMAPs respectively:

1. InputMap when the component itself has a focus: When the component has a focus, the keyboard button is pressed, and Java looks for the Keystroke object corresponding to the keyboard event in this InputMap.

2. InputMap when the component's ancestors has focus: When the ancestors of the component have a focus, the keyboard button is pressed, and Java finds this inputmap.

3. InputMap when the window is located with the focus: When the window where the component is located, the keyboard button is pressed, and Java finds this inputmap.

When a button 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 ancestors have focus, Java looks for this JComponent's ancestor's ancestor's inputmap. This keyStroke, if there is, take out the object it corresponding to it (usually the string), use this object to find in this JComponent's actionMap, if the corresponding behavior is found, Java executes the actionPerformed method for this behavior (later introduction this way). Thus the purpose of processing the keyboard event. Each INPUTMAP can have a Parent property, and the value of this property is an InputMap. When you find Keystroke without the keyboard event in an InputMap, Java will automatically find in the InputMap specified by its Parent property, and look up in turn until it is found. The benefits of using PAREN are: When there are some fixed, it is not desirable that the keyboard mapping of the user can be modified in the inputMap specified by the Parent property, thereby avoiding accidental modifications; otherwise, you can have the same name of multiple JComponent's default inputmap settings Parent makes a shared setting of the keyboard binding. It can set its Parent attribute with the setParent () method of the InputMap class. ActionMap also has the same Parent attribute, and the use method is also the same.

The above is how to correspond to a keyboard event, and the following is simply introduced.

Behavior is a class that implements an action interface. Seven methods are defined in the Action interface. The most critical is the actionPerformed () method. This method describes the specific operation of this behavior. Several other methods include setENABLED, ISENABLED, PUTVALUE, GETVALUE, ADDPROPERTYCHANGELISTENER, and REMOPROPERTYCHANGELISTENER methods. They are used to set whether the behavior is available, determine the status, setting, and acquisition behavior of the behavior, and the last two methods are used to allow other objects to be notified after the attributes of the action object.

Usually we use an abstract class AbstractAction class that implements most of the Action interface as a base class, overloads an ActionPerformed method to achieve our behavior.

We use an example to specifically explain how to perform actual operations.

First, a specific behavior is written, and the specified keyboard event is first processed:

public class TextAction extends AbstractAction {private String a; public TextAction (String a) {this.a = a;} public void actionPerformed (ActionEvent parm1) {String b = parm1.getActionCommand (); // get the behavior of the command string System .out.println ("Command =" b); System.out.println ("Prompt =" THIS.A);}}

Establish 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"); and then, in a The form is added to the two panels, named Sonpanel and ParentPanel, making ParentPanel ancestors of Sonpanel. And add a Button called SON in Sonpanel, adding the Button called ParentPanel. Add a few Button outside FatherPanel.

Get the three InputMaps of the SON component, and create an InputMap called Focusfatherim so that this inputmap is the Parent of Focusim:

// Get Default INPUTMAP (WHEN FOCUS INPUTMAP) and set a pent inputmapfocusim = SON.GETINPUTMAP (); Focusfatherim = New INPUTMAP (); Focusim.SetParent (FocusfatherIM);

// Get when_ancestor_of_focused_component inputMapanceStorim = Son.getInputMap (when_ancestor_of_focused_component);

// get WHEN_IN_FOCUSED_WINDOW inputMapwindowIm = son.getInputMap (WHEN_IN_FOCUSED_WINDOW); these are added InputMap keyboard bindings: focusIm.put (KeyStroke.getKeyStroke ( 'f'), "actionFocusSon"); focusFatherIm.put (KeyStroke.getKeyStroke ( ' F '), "ActionFocusfather"); Anchestroke.Put (Keystroke.getKeystroke (' a '), "ActionancenceStor"); Windowim.Put (Keystroke.getKeystroke (' W '), "ActionWindow"; get the lack of SON components Provincial ActionMap, and binds the established behavior with a specific object (string): am = SON.GETACTIONMAP ();

am.put ("Actionfocusson", Whenfocusson; am.put ("ActionFocusfather", Whenfocusfather; am.put ("ActionanceStor"; Am.put ("ActionWindow", WINDOW)

Run the program and its corresponding results:

1. Click the SON button, if you press 'f', 'f', 'A', 'W', the program will have the corresponding output. This is because the focus at this time is on the SON button, while the three inputmaps of the SON button component are valid. So what they have in response will happen.

2. Click the Parent button, then press 'W', the program will have the corresponding output. Press 'F', 'F', 'A', and the program has no response. This is because the PARENT button has a focus. This button is not ancestors of the SON button, and the window where the SON is located is focus, so only INPUTMAPs where the component is located is effective. 3. Click on the other buttons (buttons outside PARETPANEL), press 'W', and the program will have the corresponding output. Press 'F', 'F', 'A', and the program has no response. This is because these buttons have focus, they are not the ancestors of the SON button, and the windows in SON have focus, so only INPUTMAPs where the components are located. InputMap is effective. Attachment: The main program code:

Import java.aw. *; 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 evefter () {Try {jbinit ();} catch (exception ex) {ex.printstacktrace ();}} void Jbinit () throws Exception {btnyelow.Settext ("YELLOW"); btnyelow.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"); PARETPANEL.SETBORDER (BorderFactory.createraiadbevelborder ()) PARENTPANEL.SETBOUNDS (New Rectangle (27, 68, 358, 227)); PARENTPANEL.SetLayout (XYLAYOUT1); SONPANEL.SETBORDER (BorderFactory.createLoweredBevelBorder ()); SON.SETTEXT ("SON"); parent.setText (" Parent "); this.add (btnyell OW, NULL); this.Add (btnblue, null); this.add (btnred, null); this.Add (PARENTPANEL, NULL); PARETPANEL.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 ActionMap am = SON.GETACTIONMAP (); am.put ("Actionfocusson", Whenfocusson; am.put ("ActionFocusfather", Whenfocusfather; am.put ("ActionanceStor"; Am.put ("ActionWindow" , window);} public void actionPerformed (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 ife (source == btnred) color = color.red; else if (source == btnblue) Color = color.blue; setBackground (color); repaint ();}}

转载请注明原文地址:https://www.9cbs.com/read-17317.html

New Post(0)