我尝试使用此代码在Mac OS上覆盖快捷键,但它不起作用。
if (System.getProperty("os.name", "").toUpperCase().startsWith("MAC")) {
InputMap im = (InputMap) UIManager.get("TextField.focusInputMap");
int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, MASK), DefaultEditorKit.selectAllAction);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, MASK), DefaultEditorKit.copyAction);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, MASK), DefaultEditorKit.pasteAction);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, MASK), DefaultEditorKit.cutAction);
}
但是,这确实...通过替换为特定的文本字段。
if (System.getProperty("os.name", "").toUpperCase().startsWith("MAC")) {
InputMap im = (InputMap) txtOutput.getInputMap();
int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, MASK), DefaultEditorKit.selectAllAction);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, MASK), DefaultEditorKit.copyAction);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, MASK), DefaultEditorKit.pasteAction);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, MASK), DefaultEditorKit.cutAction);
}
是否可以一次覆盖所有文本字段的快捷键?
我正在使用java swing。
不知道您现在在做什么,因为您没有向我们提供 MCVE,但您需要在创建摆动组件之前更改属性:
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.DefaultEditorKit;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Test());
}
Test() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
InputMap im = (InputMap) UIManager.get("TextField.focusInputMap");
int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_B, MASK), DefaultEditorKit.cutAction);
JTextField tf = new JTextField("FF");
JFrame frame = new JFrame();
frame.add(tf);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}