[英]Java Swing JMenuItem intercepts its accelerator key even entered into a JTextField component
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; 这里的问题是,如果我在文本字段中键入5
,不仅文本字段会获取此事件,菜单项也将得到此事件,并且将执行它的操作。 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. 在我的真实应用程序中,我有很多菜单项需要为几个文本字段禁用。
Bind the JMenuItem
with some modifiers such as Ctrl, Alt, Shift etc. if possible as mentioned here KeyStroke#getKeyStroke() . 如果可能的话 ,将JMenuItem
与一些修饰符(例如Ctrl,Alt,Shift等)绑定,如此处KeyStroke#getKeyStroke()所述 。
Try something like as shown below to bind it with Ctrl+5
. 尝试如下所示将其与Ctrl+5
绑定。
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, InputEvent.CTRL_DOWN_MASK));
It might help you if you don't want to use any modifier. 如果您不想使用任何修饰符,可能会对您有所帮助。
If the current focusable component is not JTextField
then perform action on JMenuItem
. 如果当前可聚焦组件不是JTextField
则对JMenuItem
执行操作。
Sample code: 样例代码:
JMenuItem item = new JMenuItem("Item1");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Component component = frame.getFocusOwner();
if (!(component instanceof JTextField)) {
JOptionPane.showMessageDialog(frame, "Menu Item clicked");
}
}
});
Read more here on In Swing, how can I find out what object currently has focus? 在In Swing中阅读更多内容,如何找到当前聚焦的对象?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.