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 javax.swing.*;
18 import java.awt.CheckboxMenuItem;
19 import java.awt.event.ItemEvent;
20 import java.awt.event.ItemListener;
21 import java.awt.event.ActionListener;
22 import java.awt.event.ActionEvent;
23 import java.util.ArrayList;
24 import java.util.List;
25
26 /**
27 * Object of this class represents a checkbox menu item
28 * group to provide radio-buton-like functionality for awt
29 * <code>CheckboxMenuItem</code>.
30 * <p/>
31 * Created date: Jan 23, 2008
32 *
33 * @author Yevgeny Nyden
34 */
35 public class AwtCheckboxMenuGroup {
36
37 /** List of checkbox items included in this group. */
38 private List<CheckboxMenuItem> menuItems;
39
40 /** Default constructor. */
41 public AwtCheckboxMenuGroup() {
42 this.menuItems = new ArrayList<CheckboxMenuItem>();
43 }
44
45 /**
46 * Adds a given checkbox menu item to the current group.
47 *
48 * @param item Item to add to the current group.
49 */
50 public void addItemToGroup(CheckboxMenuItem item) {
51 this.menuItems.add(item);
52 GroupItemListener itemListener = new GroupItemListener(this.menuItems.size() - 1);
53 item.addItemListener(itemListener);
54 item.addActionListener(itemListener);
55 }
56
57 /** Listener for the group's checkbox items. */
58 private class GroupItemListener implements ItemListener, ActionListener {
59
60 /** Index of the current item on the group's list. */
61 private int index;
62
63 /**
64 * Constructor that sets the index of the current item.
65 *
66 * @param index Index to set.
67 */
68 public GroupItemListener(int index) {
69 this.index = index;
70 }
71
72 /** {@inheritDoc} */
73 public void itemStateChanged(ItemEvent itemEvent) {
74 if (itemEvent.getStateChange() == ItemEvent.DESELECTED) {
75 menuItems.get(index).setState(true);
76 }
77 unselectItemsHelper();
78 }
79
80 /** {@inheritDoc} */
81 public void actionPerformed(ActionEvent event) {
82 unselectItemsHelper();
83 SwingUtilities.invokeLater(new Runnable() {
84 public void run() {
85 menuItems.get(index).setState(true);
86 }
87 });
88 }
89
90 /** Does all the work for unselecting items other than the current one. */
91 private void unselectItemsHelper() {
92 for (int i = 0; i < menuItems.size(); ++i) {
93 if (i != index) {
94 menuItems.get(i).setState(false);
95 }
96 }
97 }
98 }
99
100 }
101