我尝试使用此代码覆盖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);
}
但是,这可以...替换为特定的TextField ..
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);
}
是否可以立即覆盖所有TextField的快捷键?
我正在使用java swing。
答案 0 :(得分:0)
现在不知道你在做什么,因为你没有给我们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);
}
}