Activating a Keystroke When Any Component in the Window Has Focus : Key Event « Event « Java






Activating a Keystroke When Any Component in the Window Has Focus

    

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;

public class Main {
  public static void main(String[] argv) throws Exception {

    JButton component = new JButton();

    MyAction action = new MyAction();
    component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F2"),
        action.getValue(Action.NAME));
  }
}

class MyAction extends AbstractAction {
  public MyAction() {
    super("my action");
  }

  public void actionPerformed(ActionEvent e) {
    System.out.println("hi");

  }
}

   
    
    
    
  








Related examples in the same category

1.KeyListener, ActionListener Demo 1KeyListener, ActionListener Demo 1
2.KeyListener, ActionListener Demo 2KeyListener, ActionListener Demo 2
3.Key event on frameKey event on frame
4.Responding to KeystrokesResponding to Keystrokes
5.Key Event DemoKey Event Demo
6.Set java.awt.Container.getFocusTraversalKeys(int id)
7.KeyStroke.getKeyStroke("F2")
8.InputMap javax.swing.JComponent.getInputMap(int condition)
9.Activating a Keystroke When Any Child Component Has Focus
10.Listening to All Key Events Before Delivery to Focused Component
11.List keystrokes in the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT input map of the component
12.List keystrokes in the WHEN_IN_FOCUSED_WINDOW input map of the component
13.Converting a KeyStroke to a String
14.Creating a KeyStroke and Binding It to an Action
15.void InputMap.put(KeyStroke keyStroke, Object actionMapKey)
16.Map actions with keystrokes
17.Handling Key Presses
18.Get key pressed as a key character (which is a Unicode character)
19.Get key pressed as a key code
20.Get Key Text
21.KeyStroke to String
22.Construct a new key description from a given universal string descriptionConstruct a new key description from a given universal string description
23.Reads for modifiers and creates integer with required mask