3 import java.awt.event.ItemEvent;
4 import java.awt.event.ItemListener;
6 import javax.swing.ImageIcon;
7 import javax.swing.JCheckBox;
10 * Class to represent a checkbox with multiple states, through which it cycles.
11 * Instead of calling isChecked, callers need to use getCurrentState which will
12 * return 0 up to (n-1) for n states.
14 public class MultiStateCheckBox extends JCheckBox implements ItemListener
16 /** Array of icons to be used */
17 private ImageIcon[] _icons = null;
18 /** Current state 0 to n-1 */
19 private int _currState = 0;
20 /** Number of states n */
21 private final int _numStates;
24 /** Inner class to proxy the listening events */
25 private class ProxyListener implements ItemListener
27 /** Listener onto which some of the events will be passed */
28 private ItemListener _listener = null;
30 ProxyListener(ItemListener inListener) {_listener = inListener;}
31 /** React to events, and only pass on the selected ones */
32 public void itemStateChanged(ItemEvent arg0) {
33 if (arg0.getStateChange() == ItemEvent.SELECTED) {
34 _listener.itemStateChanged(arg0);
41 * @param inNumStates number of states to cycle through
43 public MultiStateCheckBox(int inNumStates)
45 _numStates = (inNumStates > 0) ? inNumStates : 1;
46 _icons = new ImageIcon[_numStates];
47 addItemListener(this);
51 * @param inState state to set
53 public void setCurrentState(int inState)
55 _currState = inState % _numStates;
56 setIcon(_icons[_currState]);
58 setSelectedIcon(_icons[(_currState+1) % _numStates]);
62 * @return current state 0 to n-1
64 public int getCurrentState()
70 * Set the icon to use for the given index
71 * @param inIndex index 0 to n-1
72 * @param inIcon icon to use for that state
74 public void setIcon(int inIndex, ImageIcon inIcon)
76 _icons[inIndex % _numStates] = inIcon;
80 /** Intercept listener adding by putting a proxy inbetween */
81 public void addItemListener(ItemListener inListener) {
82 super.addItemListener(new ProxyListener(inListener));
85 /** React to a selection event by advancing the state */
86 public void itemStateChanged(ItemEvent inEvent)
88 setCurrentState(_currState + 1);