On OSX Java 7 (1.7.0_40) I wanted to add some mutually exclusive CheckBoxItems to the dock menu, in order to create the mutual exclusivity I used the answer here by http://stackoverflow.com/questions/13596428/adding-a-checkbox-group-to-a-java-menu/20092694#20092694 provided by Julian Wright to create the equivalent of ButtonGroup available for JCheckBoxMenuItems

But I ran into a problem, the object returned by ItemEvent is of type String rather than CheckBoxMenuItem, I worked round it with the code below but this is an OSX bug isnt it ?

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

Reply via email to