在背景框架上使用Java KeyListener [英] Use a Java KeyListener on a background frame

查看:71
本文介绍了在背景框架上使用Java KeyListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内容窗格,其中包含一个JScrollPane,该JScrollPane包裹在我正在使用的不可编辑JTextArea上(现在),它仅显示有关所按下的键的信息(只是试图使此KeyListener起作用). /p>

KeyListener位于JTextArea上,并且在选择框架时一切正常.但是,即使选择了另一个窗口,我也希望注册按键.有什么办法吗?

谢谢.

解决方案

我过去曾经这样做过,但我不记得确切是怎么做的.我认为这类似于:

KeyEventDispatcher dispatcher = new KeyEventDispatcher()
{
    public boolean dispatchKeyEvent(KeyEvent e)
    {
        System.out.println(e.getKeyChar());
        return false;
    }
};

DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);

只需使用您的自定义代码修改SysOut.如果要防止调度事件,则该方法应返回true而不是false.我还发现了这个问题,可以解决您的问题.

I have a content pane containing a JScrollPane wrapped around a non-editable JTextArea that I'm using to (right now) simply display info about what key is being pressed (was just trying to get this KeyListener to work).

The KeyListener is on the JTextArea and everything works fine when the frame is selected. However, I'd like for the key presses to be registered even if another window is selected. Any way to do this?

Thanks.

解决方案

I did that in the past but I do not remember exactly how. I think it was similar to that:

KeyEventDispatcher dispatcher = new KeyEventDispatcher()
{
    public boolean dispatchKeyEvent(KeyEvent e)
    {
        System.out.println(e.getKeyChar());
        return false;
    }
};

DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);

Just modify the SysOut with your custom code. If you want to prevent an event from being dispatched, the method should return true instead of false. I also found this question that may adress your problem.

这篇关于在背景框架上使用Java KeyListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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