RotaryButton.java
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13: package xeij;
14:
15: import java.awt.event.*;
16: import java.util.*;
17: import javax.swing.*;
18:
19:
20:
21:
22: @SuppressWarnings ("this-escape")
23: public class RotaryButton extends JButton implements ActionListener {
24:
25: protected int index;
26: protected String[] texts;
27: protected Icon[] icons;
28: protected ArrayList<ActionListener> listeners;
29:
30:
31:
32:
33: public RotaryButton (int index, String... texts) {
34: super (texts[index]);
35: this.texts = texts;
36: this.index = index;
37: listeners = new ArrayList<ActionListener> ();
38: super.addActionListener (this);
39: }
40:
41:
42:
43: public RotaryButton (int index, Icon... icons) {
44: super (icons[index]);
45: this.icons = icons;
46: this.index = index;
47: listeners = new ArrayList<ActionListener> ();
48: super.addActionListener (this);
49: }
50:
51:
52:
53:
54: public int getIndex () {
55: return index;
56: }
57:
58:
59:
60:
61: public void setIndex (int index) {
62: if (this.index != index) {
63: this.index = index;
64: if (texts != null) {
65: setText (texts[index]);
66: } else if (icons != null) {
67: setIcon (icons[index]);
68: }
69: }
70: }
71:
72:
73:
74:
75: @Override public void actionPerformed (ActionEvent ae) {
76: if (texts != null) {
77: index = index + 1 < texts.length ? index + 1 : 0;
78: setText (texts[index]);
79: } else if (icons != null) {
80: index = index + 1 < icons.length ? index + 1 : 0;
81: setIcon (icons[index]);
82: }
83: for (ActionListener listener : listeners) {
84: listener.actionPerformed (ae);
85: }
86: }
87:
88:
89:
90: @Override public void addActionListener (ActionListener listener) {
91: if (listener != null) {
92: listeners.add (listener);
93: }
94: }
95:
96:
97:
98: @Override public ActionListener[] getActionListeners () {
99: return listeners.toArray (new ActionListener[listeners.size ()]);
100: }
101:
102:
103:
104: @Override public void removeActionListener (ActionListener listener) {
105: listeners.remove (listener);
106: }
107:
108: }