]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/gui/TripleStateCheckBox.java
Version 18.6, December 2016
[GpsPrune.git] / tim / prune / gui / TripleStateCheckBox.java
1 package tim.prune.gui;
2
3 import java.awt.event.ItemEvent;
4 import java.awt.event.ItemListener;
5
6 import javax.swing.ImageIcon;
7 import javax.swing.JCheckBox;
8
9 /**
10  * Class to represent a checkbox with three states, through which it cycles
11  * Instead of calling isChecked, need to use getCurrentState which will
12  * return 0, 1 or 2
13  */
14 public class TripleStateCheckBox extends JCheckBox implements ItemListener
15 {
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;
20
21         /** Inner class to proxy the listening events */
22         private class ProxyListener implements ItemListener
23         {
24                 /** Listener onto which some of the events will be passed */
25                 private ItemListener _listener = null;
26                 /** Constructor */
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);
32                         }
33                 }
34         }
35
36         /** Constructor */
37         public TripleStateCheckBox()
38         {
39                 addItemListener(this);
40         }
41
42         /** Set the current state */
43         public void setCurrentState(int inState)
44         {
45                 _currState = inState % 3;
46                 setIcon(_icons[_currState]);
47                 setSelected(false);
48                 setSelectedIcon(_icons[(_currState+1)%3]);
49         }
50
51         /** @return current state 0, 1 or 2 */
52         public int getCurrentState()
53         {
54                 return _currState;
55         }
56
57         /**
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
61          */
62         public void setIcon(int inIndex, ImageIcon inIcon)
63         {
64                 _icons[inIndex % 3] = inIcon;
65         }
66
67         @Override
68         /** Intercept listener adding by putting a proxy inbetween */
69         public void addItemListener(ItemListener inListener) {
70                 super.addItemListener(new ProxyListener(inListener));
71         }
72
73         /** React to a selection event by advancing the state */
74         public void itemStateChanged(ItemEvent inEvent)
75         {
76                 setCurrentState(_currState + 1);
77         }
78 }