【问题标题】:How can I set accelerator shortcuts on CheckBoxMenuItems in Java?如何在 Java 中的 CheckBoxMenuItems 上设置加速器快捷方式?
【发布时间】:2012-12-10 10:45:12
【问题描述】:

我正在用 Java 编写一个简单的绘图程序,我有一个 MenuBar(不是 JMenuBar)来选择要绘制的形状和颜色。我想设置键盘快捷键以在 Rectangle、Oval 和 Line 之间进行选择。我知道我可以将 MenuShortcut 用于 MenuItems,但这不适用于 CheckBoxMenuItems。任何线索我可以如何做到这一点?

【问题讨论】:

  • “Java 中的一个简单绘图程序” 使用 AWT 做这件事并不“简单”,原因有二。 1) AWT 的功能比 Swing 少(您必须更频繁地“自己动手”) 2) 使用 AWT 的少数人已经基本忘记了它。 -- 你的教授现在需要 AWT 组件, 是一个非常(非常)的坏信号。

标签: java checkbox keyboard-shortcuts awt menuitem


【解决方案1】:

也许这需要JRadioButtonMenuItem,因为用户将一次绘制其中一个元素(例如,什么是椭圆形线?)。

JRadioButtonMenuItem 有一个加速器。例如

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);
    }
}

【讨论】:

  • 它基本上是一个单选按钮(使用 if 语句禁用其他按钮),但我使用的是常规 MenuBar 而不是 JMenuBar。我正在编写的程序只是我为期末考试而学习的方式,我的教授不让我们使用 JMenuBar
  • “我的教授不让我们使用 JMenuBar” 你的教授需要把自己(踢和尖叫)拖到第三个千年,直到那个时候,他们不应该教别人。
  • 是的,我完全同意,一旦课程结束,我将使用 Swing 而不是 AWT 回顾所有项目,但直到决赛结束,我必须做他想要什么
  • +1 表示 Swing,但我很惊讶从 MenuItem 继承的 setShortcut() 不起作用。
猜你喜欢
  • 2012-05-28
  • 2011-02-18
  • 2019-09-04
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-08
  • 2023-03-13
相关资源
最近更新 更多