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 AbstractToggleReversedPrefAction 
36  	extends AbstractToggleAction 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 AbstractToggleReversedPrefAction
54  		(PreferencesProvider prefs, String prefsKey)
55      {
56  		this.prefs = prefs;
57  		this.prefsKey = prefsKey;
58  
59  		prefs.addPropertyChangeListener(prefsKey, this);
60  
61  		// initialize
62  		boolean value = !prefs.getBoolean(prefsKey);
63  		setSelected(value);
64  		toggled(value);
65      }
66  
67      public AbstractToggleReversedPrefAction(String prefsKey)
68      {
69  		this(Preferences.getInstance(), prefsKey);
70      }
71  
72      //--- Method(s) ---
73  
74      public void actionPerformed(ActionEvent event) 
75      {
76  		if (event.getSource() instanceof AbstractButton) {
77  			AbstractButton ab = (AbstractButton)event.getSource();
78  			prefs.set(prefsKey, !ab.isSelected());
79  		}
80      }
81  
82      public void propertyChange(PropertyChangeEvent e) 
83      {
84  		setSelected(!prefs.getBoolean(prefsKey));
85      }
86  
87  }