View Javadoc

1   /*
2    *  XNap - A P2P framework and client.
3    *
4    *  See the file AUTHORS for copyright information.
5    *
6    *  This program is free software; you can redistribute it and/or modify
7    *  it under the terms of the GNU General Public License as published by
8    *  the Free Software Foundation.
9    *
10   *  This program is distributed in the hope that it will be useful,
11   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   *  GNU General Public License for more details.
14   *
15   *  You should have received a copy of the GNU General Public License
16   *  along with this program; if not, write to the Free Software
17   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
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      //--- Constant(s) ---
40      
41      //--- Data field(s) ---
42  
43      private PreferencesProvider prefs;
44      private String prefsKey;
45  
46      //--- Constructor(s) ---
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  		// initialize
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      //--- Method(s) ---
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  }