使用Nimbus LAF的Mac键盘快捷键

时间:2012-03-20 00:50:14

标签: java macos swing keyboard-shortcuts nimbus

有没有办法在OS X上使用Nimbus LAF(外观和感觉),同时仍然能够使用 Meta 键进行剪切/复制/粘贴和选择所有操作?

我目前在Swing应用程序的主要方法中有以下代码,它根据操作系统更改了LAF(OS X的默认值,所有其他的Nimbus):

if (!System.getProperty("os.name", "").startsWith("Mac OS X")) {
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(LicenseInspectorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(LicenseInspectorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(LicenseInspectorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(LicenseInspectorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
}

我这样做是一种解决方法,因为Nimbus会在OS X上覆盖剪切/复制/粘贴和select-all的键盘快捷键( Meta 键与 Ctrl 键)。如果只是键盘快捷键没有被覆盖,我宁愿一直使用Nimbus。

2 个答案:

答案 0 :(得分:3)

使用getMenuShortcutKeyMask()方法与NimbusLookAndFeel一起使用以启用键,如此example所示。另请参阅此相关answer

JTextField的特定情况下,您可以使用key binding中的掩码来唤起原始操作。

int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
JTextField jtf = new JTextField("Test");
jtf.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_A, MASK), "select-all");
jtf.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_C, MASK), "copy");
jtf.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_X, MASK), "cut");
jtf.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_V, MASK), "paste");

答案 1 :(得分:1)

不同的组件使用不同的键,因此要映射所有键,您必须定义不同的键。例如(从here找到的基础):

// This must be performed immediately after the LaF has been set
if (System.getProperty("os.name", "").startsWith("Mac OS X")) {
  // Ensure OSX key bindings are used for copy, paste etc
  // Use the Nimbus keys and ensure this occurs before any component creation
  addOSXKeyStrokes((InputMap) UIManager.get("EditorPane.focusInputMap"));
  addOSXKeyStrokes((InputMap) UIManager.get("FormattedTextField.focusInputMap"));
  addOSXKeyStrokes((InputMap) UIManager.get("PasswordField.focusInputMap"));
  addOSXKeyStrokes((InputMap) UIManager.get("TextField.focusInputMap"));
  addOSXKeyStrokes((InputMap) UIManager.get("TextPane.focusInputMap"));
  addOSXKeyStrokes((InputMap) UIManager.get("TextArea.focusInputMap"));
  addOSXKeyStrokes((InputMap) UIManager.get("Table.ancestorInputMap"));
  addOSXKeyStrokes((InputMap) UIManager.get("Tree.focusInputMap"));
}

然后可以将其映射到不同的组件,如下所示:

{{1}}

Aqua(OS X外观和感觉)动作名称的完整列表为here