简体   繁体   English

有没有办法在Java中进行分组复选框?

[英]Is there a way to do grouped checkboxes in Java?

For example, selecting the parent checkbox will select all the child checkboxes (and vice versa if you unselect the parent checkbox). 例如,选择父复选框将选中所有子复选框(反之亦然,如果取消选择父复选框)。

If you unselect a child checkbox, the check mark in the parent checkbox will turn into a box. 如果取消选择子复选框,则父复选框中的复选标记将变为一个框。

If you unselect all the child checkboxes, the parent checkbox will unselect as well. 如果取消选中所有子复选框,则父复选框也将取消选中。

For example, something like this, but in Java. 例如,类似的东西,但是使用Java。 在此处输入图片说明

This is not a true grouping of JCheckBox components, but it simulates a grouping and should outwardly display the behavior you've described. 这不是对JCheckBox组件的真正分组,但是它模拟了分组,并且应该向外显示您描述的行为。 You could always implement your own grouped checkbox class, but I suspect my approach is more efficient. 您总是可以实现自己的分组复选框类,但是我怀疑我的方法更有效。

// UI element declarations

JCheckBox cbAsia = new JCheckBox("Asia");
cbAsia.addItemListener(this);

JCheckBox cbChina = new JCheckBox("China");

JCheckBox cbIndia = new JCheckBox("India");

JCheckBox cbJapan = new JCheckBox("Japan");

JCheckBox cbPakistan = new JCheckBox("Pakistan");

JCheckBox cbThailand = new JCheckBox("Thailand");

JCheckBox cbVietnam = new JCheckBox("Vietnam");

// Item state handling loop

public void itemStateChanged(ItemEvent e)
{
    Object source = e.getItemSelectable();

    if (source == cbAsia)
    {
        if(e.getStateChange() == ItemEvent.SELECTED)
        {
            cbChina.setSelected(true);
            cbIndia.setSelected(true);
            cbJapan.setSelected(true);
            cbPakistan.setSelected(true);
            cbThailand.setSelected(true);
            cbVietnam.setSelected(true);
        }
        else
            cbChina.setSelected(false);
            cbIndia.setSelected(false);
            cbJapan.setSelected(false);
            cbPakistan.setSelected(false);
            cbThailand.setSelected(false);
            cbVietnam.setSelected(false);
        }
    }
}

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

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