1 /*
   2  * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package javax.swing;
  26 
  27 import java.awt.*;
  28 import java.awt.event.*;
  29 
  30 import javax.swing.event.*;
  31 import javax.swing.plaf.*;
  32 import javax.accessibility.*;
  33 
  34 import java.io.ObjectOutputStream;
  35 import java.io.ObjectInputStream;
  36 import java.io.IOException;
  37 
  38 
  39 /**
  40  * An implementation of a two-state button.
  41  * The <code>JRadioButton</code> and <code>JCheckBox</code> classes
  42  * are subclasses of this class.
  43  * For information on using them see
  44  * <a
  45  href="http://docs.oracle.com/javase/tutorial/uiswing/components/button.html">How to Use Buttons, Check Boxes, and Radio Buttons</a>,
  46  * a section in <em>The Java Tutorial</em>.
  47  * <p>
  48  * Buttons can be configured, and to some degree controlled, by
  49  * <code><a href="Action.html">Action</a></code>s.  Using an
  50  * <code>Action</code> with a button has many benefits beyond directly
  51  * configuring a button.  Refer to <a href="Action.html#buttonActions">
  52  * Swing Components Supporting <code>Action</code></a> for more
  53  * details, and you can find more information in <a
  54  * href="http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html">How
  55  * to Use Actions</a>, a section in <em>The Java Tutorial</em>.
  56  * <p>
  57  * <strong>Warning:</strong> Swing is not thread safe. For more
  58  * information see <a
  59  * href="package-summary.html#threading">Swing's Threading
  60  * Policy</a>.
  61  * <p>
  62  * <strong>Warning:</strong>
  63  * Serialized objects of this class will not be compatible with
  64  * future Swing releases. The current serialization support is
  65  * appropriate for short term storage or RMI between applications running
  66  * the same version of Swing.  As of 1.4, support for long term storage
  67  * of all JavaBeans&trade;
  68  * has been added to the <code>java.beans</code> package.
  69  * Please see {@link java.beans.XMLEncoder}.
  70  *
  71  * @beaninfo
  72  *   attribute: isContainer false
  73  * description: An implementation of a two-state button.
  74  *
  75  * @see JRadioButton
  76  * @see JCheckBox
  77  * @author Jeff Dinkins
  78  */
  79 @SuppressWarnings("serial") // Same-version serialization only
  80 public class JToggleButton extends AbstractButton implements Accessible {
  81 
  82     /**
  83      * @see #getUIClassID
  84      * @see #readObject
  85      */
  86     private static final String uiClassID = "ToggleButtonUI";
  87 
  88     /**
  89      * Creates an initially unselected toggle button
  90      * without setting the text or image.
  91      */
  92     public JToggleButton () {
  93         this(null, null, false);
  94     }
  95 
  96     /**
  97      * Creates an initially unselected toggle button
  98      * with the specified image but no text.
  99      *
 100      * @param icon  the image that the button should display
 101      */
 102     public JToggleButton(Icon icon) {
 103         this(null, icon, false);
 104     }
 105 
 106     /**
 107      * Creates a toggle button with the specified image
 108      * and selection state, but no text.
 109      *
 110      * @param icon  the image that the button should display
 111      * @param selected  if true, the button is initially selected;
 112      *                  otherwise, the button is initially unselected
 113      */
 114     public JToggleButton(Icon icon, boolean selected) {
 115         this(null, icon, selected);
 116     }
 117 
 118     /**
 119      * Creates an unselected toggle button with the specified text.
 120      *
 121      * @param text  the string displayed on the toggle button
 122      */
 123     public JToggleButton (String text) {
 124         this(text, null, false);
 125     }
 126 
 127     /**
 128      * Creates a toggle button with the specified text
 129      * and selection state.
 130      *
 131      * @param text  the string displayed on the toggle button
 132      * @param selected  if true, the button is initially selected;
 133      *                  otherwise, the button is initially unselected
 134      */
 135     public JToggleButton (String text, boolean selected) {
 136         this(text, null, selected);
 137     }
 138 
 139     /**
 140      * Creates a toggle button where properties are taken from the
 141      * Action supplied.
 142      *
 143      * @since 1.3
 144      */
 145     public JToggleButton(Action a) {
 146         this();
 147         setAction(a);
 148     }
 149 
 150     /**
 151      * Creates a toggle button that has the specified text and image,
 152      * and that is initially unselected.
 153      *
 154      * @param text the string displayed on the button
 155      * @param icon  the image that the button should display
 156      */
 157     public JToggleButton(String text, Icon icon) {
 158         this(text, icon, false);
 159     }
 160 
 161     /**
 162      * Creates a toggle button with the specified text, image, and
 163      * selection state.
 164      *
 165      * @param text the text of the toggle button
 166      * @param icon  the image that the button should display
 167      * @param selected  if true, the button is initially selected;
 168      *                  otherwise, the button is initially unselected
 169      */
 170     public JToggleButton (String text, Icon icon, boolean selected) {
 171         // Create the model
 172         setModel(new ToggleButtonModel());
 173 
 174         model.setSelected(selected);
 175 
 176         // initialize
 177         init(text, icon);
 178     }
 179 
 180     /**
 181      * Resets the UI property to a value from the current look and feel.
 182      *
 183      * @see JComponent#updateUI
 184      */
 185     public void updateUI() {
 186         setUI((ButtonUI)UIManager.getUI(this));
 187     }
 188 
 189     /**
 190      * Returns a string that specifies the name of the l&amp;f class
 191      * that renders this component.
 192      *
 193      * @return String "ToggleButtonUI"
 194      * @see JComponent#getUIClassID
 195      * @see UIDefaults#getUI
 196      * @beaninfo
 197      *  description: A string that specifies the name of the L&amp;F class
 198      */
 199     public String getUIClassID() {
 200         return uiClassID;
 201     }
 202 
 203 
 204     /**
 205      * Overriden to return true, JToggleButton supports
 206      * the selected state.
 207      */
 208     boolean shouldUpdateSelectedStateFromAction() {
 209         return true;
 210     }
 211 
 212     // *********************************************************************
 213 
 214     /**
 215      * The ToggleButton model
 216      * <p>
 217      * <strong>Warning:</strong>
 218      * Serialized objects of this class will not be compatible with
 219      * future Swing releases. The current serialization support is
 220      * appropriate for short term storage or RMI between applications running
 221      * the same version of Swing.  As of 1.4, support for long term storage
 222      * of all JavaBeans&trade;
 223      * has been added to the <code>java.beans</code> package.
 224      * Please see {@link java.beans.XMLEncoder}.
 225      */
 226     @SuppressWarnings("serial") // Same-version serialization only
 227     public static class ToggleButtonModel extends DefaultButtonModel {
 228 
 229         /**
 230          * Creates a new ToggleButton Model
 231          */
 232         public ToggleButtonModel () {
 233         }
 234 
 235         /**
 236          * Checks if the button is selected.
 237          */
 238         public boolean isSelected() {
 239 //              if(getGroup() != null) {
 240 //                  return getGroup().isSelected(this);
 241 //              } else {
 242                 return (stateMask & SELECTED) != 0;
 243 //              }
 244         }
 245 
 246 
 247         /**
 248          * Sets the selected state of the button.
 249          * @param b true selects the toggle button,
 250          *          false deselects the toggle button.
 251          */
 252         public void setSelected(boolean b) {
 253             ButtonGroup group = getGroup();
 254             if (group != null) {
 255                 // use the group model instead
 256                 group.setSelected(this, b);
 257                 b = group.isSelected(this);
 258             }
 259 
 260             if (isSelected() == b) {
 261                 return;
 262             }
 263 
 264             if (b) {
 265                 stateMask |= SELECTED;
 266             } else {
 267                 stateMask &= ~SELECTED;
 268             }
 269 
 270             // Send ChangeEvent
 271             fireStateChanged();
 272 
 273             // Send ItemEvent
 274             fireItemStateChanged(
 275                     new ItemEvent(this,
 276                                   ItemEvent.ITEM_STATE_CHANGED,
 277                                   this,
 278                                   this.isSelected() ?  ItemEvent.SELECTED : ItemEvent.DESELECTED));
 279 
 280         }
 281 
 282         /**
 283          * Sets the pressed state of the toggle button.
 284          */
 285         public void setPressed(boolean b) {
 286             if ((isPressed() == b) || !isEnabled()) {
 287                 return;
 288             }
 289 
 290             if (b == false && isArmed()) {
 291                 setSelected(!this.isSelected());
 292             }
 293 
 294             if (b) {
 295                 stateMask |= PRESSED;
 296             } else {
 297                 stateMask &= ~PRESSED;
 298             }
 299 
 300             fireStateChanged();
 301 
 302             if(!isPressed() && isArmed()) {
 303                 int modifiers = 0;
 304                 AWTEvent currentEvent = EventQueue.getCurrentEvent();
 305                 if (currentEvent instanceof InputEvent) {
 306                     modifiers = ((InputEvent)currentEvent).getModifiers();
 307                 } else if (currentEvent instanceof ActionEvent) {
 308                     modifiers = ((ActionEvent)currentEvent).getModifiers();
 309                 }
 310                 fireActionPerformed(
 311                     new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
 312                                     getActionCommand(),
 313                                     EventQueue.getMostRecentEventTime(),
 314                                     modifiers));
 315             }
 316 
 317         }
 318     }
 319 
 320 
 321     /**
 322      * See readObject() and writeObject() in JComponent for more
 323      * information about serialization in Swing.
 324      */
 325     private void writeObject(ObjectOutputStream s) throws IOException {
 326         s.defaultWriteObject();
 327         if (getUIClassID().equals(uiClassID)) {
 328             byte count = JComponent.getWriteObjCounter(this);
 329             JComponent.setWriteObjCounter(this, --count);
 330             if (count == 0 && ui != null) {
 331                 ui.installUI(this);
 332             }
 333         }
 334     }
 335 
 336 
 337     /**
 338      * Returns a string representation of this JToggleButton. This method
 339      * is intended to be used only for debugging purposes, and the
 340      * content and format of the returned string may vary between
 341      * implementations. The returned string may be empty but may not
 342      * be <code>null</code>.
 343      *
 344      * @return  a string representation of this JToggleButton.
 345      */
 346     protected String paramString() {
 347         return super.paramString();
 348     }
 349 
 350 
 351 /////////////////
 352 // Accessibility support
 353 ////////////////
 354 
 355     /**
 356      * Gets the AccessibleContext associated with this JToggleButton.
 357      * For toggle buttons, the AccessibleContext takes the form of an
 358      * AccessibleJToggleButton.
 359      * A new AccessibleJToggleButton instance is created if necessary.
 360      *
 361      * @return an AccessibleJToggleButton that serves as the
 362      *         AccessibleContext of this JToggleButton
 363      * @beaninfo
 364      *       expert: true
 365      *  description: The AccessibleContext associated with this ToggleButton.
 366      */
 367     public AccessibleContext getAccessibleContext() {
 368         if (accessibleContext == null) {
 369             accessibleContext = new AccessibleJToggleButton();
 370         }
 371         return accessibleContext;
 372     }
 373 
 374     /**
 375      * This class implements accessibility support for the
 376      * <code>JToggleButton</code> class.  It provides an implementation of the
 377      * Java Accessibility API appropriate to toggle button user-interface
 378      * elements.
 379      * <p>
 380      * <strong>Warning:</strong>
 381      * Serialized objects of this class will not be compatible with
 382      * future Swing releases. The current serialization support is
 383      * appropriate for short term storage or RMI between applications running
 384      * the same version of Swing.  As of 1.4, support for long term storage
 385      * of all JavaBeans&trade;
 386      * has been added to the <code>java.beans</code> package.
 387      * Please see {@link java.beans.XMLEncoder}.
 388      */
 389     @SuppressWarnings("serial") // Same-version serialization only
 390     protected class AccessibleJToggleButton extends AccessibleAbstractButton
 391             implements ItemListener {
 392 
 393         public AccessibleJToggleButton() {
 394             super();
 395             JToggleButton.this.addItemListener(this);
 396         }
 397 
 398         /**
 399          * Fire accessible property change events when the state of the
 400          * toggle button changes.
 401          */
 402         public void itemStateChanged(ItemEvent e) {
 403             JToggleButton tb = (JToggleButton) e.getSource();
 404             if (JToggleButton.this.accessibleContext != null) {
 405                 if (tb.isSelected()) {
 406                     JToggleButton.this.accessibleContext.firePropertyChange(
 407                             AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
 408                             null, AccessibleState.CHECKED);
 409                 } else {
 410                     JToggleButton.this.accessibleContext.firePropertyChange(
 411                             AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
 412                             AccessibleState.CHECKED, null);
 413                 }
 414             }
 415         }
 416 
 417         /**
 418          * Get the role of this object.
 419          *
 420          * @return an instance of AccessibleRole describing the role of the
 421          * object
 422          */
 423         public AccessibleRole getAccessibleRole() {
 424             return AccessibleRole.TOGGLE_BUTTON;
 425         }
 426     } // inner class AccessibleJToggleButton
 427 }