KeyStroke.getKeyStroke(int, int)
isn't used to get the KeyStroke
for a press or release event, it is used to apply a modifier to the KeyStroke
in the form of KeyEvent.SHIFT_DOWN_MASK
and/or KeyEvent.CTRL_DOWN_MASK
and/or KeyEvent.ALT_DOWN_MASK
and/or KeyEvent.ALT_GRAPH_DOWN_MASK
and/or KeyEvent.META_DOWN_MASK
...
Instead of getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, KeyEvent.KEY_PRESSED), "none");
you should be using getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0), "none");
When I use the following, I can get the key action to trigger when the field is focused...
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");
}
});
}
}
}
Updated with popup
I'm still missing something here, based on the previous example, if I do something like...
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());
}
});
I can get it to show the JPopupMenu