View Javadoc

1   /**
2    * This program is free software: you can redistribute it and/or modify
3    * it under the terms of the GNU General Public License as published by
4    * the Free Software Foundation, version 3.
5    *
6    * This program is distributed in the hope that it will be useful,
7    * but WITHOUT ANY WARRANTY; without even the implied warranty of
8    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9    * GNU General Public License for more details.
10   *
11   * You should have received a copy of the GNU General Public License
12   * along with this program. If not, see <http://www.gnu.org/licenses/>.
13   */
14  
15  package net.curre.prefcount.gui.menu;
16  
17  import java.awt.*;
18  import java.awt.event.ItemEvent;
19  import java.awt.event.ItemListener;
20  import java.util.ArrayList;
21  import java.util.List;
22  
23  /**
24   * Object of this class represents a checkbox menu item
25   * group to provide radio-buton-like functionality for awt
26   * <code>CheckboxMenuItem</code>.
27   * <p/>
28   * Created date: Jan 23, 2008
29   *
30   * @author Yevgeny Nyden
31   */
32  public class AwtCheckboxMenuGroup {
33  
34    /** List of checkbox items included in this group. */
35    private List<CheckboxMenuItem> menuItems;
36  
37    /** Listener for the group's checkbox items. */
38    private class GroupItemListener implements ItemListener {
39  
40      /** Index of the current item on the group's list. */
41      private int index;
42  
43      /**
44       * Constructor that sets the index of the current item.
45       *
46       * @param index Index to set.
47       */
48      public GroupItemListener(int index) {
49        this.index = index;
50      }
51  
52      /**
53       * Changes state of other items to the opposite state of
54       * what the current item is in.
55       * <p/>
56       * {@inheritDoc}
57       */
58      public void itemStateChanged(ItemEvent itemEvent) {
59        if (itemEvent.getStateChange() == ItemEvent.DESELECTED) {
60          menuItems.get(index).setState(true);
61        }
62        for (int i = 0; i < menuItems.size(); ++i) {
63          if (i != index) {
64            menuItems.get(i).setState(false);
65          }
66        }
67      }
68    }
69  
70    /** Default constructor. */
71    public AwtCheckboxMenuGroup() {
72      menuItems = new ArrayList<CheckboxMenuItem>();
73    }
74  
75    /**
76     * Adds a given checkbox menu item to the current group.
77     *
78     * @param item Item to add to the current group.
79     */
80    public void addItemToGroup(CheckboxMenuItem item) {
81      menuItems.add(item);
82      item.addItemListener(new GroupItemListener(menuItems.size() - 1));
83    }
84  
85  }
86