java中对窗体设置快捷键程序,java中的自定义键盘快捷键

在Java Swing应用中,开发者遇到一个问题,即如何为非焦点组件设置全局键盘快捷键(如CTRL+H),使其行为与点击jButton1相同。尝试使用KeyEventDispatcher未成功。解决方案涉及为特定KeyStroke创建Action,并在必要时为组件添加该Action,以实现在任何情况下都能响应快捷键。

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

I am developing a java swing application. I want to add a keyboard shortcut say CTRL + H. This should perform the same action performed by jButton1 when clicked.

This shortcut should behave in the same way even when jButton1 is not focused.

I tried with KeyEventDispatcher, but it doesn't seem to be working for me. Is there any other way?

解决方案

Ok - First I don't think there is a way to set application wide shortcuts in Java Swing(Refer this question). But for a component it is possible.

You have to use a create an Action for the KeyStroke. But for Windows I found this library very helpful.

{

KeyStroke cancelKeyStroke = KeyStroke

.getKeyStroke((char) KeyEvent.VK_ESCAPE);

Keymap map = JTextComponent.getKeymap(JTextComponent.DEFAULT_KEYMAP);

map.addActionForKeyStroke(cancelKeyStroke, cancelKeyAction);

}

private static Action cancelKeyAction = new AbstractAction() {

public void actionPerformed(ActionEvent ae) {

Component comp = (Component) ae.getSource();

Window window = SwingUtilities.windowForComponent(comp);

if (window instanceof Dialog) {

window.dispose();

} else if (comp instanceof JTextComponent

&& !(comp instanceof JFormattedTextField)) {

JTextComponent tc = (JTextComponent) comp;

int end = tc.getSelectionEnd();

if (tc.getSelectionStart() != end) {

tc.setCaretPosition(end);

}

}

}

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值