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?
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 JTextField
s 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.
Have you seen, know of or are using the SWT (Standard Widget Toolkit) maintained by Eclipse? That has a key press (SWT.COMMAND) for command.
Are you running pure Swing? If so it should do that automatically(note it may not make the little menu animation if you dont use an Application bundle). If not then you will have to consult the documentation for whatever API you are using.
Just tested it and it works fine on Snow Leopard.
精彩评论