简体   繁体   English

将加速器描述添加到GUI中的JMenuItem,而无需实际添加加速器

[英]Add accelerator description to JMenuItem in GUI, without actually adding an accelerator

I'm trying to set some text to be displayed where the accelerator binding is usually displayed, for a JMenuItem . 我正在尝试为JMenuItem设置一些通常在显示加速器绑定的地方显示的文本。 The demarcated Ctrl+Z text in the following image is an example of what I'm trying to set, for another JMenuItem . 下图中标出的Ctrl + Z文本是我要为另一个JMenuItem设置的示例。

accelerator text example

I don't actually want to set an accelerator for this JMenuItem , though. 实际上并不想为这个加速器JMenuItem ,虽然。 I've poked around the source for several classes, like JMenuItem and BasicMenuItemUI , to no avail. 我在几个类的源代码中四处BasicMenuItemUI ,如JMenuItemBasicMenuItemUI ,无济于事。 What's the simplest way to achieve this? 最简单的方法是什么?

Thanks in advance :) 提前致谢 :)

I assume the reason you want this is so you can prevent the menu from triggering the undo action a second time, when the key combination is already bound on a component on the frame, but this shouldn't be necessary. 我假设您想要这样做的原因是这样,当组合键已绑定到框架上的某个组件上时,您可以防止菜单再次触发撤消操作,但这不是必需的。 If the component consumes the key event, the menu won't detect it. 如果组件使用了键事件,则菜单将无法检测到它。

Here's an example with a JTextArea to see what I mean: 这是一个带有JTextArea的示例,以了解我的意思:

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

JMenuBar menu = new JMenuBar();
frame.setJMenuBar(menu);
JMenu menuEdit = new JMenu("Edit");
menu.add(menuEdit);
JMenuItem menuEditUndo = new JMenuItem("Undo");
menuEdit.add(menuEditUndo);
menuEditUndo.setAccelerator(KeyStroke.getKeyStroke("control Z"));
menuEditUndo.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("menu");
    }
});

JTextArea textArea = new JTextArea(20, 40);
textArea.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "undo");
textArea.getActionMap().put("undo", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("text");
    }
});
frame.add(new JScrollPane(textArea));

frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

Both the text area and the menu item have bound to the same key combo, but pressing Ctrl+Z while the text area has focus prints only "text" and never "menu". 文本区域和菜单项都已绑定到相同的组合键,但是当文本区域具有焦点时,按Ctrl + Z只会打印“文本”,而不会打印“菜单”。 Ie, the action does not happen twice. 即,该动作不会发生两次。 Although this uses a JTextArea, it should be true of any component. 尽管这使用了JTextArea,但任何组件都应为true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM