如何避免按下ALT键会从我的GUI中消除焦点 [英] How to avoid that pressing the ALT key takes away the focus from my GUI

查看:189
本文介绍了如何避免按下ALT键会从我的GUI中消除焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个带有swing的Windows应用程序。

I'm developing a java app with swing in Windows.

问题是:在按下(并释放) ALT 键之后,下一次按键无效(不会触发keyPressed事件)。只有释放下一个键才会被识别。在 ALT 之后按下并释放 CTRL SHIFT 根本没有效果。您首先必须按另一个键或单击该组件才能再次从 CTRL SHIFT 接收关键事件。

The problem is: after pressing (and releasing) the ALT key, the next key press has no effect (there won't be a keyPressed event fired). Only the releasing the next key will be recognized. Pressing and releasing CTRL or SHIFT after ALT has no effect at all. The you first have to press another key or click into the component to receive key events from CTRL or SHIFT again.

可能Windows将焦点从我的GUI组件转移到帧的标题/菜单。
我需要 ALT + MouseWheel在我的应用程序中移动图形,如果我之后想用 CTRL + MouseWheel缩放图形,这将无法正常工作。
那么如何阻止 ALT 取消焦点(但仍然可以访问带有例如 ALT + F 的menuItem)?

Probably Windows takes the focus away from my GUI component to the title/menu of the frame. I need ALT+MouseWheel to move a graphic in my app, if I afterwards wants to zoom the graphic with CTRL+MouseWheel this won't be working. So howe to stop ALT from taking away the focus (but still be able to access a menuItem with e.g. ALT+F)?

我已经尝试过Component.requestFocus() - 但实际上我的组件并没有真正失去焦点。

I already tried Component.requestFocus() - but actually my component doesn't lose the focus really.

显示行为的简单示例:

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;

class MyKeyListener implements KeyListener {
public void keyTyped(KeyEvent arg0) {}

public void keyPressed(KeyEvent arg0) {
    System.out.println("Key perssed: " + arg0.getKeyCode());
}   
public void keyReleased(KeyEvent arg0) {
    System.out.println("Key released: " + arg0.getKeyCode());
}
}

public class KeyListenerDemo {

public static void main(String[] a) {
    JFrame frame = new JFrame("Keytest");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setFocusTraversalKeysEnabled(true);
    JTextField textField = new JTextField();
    textField.addKeyListener(new MyKeyListener());
    frame.add(textField);
    frame.setSize(300, 200);
    frame.setVisible(true);
}
}


推荐答案

In我的情况如下:KeyEvent.consume()

In my case the following worked: KeyEvent.consume()


消耗此事件,以便源不会以默认方式处理它它起源于它。

Consumes this event so that it will not be processed in the default manner by the source which originated it.

这会阻止Windows窃取我的焦点,但我仍然可以使用ALT键盘助记符来访问我的菜单项。

This stops Windows from stealing my focus, but I'm still able to access my menuitems with the keyboard mnemonics with ALT.

感谢Scott W的评论!!

Thanks to Scott W for his comment!!

这篇关于如何避免按下ALT键会从我的GUI中消除焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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