Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing KeyStrokes: how to make CTRL-modifier work

In the following program, why does hitting the a key print "hello, world" while hitting CTRL+a doesn't?

import java.awt.event.*;
import javax.swing.*;

public class KeyStrokeTest {
    public static void main(String[] args) {
        JPanel panel = new JPanel();

        /* add a new action named "foo" to the panel's action map */
        panel.getActionMap().put("foo", new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("hello, world");
                }
            });

        /* connect two keystrokes with the newly created "foo" action:
           - a
           - CTRL-a
        */
        InputMap inputMap = panel.getInputMap();
        inputMap.put(KeyStroke.getKeyStroke(Character.valueOf('a'), 0), "foo");
        inputMap.put(KeyStroke.getKeyStroke(Character.valueOf('a'), InputEvent.CTRL_DOWN_MASK), "foo");

        /* display the panel in a frame */
        JFrame frame = new JFrame();
        frame.getContentPane().add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }
}

How could I fix it that CTRL+a works as well?

like image 971
Thomas Avatar asked Mar 10 '10 18:03

Thomas


People also ask

How do you code KeyStrokes in Java?

Basically in order to set up and use key strokes in Java, one should follows these steps: Use KeyStroke. getKeyStroke(String keystroke) to get a KeyStroke object that represent the keystroke you dictated. Create an input component like a JButton and use its getInputMap method to get the InputMap of that component.

What is Java KeyStroke?

A KeyStroke represents a key action on the keyboard, or equivalent input device. KeyStrokes can correspond to only a press or release of a particular key, just as KEY_PRESSED and KEY_RELEASED KeyEvents do; alternately, they can correspond to typing a specific Java character, just as KEY_TYPED KeyEvents do.

What is an action in Java?

An Action can be used to separate functionality and state from a component. For example, if you have two or more components that perform the same function, consider using an Action object to implement the function.


2 Answers

I find it easier to use:

KeyStroke a = KeyStroke.getKeyStroke("A");
KeyStroke controlA = KeyStroke.getKeyStroke("control A");

or:

KeyStroke controlA = KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK);
like image 84
camickr Avatar answered Sep 23 '22 21:09

camickr


Dude, use this

inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK), "foo");
like image 41
bragboy Avatar answered Sep 21 '22 21:09

bragboy