JPanel keylistener [英] JPanel keylistener

查看:101
本文介绍了JPanel keylistener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加一个包含 JTabbedPane 的密钥监听器。

当收到ctrl + tab时,它应该切换标签。

但是keypressed事件永远不会被发送
我尝试将它添加到面板和选项卡式对象 - 但没有成功。

I am trying to add a key listener that holds a JTabbedPane.
It should switch the tabs when ctrl + tab is received.
But the keypressed event is never sent I tried adding it to the panel and to the tabbed object - but with no success.

这是我的代码

SwitchTabsListener ctrlTabListener = new SwitchTabsListener(genericTabbedPanel);  
jMainFrame.addKeyListener(ctrlTabListener);  
genericTabbedPanel.addKeyListener(ctrlTabListener);  


推荐答案

以典型的方式,您的关键事件不会被拦截通过正确的Swing组件。您必须了解光标下方的第一个组件将接收键盘事件。如果你用键盘选择一个按钮,那将是这个JButton会收到关键事件。

In a typical fashion, your key event is not intercepted by the correct Swing component. You have to understand that the first component below the cursor will receive the keyboard event. Were you to select a button with your keyboard, it would be this JButton that would receive the key event.

为了确保你得到所有这些事件,你没有必须在组件上注册,而是使用 KeyboardFocusManager ,它将在任何地方接收关键事件。

To make sure you get all those events, you don't have to register on components, but rather by using a KeyboardFocusManager, which will receive key events wherever they occur.

您的代码需要以下元素

KeyEventDispatcher myKeyEventDispatcher = new DefaultFocusManager();
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(myKeyEventDispatcher);

myKeyEventDispatcher 然后会接到<$的电话c $ c> dispatchKeyEvent 只要按下某个键,无论它在UI中的哪个位置。这样,您可以确保正确调用您的代码。

myKeyEventDispatcher will then receive calls to dispatchKeyEvent whenever a key is pressed, wherever it is in UI. This way, you can make sure your code is correctly called.

注册密钥监听器的另一种方法是要求您使用 HierarchyListener 为您的关键监听器添加:移除到​​每个swing组件,这些组件似乎作为根组件的子级添加/删除。这不仅编写起来很麻烦,而且很难调试和理解。

The alternative method of registering key listener would require you to use a HierarchyListener in order for your key listener to be added:removed to each and every swing component that appear to be added/removed as a child of your root component. This is not only cumbersome to write, but also really hard to debug and understand.

这就是为什么我更喜欢蛮力,但是虽然添加的方式非常优雅应用程序全局键侦听器到特定键盘焦点管理器。

This is why I prefer the more brute-force, but although quite elegant way of adding application global key listener to a specific keyboard focus manager.

这篇关于JPanel keylistener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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