复制粘贴快捷方式仅适用于 OSX Java 应用程序中的 ctrl 键

copy paste shortcuts only working with ctrl key in OSX Java application

我在 OSX 上使用 Netbeans 8.1 创建了一个小应用程序,执行以下步骤:

在这个 JDialog 中,我需要文本字段的复制/粘贴功能。问题是:复制/粘贴仅适用于 "ctrl" + "c"、"x" 或 "v" 的对话框,不适用于 osx 标准 "cmd" 钥匙。

我尝试将以下代码行添加到 JForm 的构造函数中,但没有成功:

KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());

附加信息: 我正在使用 JDK7 和 OSX Yosemite。外观和感觉是 "Nimbus"。其他两个菜单 ("File","Edit") 尚未实现。

你能给出解决方案的提示吗?

更新: 我使用 Netbeans GUI 构建器(Swing GUI Forms -> JDialog)创建了另一个小示例。我刚刚向 JFrame 添加了一个菜单栏,并在 GUI 构建器中添加了一个 JMenuItem。根据下面答案的评论,我手动向构造函数添加了一些代码:

public NewJDialogGUI(java.awt.Frame parent, boolean modal) {
        super(parent, modal);   
        initComponents();

        AbstractAction copyAction = new DefaultEditorKit.CopyAction();
        copyAction.putValue(Action.ACCELERATOR_KEY,KeyStroke.getKeyStroke(KeyEvent.VK_C, MASK));

        this.jMenuItem1.setAction(copyAction);
        this.jMenuItem1.setText("Copy");
        this.jMenuItem1.setMnemonic(KeyEvent.VK_C);
    }

结果是:

更新2: 我使用 Netbeans GUI 构建器创建了另一个小示例(Swing GUI 表单 -> 应用程序示例表单)。

结果是:

最后,我使用 Netbeans(空 Java 文件)创建了一个示例,源代码根据以下答案稍作修改。

结果是:

Java 使用 Actions to encapsulate functionality and Key Bindings to respond to keys typed by the user. In this example, the DefaultEditorKit action CopyAction is used as the menu item's Action. It will copy the user's selection from the focused text component to the clipboard. Use Toolkit.getMenuShortcutKeyMask() to get the correct accelerator, as discussed here.

import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.DefaultEditorKit;

/**
 * @see 
 */
public class MenuTest {

    private static final int MASK
        = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("Edit");
        menu.setMnemonic(KeyEvent.VK_E);
        JMenuItem menuItem = new JMenuItem();
        AbstractAction copyAction = new DefaultEditorKit.CopyAction();
        copyAction.putValue(Action.ACCELERATOR_KEY,
            KeyStroke.getKeyStroke(KeyEvent.VK_C, MASK));
        menuItem.setAction(copyAction);
        menuItem.setText("Copy");
        menu.add(menuItem);
        menuBar.add(menu);
        f.setJMenuBar(menuBar);
        f.add(new JTextField(10));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new MenuTest()::display);
    }
}