KeyStroke.getKeyStroke(int, int)
不用于获取KeyStroke
新闻或发布事件,它用于以和/或和/或和/或和/或...KeyStroke
的形式将修饰符应用于KeyEvent.SHIFT_DOWN_MASK
KeyEvent.CTRL_DOWN_MASK
KeyEvent.ALT_DOWN_MASK
KeyEvent.ALT_GRAPH_DOWN_MASK
KeyEvent.META_DOWN_MASK
而不是getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, KeyEvent.KEY_PRESSED), "none");
你应该使用getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0), "none");
当我使用以下内容时,我可以获得在字段聚焦时触发的关键动作......
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTextFieldKeyStroke {
public static void main(String[] args) {
new TestTextFieldKeyStroke();
}
public TestTextFieldKeyStroke() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JTextField field = new JTextField(20);
add(field);
JPopupMenu pop = new JPopupMenu();
field.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0), "happy");
field.getActionMap().put("happy", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Happy");
}
});
}
}
}
更新了弹出窗口
根据前面的示例,如果我执行类似...
final JTextField field = new JTextField(20);
add(field);
JPopupMenu pop = new JPopupMenu();
pop.add(new JLabel("Hello"));
field.setComponentPopupMenu(pop);
field.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0), "happy");
field.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, KeyEvent.CTRL_DOWN_MASK), "happy");
field.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, KeyEvent.ALT_DOWN_MASK), "happy");
field.getActionMap().put("happy", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
JPopupMenu popup = field.getComponentPopupMenu();
popup.show(field, 0, field.getHeight());
}
});
我可以让它显示JPopupMenu