Example code:
public class FrameMenuTextFieldTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JFrame frame = new JFrame();
frame.getContentPane().add(new JTextField());
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("Menu");
JMenuItem item = new JMenuItem("Item1");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Menu Item clicked");
}
});
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, 0));
menu.add(item);
menubar.add(menu);
frame.setJMenuBar(menubar);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
The problem here is if I type 5
into the textfield, not only the textfield gets this event, but the menu item as well, and its action is performed; message shown.
What is the simplest way to disable the key event propagation to the menu bar?
I my real application, I have a lot of menu items to disable for a few textfields.