Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to define keyboard events in Java Swing

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about how keyboard events are defined in Java Swing. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

In jdk1.2, different methods for handling keyboard events are customized for objects of Jcomponent and Text classes: in Jcomponent, the registerKeyboardAction method is defined, which is used to bind the keyboard events to be handled and the behavior to handle them. There is a keymap object in the Text class, similar to the handling method in Jcomponent, which holds the keyboard events and corresponding behaviors that need to be handled.

In jdk1.3, a new method is used to handle keyboard events, which integrates the two methods of jdk1.2. There is no need to distinguish between components of type Jcomponent or Text being processed. It defines two new classes: InputMap and ActionMap. They are all simple tables or mappings. An InputMap maps a Keystroke to an object, and ActionMap maps an object to an Action. Usually, the object corresponding to KeyStroke in InputMap is a string through which the corresponding behavior can be found in ActionMap.

There are put methods in both InputMap and ActionMap. InputMap's put method can map Keystroke to an object, while ActionMap's put method can map an object to a behavior.

In each Jcomponent component, there are three default InputMap and one default ActionMap. They can get it by calling getInputMap (int condition) and getActionMap (). The three InputMap are the InputMap (WHEN_FOCUSED) when the component itself has focus, the InputMap (WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) when the ancestors of the component have focus, and the InputMap (WHEN_IN_FOCUSED_WINDOW) when the form on which the component is located has focus (parentheses indicate the parameters that should be set in getInputMap in order to get these InputMap). These three types of InputMap are described below:

1. InputMap when the component itself has focus: when the component has focus and the keyboard key is pressed, java looks in this InputMap for the KeyStroke object corresponding to the keyboard event.

two。 The InputMap when the ancestor of the component has focus: when the ancestor of the component has focus and the keyboard key is pressed, java looks for the InputMap.

3. The InputMap when the window of the component has focus: when the window of the component has focus and the keyboard key is pressed, java looks for the InputMap.

When a key is pressed and the event is converted into a KeyStroke object, java looks for the corresponding InputMap of the Jcomponent (for example, when the ancestor of the component has focus, java looks for the InputMap where the ancestor of the Jcomponent has focus). If so, take out the corresponding object (usually a string), use this object to look in the ActionMap of the Jcomponent, and if you find the corresponding behavior (Action) Then java executes the actionPerformed method for this behavior (this method is described later). In order to achieve the purpose of dealing with keyboard events.

Each InputMap can have a parent attribute whose value is an InputMap. When the KeyStroke of a keyboard event is not found in an InputMap, the java automatically looks in the InputMap specified by its parent property and looks up until it is found. The advantage of using parent is that when there are some fixed keyboard mappings that do not want users to make changes, they can be stored in the InputMap specified by the parent attribute to avoid accidental modification; in addition, the default InputMap settings of multiple Jcomponent can have the same parent, so that some keyboard binding settings can be shared. You can set its parent property through the setparent () method of the InputMap class. ActionMap also has the same parent property and uses it in the same way.

The above is how to map a keyboard event to a behavior. Here is a brief introduction to the behavior (Action).

The behavior is a class that implements the Action interface. Seven methods are defined in the Action interface. The most critical of these is the actionPerformed () method. This method describes the specific operation of this behavior. Several other methods include the setEnabled,isEnabled,putValue,getValue,addPropertyChangeListener, and removePropertyChangeListener methods. They are used to set whether the behavior is available, to determine the state available to the behavior, to set and get some properties of the behavior, and the last two methods are used to allow other objects to be notified after the properties of the action object have changed.

Usually we use an abstract class AbstractAction class that implements most of the methods of the Action interface as the base class, overloading the actionPerformed method to implement our behavior.

Let's use an example to illustrate how to do it in practice.

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

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 command string of the behavior

System.out.println ("command=" + b)

System.out.println ("prompt=" + this.a)

}

}

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 the sonPanel and a button named parent to the parentPanel. Add several button outside the fatherPanel.

Get the three InputMap of the son component, and create an InputMap named focusFatherIm, making this InputMap the 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 keyboard bindings to these 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 default ActionMap of the son component and bind the established 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 its corresponding results:

1. Click the son button, at this time, if you press Fmai FMagna Pol w, the program will have the corresponding output. This is because the focus at this time is on the son button, and all three InputMap of the son button component are valid. So all their corresponding events will happen.

two。 Click the parent button and press w, and the program will have the corresponding output. The program did not respond when you pressed fforce and fjora. This is because the parent button has focus, which is not the ancestor of the son button, and the window where the son is located has focus, so only the InputMap with focus in the window where the component resides is valid.

3. Click the other button (the button outside parentPanel), press w at this time, the program will have the corresponding output. The program did not respond when you pressed fforce and fjora. This is because these buttons have focus, they are not the ancestors of the son button, and the window where the son is located has focus, so only the InputMap with focus in the window where the component resides is valid.

Attached: 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 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 if (source==btnRed) color = Color.red

Else if (source = = btnBlue) color = Color.blue

SetBackground (color)

Repaint ()

}

}

Thank you for reading! This is the end of the article on "how to define keyboard events in Java Swing". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report