将复选框组添加到 Java 菜单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13596428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:21:01  来源:igfitidea点击:

Adding a checkbox group to a java menu

javacheckboxawtjmenu

提问by user1515742

Im trying to add a checkboxgroup to my menu but keep getting a "Cannot find symbol" error.

我试图在我的菜单中添加一个复选框组,但不断收到“找不到符号”错误。

    MenuBar mb = new MenuBar();
    Menu file = new Menu("File");
    Menu colorM = new Menu("Color");
    MenuItem quitM = new MenuItem("Quit", new MenuShortcut(KeyEvent.VK_Q));
    CheckboxGroup cbg = new CheckboxGroup();
    Checkbox cb1 = new Checkbox("Black",cbg,true);
    Checkbox cb2 = new Checkbox("Red",cbg,false);
    Checkbox cb3 = new Checkbox("Blue",cbg,false);
    Checkbox cb4 = new Checkbox("Green",cbg,false);

Then in my initialization i have

然后在我的初始化我有

    chatF.setMenuBar(mb);
    mb.add(file);
    mb.add(colorM);
    file.add(quitM);
    colorM.add(cbg);

I tried adding a MenuItem and putting the cbg in there but same problem

我尝试添加一个 MenuItem 并将 cbg 放在那里但同样的问题

回答by Julian Wright

You can't add a CheckboxGroupto a Menu... you can only add MenuIteminstances. You can add a CheckboxMenuItem, but this doesn't understand CheckboxGroupeither.

您不能将 a 添加CheckboxGroup到菜单...您只能添加MenuItem实例。您可以添加一个CheckboxMenuItem,但这也不明白CheckboxGroup

So you need to change the CheckBoxs to CheckboxMenuItems, add them individually to the menu, roll your own CheckboxMenuItemGroupclass and use it to bind the CheckboxMenuItems together.

因此,您需要将CheckBoxs更改为CheckboxMenuItems,将它们单独添加到菜单中,滚动您自己的CheckboxMenuItemGroup类并使用它来将CheckboxMenuItems绑定在一起。

Something like the following should work:

类似以下的内容应该可以工作:

public class CheckboxMenuItemGroup implements ItemListener {

    private Set<CheckboxMenuItem>   items = new HashSet<CheckboxMenuItem>();

    public void add(CheckboxMenuItem cbmi) {
        cbmi.addItemListener(this);
        cbmi.setState(false);
        items.add(cbmi);
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            String itemAffected = (String) e.getItem();
            for (CheckboxMenuItem item : items) {
                // Use this line to allow user to toggle the selected item off
                if (!item.getLabel().equals(itemAffected)) item.setState(false);
                // Use this line to force one of the items to always be selected
                // item.setState(item.getLabel().equals(itemAffected));
            }
        }
    }

    public void selectItem(CheckboxMenuItem itemToSelect) {
        for (CheckboxMenuItem item : items) {
            item.setState(item == itemToSelect);
        }
    }

    public CheckboxMenuItem getSelectedItem() {
        for (CheckboxMenuItem item : items) {
            if (item.getState()) return item;
        }
        return null;
    }
}

This should work because ItemListeners don't get called when code calls item.setState(), only when the user clicks on the item in the menu. Just make sure you only set the state of the items with the CheckboxMenuItemGroup.selectItem()call, otherwise you could end up with more than one item selected.

这应该有效,因为ItemListeners 不会在代码调用item.setState()时被调用,只有当用户单击菜单中的项目时才会调用。只要确保您只在CheckboxMenuItemGroup.selectItem()调用时设置项目的状态,否则您最终可能会选择多个项目。

Then you just need to build your menu like this:

然后你只需要像这样构建你的菜单:

public static void main(String[] args) {

    final Frame f = new Frame("Test CheckboxMenuItemGroup");
    MenuBar mb = new MenuBar();
    Menu menu = new Menu("Menu");
    CheckboxMenuItem cb1 = new CheckboxMenuItem("Black");
    CheckboxMenuItem cb2 = new CheckboxMenuItem("Red");
    CheckboxMenuItem cb3 = new CheckboxMenuItem("Blue");
    CheckboxMenuItem cb4 = new CheckboxMenuItem("Green");

    CheckboxMenuItemGroup mig = new CheckboxMenuItemGroup();
    mig.add(cb1);
    mig.add(cb2);
    mig.add(cb3);
    mig.add(cb4);
    mig.selectItem(cb1);

    menu.add(cb1);
    menu.add(cb2);
    menu.add(cb3);
    menu.add(cb4);

    f.setMenuBar(mb);

    f.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
    f.setSize(300, 200);
    f.setVisible(true);
}

