java 按两个键,Java KeyListener:当按下两个键时如何执行动作?

本文介绍了一个Java Swing应用中处理键盘事件的问题,原始代码试图在用户按下CTRL+A时显示消息框,但实现有误。解决方案是改用KeyBindings来注册组合键事件,避免手动检查修饰键。示例代码给出了如何创建一个Action并将其绑定到CTRL+A键,当按下此组合键时,会显示‘OK’消息框。这种方法更简洁且易于维护。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Please have a look at the following code

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);

}

}

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.

解决方案

if(k.getKeyCode()==KeyEvent.VK_A

&& (k.getModifiers & KeyEvent.CTRL_MASK==KeyEvent.CTRL_MASK))

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.Create an Action like this:

public class MyAction extends AbstractAction {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(null, "OK");

}

}

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值