如何获取指定键的按下和释放事件?

时间:2014-07-15 11:52:31

标签: java swing awt key-bindings

我想知道用户何时按下指定键,如ctrl,shift或其他键以及用户何时释放它。

我已经为JPanel使用了Key Binding,我可以知道用户何时输入指定的密钥。代码如下:

 import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;

    import javax.swing.AbstractAction;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.KeyStroke;


    public class KeyBindingTest {
        public static void main(String[] args) {
            KeyBindingTest test = new KeyBindingTest();
            test.createUI();
        }

        public void createUI(){
            JFrame frame = new JFrame("KeyBinding Test");
            MainPanel mainPanel = new MainPanel();
            frame.add(mainPanel,BorderLayout.CENTER);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }

        @SuppressWarnings("serial")
        class MainPanel extends JPanel{
            public MainPanel(){
                setPreferredSize(new Dimension(200, 200));
                //========================key binding============================
                requestFocusInWindow();
                String ctrlString = "ctrlStr";
                getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_CONTROL, KeyEvent.CTRL_DOWN_MASK), ctrlString);
                getActionMap().put(ctrlString, new AbstractAction() {           
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        // TODO Auto-generated method stub
                        System.out.println("ctrl is typed");
                    }
                });         
            }   
        }
    }

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

您可以使用KeyStroke类,KeyStroke.getKeyStroke(int, int, boolean)KeyStroke.getKeyStroke(String)的这些变体来获得所需的结果。

对于按 CTRL ,请使用以下命令:

KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_CONTROL, InputEvent.CTRL_DOWN_MASK, false);

对于已发布的 CTRL ,请使用以下命令:

keyStroke = KeyStroke.getKeyStroke("released CONTROL");

在这里尝试这个程序:

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

public class KeyExample {

    private JPanel contentPane;

    private class KeyAction extends AbstractAction {

        private String keyState;
        private String keyValue;

        public KeyAction(String state, String value) {
            this.keyState = state;
            this.keyValue = value;
        }

        @Override
        public void actionPerformed(ActionEvent ae) {
            System.out.println("Value: " + keyValue + " State: " + keyState);
        }
    }

    private void displayGUI() {
        JFrame frame = new JFrame("Swing Worker Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        contentPane = new JPanel();
        InputMap inputMap = contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);

        KeyStroke keyStroke = null;

        keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_CONTROL, InputEvent.CTRL_DOWN_MASK, false);
        inputMap.put(keyStroke, "pressedControl");
        contentPane.getActionMap().put("pressedControl", new KeyAction("pressed", "CONTROL"));

        keyStroke = KeyStroke.getKeyStroke("released CONTROL");
        inputMap.put(keyStroke, "releasedControl");
        contentPane.getActionMap().put("releasedControl", new KeyAction("released", "CONTROL"));

        keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT, InputEvent.SHIFT_DOWN_MASK, false);
        inputMap.put(keyStroke, "pressedShift");
        contentPane.getActionMap().put("pressedShift", new KeyAction("pressed", "SHIFT"));

        keyStroke = KeyStroke.getKeyStroke("released SHIFT");
        inputMap.put(keyStroke, "releasedShift");
        contentPane.getActionMap().put("releasedShift", new KeyAction("released", "SHIFT"));

        keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ALT, InputEvent.ALT_DOWN_MASK, false);
        inputMap.put(keyStroke, "pressedAlt");
        contentPane.getActionMap().put("pressedAlt", new KeyAction("pressed", "ALT"));

        keyStroke = KeyStroke.getKeyStroke("released ALT");
        inputMap.put(keyStroke, "releasedAlt");
        contentPane.getActionMap().put("releasedAlt", new KeyAction("released", "ALT"));

        frame.setContentPane(contentPane);
        frame.setSize(300, 100);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                new KeyExample().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

编辑:2

实际上,自从我回答这个问题以来,这就是我自昨天以来所做的事情。但似乎他们确实阻止了该实现,但是如果我在 CTRL SHIFT 中添加另一个键,那么它可以正常工作。如下面的代码段所示:

keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK, false);
        inputMap.put(keyStroke, "pressedControlShift");
        contentPane.getActionMap().put("pressedControlShift", new KeyAction("pressed", "CONTROL SHIFT"));