Java KeyListener:当按下两个键时如何执行动作? [英] Java KeyListener: How to perform an action when two keys are pressed?

查看:335
本文介绍了Java KeyListener:当按下两个键时如何执行动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看下面的代码

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

public class KeyCheck extends JFrame
{
    private JButton check;
    private JPanel panel;
    private FlowLayout flow;

    public KeyCheck()
    {
        check = new JButton("Check");
        check.addKeyListener(new KeyWork());

        panel = new JPanel();
        panel.setLayout(new FlowLayout());
        panel.add(check);

        getContentPane().add(panel);

    }

    private class KeyWork extends KeyAdapter
    {
        public void keyPressed(KeyEvent k)
        {
            if(k.getKeyCode()==KeyEvent.VK_CONTROL && KeyEvent.VK_A)
            {
                JOptionPane.showMessageDialog(null, "OK");
            }
        }
    }
    public static void main(String[]args)
    {
        KeyCheck k = new KeyCheck();
        k.setVisible(true);
        k.setSize(200,200);
        k.validate();
        k.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

在这种情况下,我向按钮添加了一个键列表,当同时按下CTRL + A(控制键和"A"键)时,我需要它显示消息"OK".但是上面的代码是错误的.因此,当两个键同时按下时,请帮助我获取消息.

In this case, I have added an keylister to the button and I need to it to display the Message "OK" when CTRL + A is pressed together (control key and "A" key). But the above code is wrong. So, please help me to get message when both the keys are pressed together.

推荐答案

您正在混合但更笼统地说,最好使用 KeyBindings 而不是KeyListener.它将使您的生活更加轻松,并避免您必须进行此类测试.

But more generally, it is better to use KeyBindings instead of KeyListener. It will make your life a lot easier and avoid you to have to make those kind of tests.

1.创建一个像这样的动作:

1.Create an Action like this:

 public class MyAction extends AbstractAction {

     public void actionPerformed(ActionEvent e) {
          JOptionPane.showMessageDialog(null, "OK");
     }
 }

2.将动作绑定到按键:

2.Bind the action to the key stroke:

check.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK), "doSomething");
check.getActionMap().put("doSomething", new MyAction());

注意事项:我尚未测试此代码,因此可能必须修复一些小故障.

Caveats: I haven't tested this code so may have to fix minor glitches.

这篇关于Java KeyListener:当按下两个键时如何执行动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