简体   繁体   English

Mac 上的 Java:屏幕菜单栏中的键盘命令未执行

[英]Java on Mac: Keyboard commands from screen menubar not executed

Using Java 8 with Swing on a Mac, I'm having a JMenuBar in a JFrame which is placed as a screen menu bar using the system property apple.laf.useScreenMenuBar .在 Mac 上使用带有 Swing 的 Java 8,我在 JFrame 中有一个 JMenuBar,它使用系统属性apple.laf.useScreenMenuBar作为屏幕菜单栏放置。

When I open a child dialog inside this JFrame, I should be able to access my menu commands via their shortcuts.当我在这个 JFrame 中打开一个子对话框时,我应该能够通过它们的快捷方式访问我的菜单命令。 When hitting my shortcut (Command +Z) The menubar flashes, but the command is not executed.当点击我的快捷方式(Command +Z)时菜单栏闪烁,但不执行命令。 Any suggestions?有什么建议?

Here a code snippet to run the problem.这是运行问题的代码片段。 Pressing Command+Z in the main JFrame works and executes the action.在主 JFrame 中按 Command+Z 工作并执行操作。 Pressing Command +Z inside the child window doesn't work.在子窗口内按 Command +Z 不起作用。

public class TestClass {

    static class MyFrame extends JFrame {

        public MyFrame() throws HeadlessException {
            JMenuBar menuBar = new JMenuBar();
            JMenu menu = new JMenu("menu");
            JMenuItem menuItem = new JMenuItem(new AbstractAction("action") {
                {
                    putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
                }

                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("action executed!");
                }
            });
            menu.add(menuItem);
            menuBar.add(menu);
            setJMenuBar(menuBar);
            JButton button = new JButton("open dialog");
            add(button);
            button.addActionListener((e) -> {
                JDialog dlg = new JDialog(MyFrame.this);
                dlg.setSize(300, 300);
                dlg.setVisible(true);
            });
        }

    }

    public static void main(String[] args) {
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        MyFrame f = new MyFrame();
        f.setSize(400, 400);
        f.setVisible(true);
    }


}

I encountered the same issue with a JFrame on macOS (jdk1.8.0_201).我在 macOS (jdk1.8.0_201) 上遇到了与 JFrame 相同的问题。 Symptoms:症状:

  • menus work fine with a mouse, and menu shortcuts are visible on the menu items菜单可以用鼠标正常工作,菜单快捷方式在菜单项上可见
  • when the shortcut keys are pressed, the menu heading flashes but no ActionEvent is triggered按下快捷键时,菜单标题闪烁但不触发ActionEvent

I eventually figured out the issue was caused by overriding java.lang.Object 's hashCode() method on the JFrame.我最终发现问题是由覆盖 JFrame 上的java.lang.ObjecthashCode()方法引起的。 Why this causes keyboard shortcuts to fail is unknown to me, but it is definitively the root cause in my case.我不知道为什么这会导致键盘快捷键失败,但这绝对是我的案例的根本原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM