How to use Command-c/Command-v shortcut in Mac to copy/paste text?

Brad picture Brad · Aug 31, 2011 · Viewed 12.1k times · Source

I have a Java Swing application that i want to run on Mac OS X. I want to use the normal Mac copy/paste shortcuts to copy/paste text to a text field in my Java application.

Ctrl+c & Ctrl+v does the trick but i want to use Command+c & Command+v instead. How can i do that?

Answer

cgull picture cgull · Aug 31, 2011

If you're using a 3rd-party L&F implementation it probably doesn't support the Mac's native keyboard shortcuts. The following code should reinstate the Mac's keyboard shortcuts for JTextFields after setting the L&F:

InputMap im = (InputMap) UIManager.get("TextField.focusInputMap");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.META_DOWN_MASK), DefaultEditorKit.copyAction);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.META_DOWN_MASK), DefaultEditorKit.pasteAction);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.META_DOWN_MASK), DefaultEditorKit.cutAction);

Of course you'll only need to do this if you detect that the application is running on a Mac so that you don't affect the keyboard mappings for other OS's.