【问题标题】:Catch all KeyEvent of the application捕获应用程序的所有 KeyEvent
【发布时间】:2018-03-29 08:41:20
【问题描述】:

我有一个带有主 JFrame 以及其他 JDialog 和 JFrame 的应用程序。

我希望用户在按下 F7 时能够截取屏幕截图。

我在主框架上有一个 KeyListener,但是当框架失去焦点时它不会工作。

有没有比将 KeyListener 添加到所有窗口更好的方法来实现我想要的?

感谢您的帮助。

【问题讨论】:

    标签: java user-interface keylistener


    【解决方案1】:

    好的,我找到了我要找的东西,KeyboardFocusManager,负责将所有 KeyEvent 调度到焦点元素。
    以下是它的工作原理:

    KeyboardFocusManager.getCurrentKeyboardFocusManager()
                    .addKeyEventDispatcher(e -> {
                        if (e.getKeyCode() == KeyEvent.VK_F7 &&
                            e.getID() == KeyEvent.KEY_RELEASED) {
                            //do something
                        }
                        return true; //dispatch the event
                    });
    

    【讨论】:

      猜你喜欢
      • 2017-04-13
      • 1970-01-01
      • 2019-03-02
      • 2014-02-14
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多