1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.action;
21
22 import java.awt.event.ActionEvent;
23 import java.beans.PropertyChangeEvent;
24 import java.beans.PropertyChangeListener;
25
26 import javax.swing.AbstractButton;
27
28 import org.xnap.util.Preferences;
29 import org.xnap.util.PreferencesProvider;
30
31 /***
32 * Provides a default implementation for a toggle action that monitors
33 * a boolean preference key.
34 */
35 public abstract class AbstractTogglePrefAction extends AbstractToggleAction
36 implements PropertyChangeListener
37 {
38
39
40
41
42
43 private PreferencesProvider prefs;
44 private String prefsKey;
45
46
47
48 /***
49 * Constructs a toggle action that monitors a boolean preference key.
50 *
51 * @param prefsKey the key to monitor
52 */
53 public AbstractTogglePrefAction(PreferencesProvider prefs, String prefsKey)
54 {
55 this.prefs = prefs;
56 this.prefsKey = prefsKey;
57
58 prefs.addPropertyChangeListener(prefsKey, this);
59
60
61 boolean value = prefs.getBoolean(prefsKey);
62 setSelected(value);
63 toggled(value);
64 }
65
66 public AbstractTogglePrefAction(String prefsKey)
67 {
68 this(Preferences.getInstance(), prefsKey);
69 }
70
71
72
73 public void actionPerformed(ActionEvent event)
74 {
75 if (event.getSource() instanceof AbstractButton) {
76 AbstractButton ab = (AbstractButton)event.getSource();
77 prefs.set(prefsKey, ab.isSelected());
78 }
79 }
80
81 public void propertyChange(PropertyChangeEvent e)
82 {
83 boolean newValue = prefs.getBoolean(prefsKey);
84 setSelected(newValue);
85 }
86
87 }