How can I set accelerator shortcuts on CheckBoxMenuItems in Java?
我正在用Java编写一个简单的绘图程序,我有一个MenuBar(不是JMenuBar)来选择要绘制的形状和颜色。 我想设置键盘快捷键以在Rectangle,Oval和Line之间进行选择。 我知道我可以将MenuShortcut用于MenuItems,但这对CheckBoxMenuItems不起作用。 任何线索我怎么能做到这一点?
也许这需要一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 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); } } |