我想在我的 Swing 应用程序中有一个自定义 Tab 和 Shift+Tab 监听器。这适用于 JTextField textField
当按下 TAB 键时=>
textField.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "Tab");
textField.getActionMap().put("Tab", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
navigateDown();
}
});
但是,我想要实现 Shift + Tab
并且我使用了这段代码:-
textField.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT, KeyEvent.VK_TAB), "BackTab");
textField.getActionMap().put("BackTab", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
navigateUp();
}
});
但是,这对我不起作用。感谢您的关注。
最佳答案
您的击键不正确。第二个整数不是键码而是修饰符。
像这样尝试:
textField.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB, java.awt.event.InputEvent.SHIFT_DOWN_MASK), "BackTab");
textField.getActionMap().put("BackTab", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
navigateUp();
}
});
另请参阅有关 Keystroke.getKeyStroke()
的 JavaDoc
关于java - 多个键的 InputMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27563902/