Java Swing:为什么在 JFrame 中拖放会触发“Ctrl”C加速器?
我创建一个 JFrame 并在其中放置一个 JMenuBar,添加带有“Ctrl+C”加速器的“复制”菜单项。下面贴出完整的源代码。当我在 JFrame 中进行拖放时,我可以看到“Ctrl+C”加速器被触发(因为 ActionEvent 打印在控制台中),就像在键盘上按 Ctrl+C 一样。
我认为这是非常奇怪的行为,我无法弄清楚为什么鼠标操作会触发该热键。这是一个错误吗?
public class Test {
public static void main(String[] args) {
final JFrame jf = new JFrame("Test");
final JMenuBar menuBar = new JMenuBar();
jf.setJMenuBar(menuBar);
final JMenu menu = new JMenu("Edit");
menuBar.add(menu);
final JMenuItem copyItem = new JMenuItem("Copy");
copyItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(e);
}
});
copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK));
menu.add(copyItem);
jf.setPreferredSize(new Dimension(400, 300));
jf.pack();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}
I create a JFrame and place a JMenuBar into it, a "Copy" menu item with "Ctrl+C" accelerator is added. The complete source code are pasted below. When I do drag and drop within the JFrame, I can see the "Ctrl+C" accelerator is triggered (since ActionEvent is printed in console), which just like you press Ctrl+C on keyboard.
I think it is quite strange behavior and I could not figure out why the mouse manipulation will trigger that hotkey. Is it a bug?
public class Test {
public static void main(String[] args) {
final JFrame jf = new JFrame("Test");
final JMenuBar menuBar = new JMenuBar();
jf.setJMenuBar(menuBar);
final JMenu menu = new JMenu("Edit");
menuBar.add(menu);
final JMenuItem copyItem = new JMenuItem("Copy");
copyItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(e);
}
});
copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK));
menu.add(copyItem);
jf.setPreferredSize(new Dimension(400, 300));
jf.pack();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
几天前我也遇到了类似的问题。但我已经解决了这个问题,更改了
KeyEvent.CTRL_DOWN_MASK
的Event.CTRL_MASK
参数。我的最终代码如下:我不知道这是否是一个众所周知的错误,但我的选项在我的情况下没有任何问题。
祝你好运!
Some days ago I had a similar problem. But I've resolved it changing the
Event.CTRL_MASK
parameter forKeyEvent.CTRL_DOWN_MASK
. My final code was the following:I don't know if this is a well-known bug, but my option works in my case without any problem.
Good luck with it!