回答by rob

CheckboxGroupis not a Component(or, more specifically, a MenuItem), so you can't add it to the menu. Instead, you can create a CheckboxMenuItem, but I think CheckboxGrouponly works with instances of Checkboxso you'll have to write your own code to enforce single-selection.

CheckboxGroup不是 a Component(或更具体地说, a MenuItem),因此您无法将其添加到菜单中。相反,您可以创建一个CheckboxMenuItem,但我认为CheckboxGroup仅适用于 的实例,Checkbox因此您必须编写自己的代码来强制执行单选。

If Swing is an option, you can instead use JRadioButtonMenuItemand ButtonGroup:

如果 Swing 是一个选项,您可以改为使用JRadioButtonMenuItemand ButtonGroup

package com.example.checkboxmenu;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;

public class CheckboxMenu extends JFrame {

    public CheckboxMenu() {
        JMenuBar mb = new JMenuBar();
        JMenu file = new JMenu("File"); //$NON-NLS-1$
        JMenu colorM = new JMenu("Color");
        JMenuItem quitM = new JMenuItem("Quit", KeyEvent.VK_Q);

        JRadioButtonMenuItem cb1 = new JRadioButtonMenuItem("Black", true);
        JRadioButtonMenuItem cb2 = new JRadioButtonMenuItem("Red", true);
        JRadioButtonMenuItem cb3 = new JRadioButtonMenuItem("Blue", true);
        JRadioButtonMenuItem cb4 = new JRadioButtonMenuItem("Green", true);

        ButtonGroup group = new ButtonGroup();
        group.add(cb1);
        group.add(cb2);
        group.add(cb3);
        group.add(cb4);

        setJMenuBar(mb);
        mb.add(file);
        mb.add(colorM);
        file.add(quitM);
        colorM.add(cb1);
        colorM.add(cb2);
        colorM.add(cb3);
        colorM.add(cb4);

        quitM.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400,300);
        setVisible(true);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        new CheckboxMenu();
    }

}

回答by hayden

Using swing instead of awt.

使用 Swing 而不是 awt。

JMenuBar menuBar = new JMenuBar();
JMenu color = new JMenu("Color");

JCheckBoxMenuItem cb1 = new JCheckBoxMenuItem("Black");
JCheckBoxMenuItem cb2 = new JCheckBoxMenuItem("Red");
JCheckBoxMenuItem cb3 = new JCheckBoxMenuItem("Blue");
JCheckBoxMenuItem cb4 = new JCheckBoxMenuItem("Green");

ButtonGroup group = new ButtonGroup();
group.add(cb1);
group.add(cb2);
group.add(cb3);
group.add(cb4);

menuBar.add(cb1);
menuBar.add(cb2);
menuBar.add(cb3);
menuBar.add(cb4);

setJMenuBar(menuBar); // Set the JMenuBar of the JFrame

You can add any AbstractButtonto a ButtonGroup.

您可以将任何AbstractButton添加到ButtonGroup

回答by Paul Taylor

On OSX Java 7 (1.7.0_40) Julians answer doesnt quite work because the object returned by ItemEvent is actually a String rather than a CheckBoxItem, soiunds like a bug in OSX but got it working by modifying the itemStateChanged method

在 OSX Java 7 (1.7.0_40) Julians 的回答不太有效,因为 ItemEvent 返回的对象实际上是 String 而不是 CheckBoxItem,听起来像 OSX 中的错误,但通过修改 itemStateChanged 方法使其工作

import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.HashSet;
import java.util.Set;

public class CheckboxMenuItemGroup implements ItemListener
{

    private Set<CheckboxMenuItem> items = new HashSet<CheckboxMenuItem>();

    public void add(CheckboxMenuItem cbmi) {
        cbmi.addItemListener(this);
        cbmi.setState(false);
        items.add(cbmi);
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {

            String itemAffected = (String)e.getItem();
            for (CheckboxMenuItem item : items) {
                if (item.getLabel() != itemAffected) item.setState(false);
            }
        }
    }

    public void selectItem(CheckboxMenuItem itemToSelect) {
        for (CheckboxMenuItem item : items) {
            item.setState(item == itemToSelect);
        }
    }

    public CheckboxMenuItem getSelectedItem() {
        for (CheckboxMenuItem item : items) {
            if (item.getState()) return item;
        }
        return null;
    }
}