简体   繁体   English

如何在Java中的CheckBoxMenuItems上设置加速器快捷方式?

[英]How can I set accelerator shortcuts on CheckBoxMenuItems in Java?

I'm writing a simple drawing program in Java, and I've got a MenuBar (not a JMenuBar) to select the shapes and colors to be drawn. 我正在用Java写一个简单的绘图程序,并且有一个MenuBar(不是JMenuBar)来选择要绘制的形状和颜色。 I want to set keyboard shortcuts to select between Rectangle, Oval, and Line. 我想设置键盘快捷键以在“矩形”,“椭圆”和“线”之间进行选择。 I know I can use MenuShortcut for MenuItems, but this doesn't work for CheckBoxMenuItems. 我知道我可以将MenuShortcut用于MenuItems,但这不适用于CheckBoxMenuItems。 Any clue how I can accomplish this? 任何线索,我怎么能做到这一点?

Maybe this needs a JRadioButtonMenuItem given the user will be drawing one of the elements at a time (eg what is an Oval-Line?). 假设用户一次要绘制其中一个元素,则可能需要一个JRadioButtonMenuItem (例如,什么是椭圆线?)。

JRadioButtonMenuItem has an accelerator. JRadioButtonMenuItem具有加速器。 EG 例如

单选菜单演示

import javax.swing.*;

public class RadioMenuDemo {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                JPanel gui = new JPanel();

                JMenuBar mb = new JMenuBar();
                JMenu shapes = new JMenu("Draw");
                mb.add(shapes);
                ButtonGroup bg = new ButtonGroup();
                shapes.setMnemonic('D');

                JRadioButtonMenuItem line = new JRadioButtonMenuItem("Line");
                line.setAccelerator(KeyStroke.getKeyStroke("L"));
                shapes.add(line);
                bg.add(line);

                JRadioButtonMenuItem oval = new JRadioButtonMenuItem("Oval");
                oval.setAccelerator(KeyStroke.getKeyStroke("O"));
                shapes.add(oval);
                bg.add(oval);

                JRadioButtonMenuItem rect = new JRadioButtonMenuItem("Rectangle");
                rect.setAccelerator(KeyStroke.getKeyStroke("R"));
                shapes.add(rect);
                bg.add(rect);

                JFrame f = new JFrame("Radio menu items");
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setJMenuBar(mb);
                f.pack();
                f.setLocationByPlatform(true);
                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

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

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