The default action of F10 is to show the menu of the window. However, I would like to disable this feature.
UPDATED: Background: I would like to implement a special behavior in a JTextField if the user presses any key. Unfortunately, the JTextField don't get the event when F10 is pressed because it is catched by the window (and the menu is shown).
Does anyone know how to disable this key binding in the window?
I tried to disable it in the root pane but without success:
frame.getRootPane().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0), "none");
I searched a lot but found no solution for this issue. Maybe one of you knows an answer.
UPDATE2 Here a code example to reproduce this behavior:
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
final JTextField edit = new JTextField();
edit.setEditable(false);
edit.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(final KeyEvent ke) {
edit.setText(KeyEvent.getKeyText(ke.getKeyCode()));
}
});
final JFrame frame = new JFrame("DEMO");
frame.setSize(320, 240);
frame.getContentPane().add(edit);
frame.setVisible(true);
}
});
}
Plase note: There is a different behavior according to whether "setDefaultLookAndFeelDecorated" is set to true or false.
Thanks in advance :)
I tried to disable it in the root pane but without success:
Check out Key Bindings for the bindings of all Swing components.
You will see that the F10 key is bound to the JMenuBar
. So you should be able to use:
menuBar.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0), "none");
Edit:
Missed the point that you didn't have a menu bar.
It appears you can't just set the binding to "none". Looks like Swing is still searching up the tree to find an Action to execute. You need to provide a dummy Action that does nothing:
Action action = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("do nothing");
}
};
JPanel content = (JPanel)frame.getContentPane();
String key = "F10";
KeyStroke f10 = KeyStroke.getKeyStroke( key );
frame.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(f10, key);
frame.getRootPane().getActionMap().put(key, action);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With