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 three states, through which it cycles
11 * Instead of calling isChecked, need to use getCurrentState which will
14 public class TripleStateCheckBox extends JCheckBox implements ItemListener
16 /** Array of icons to be used */
17 private ImageIcon[] _icons = new ImageIcon[3];
18 /** Current state 0, 1 or 2 */
19 private int _currState = 0;
21 /** Inner class to proxy the listening events */
22 private class ProxyListener implements ItemListener
24 /** Listener onto which some of the events will be passed */
25 private ItemListener _listener = null;
27 ProxyListener(ItemListener inListener) {_listener = inListener;}
28 /** React to events, and only pass on the selected ones */
29 public void itemStateChanged(ItemEvent arg0) {
30 if (arg0.getStateChange() == ItemEvent.SELECTED) {
31 _listener.itemStateChanged(arg0);
37 public TripleStateCheckBox()
39 addItemListener(this);
42 /** Set the current state */
43 public void setCurrentState(int inState)
45 _currState = inState % 3;
46 setIcon(_icons[_currState]);
48 setSelectedIcon(_icons[(_currState+1)%3]);
51 /** @return current state 0, 1 or 2 */
52 public int getCurrentState()
58 * Set the icon to use for the given index
59 * @param inIndex index 0, 1 or 2
60 * @param inIcon icon to use for that state
62 public void setIcon(int inIndex, ImageIcon inIcon)
64 _icons[inIndex % 3] = inIcon;
68 /** Intercept listener adding by putting a proxy inbetween */
69 public void addItemListener(ItemListener inListener) {
70 super.addItemListener(new ProxyListener(inListener));
73 /** React to a selection event by advancing the state */
74 public void itemStateChanged(ItemEvent inEvent)
76 setCurrentState(_currState + 1);