View Javadoc

1   /*
2    *  XNap Commons
3    *
4    *  Copyright (C) 2005  Steffen Pingel
5    *
6    *  This library is free software; you can redistribute it and/or
7    *  modify it under the terms of the GNU Lesser General Public
8    *  License as published by the Free Software Foundation; either
9    *  version 2.1 of the License, or (at your option) any later version.
10   *
11   *  This library is distributed in the hope that it will be useful,
12   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   *  Lesser General Public License for more details.
15   *
16   *  You should have received a copy of the GNU Lesser General Public
17   *  License along with this library; if not, write to the Free Software
18   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19   */
20  package org.xnap.commons.gui.action;
21  
22  import java.awt.event.ActionEvent;
23  import javax.swing.AbstractButton;
24  
25  /***
26   * Provides a default implementation for toggeable <code>Action</code> objects.
27   */
28  public abstract class AbstractToggleAction extends AbstractXNapAction 
29      implements ToggleAction {
30      
31      public AbstractToggleAction(boolean selected)
32      {
33  		putValue(ToggleAction.SELECTED, new Boolean(selected));
34      }
35  
36      /***
37       * Constructor an AbstractToggleAction that is not selected by default.
38       */
39      public AbstractToggleAction()
40      {
41  		this(false);
42      }
43  
44      /***
45       * Returns the state of the action.
46       * 
47       * @return true, if the action is currently in active state, e.g. selected 
48       * in case of a {@link javax.swing.JToggleButton}
49       */
50      public boolean isSelected()
51      {
52  		return ((Boolean)getValue(ToggleAction.SELECTED)).booleanValue();
53      }
54  
55      public void actionPerformed(ActionEvent event) 
56      {
57  		if (event.getSource() instanceof AbstractButton) {
58  			AbstractButton ab = (AbstractButton)event.getSource();
59  			setSelected(ab.isSelected());
60  		}
61      }
62  
63      /***
64       * Invoked when the selection changes.
65       */
66      public abstract void toggled(boolean selected);
67          
68      /***
69       * Sets the state of the action.
70       * 
71       * @param newValue if true, the action is set to active state
72       */
73      public void setSelected(boolean newValue)
74      {
75  		if (newValue != isSelected()) {
76  			putValue(ToggleAction.SELECTED, new Boolean(newValue));
77  			toggled(newValue);
78  		}
79      }
80      
81  }