1 /*
   2  * Copyright (c) 1997, 2015, 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 import java.beans.JavaBean;
  30 import java.beans.BeanProperty;
  31 
  32 import javax.swing.plaf.*;
  33 import javax.accessibility.*;
  34 
  35 import java.io.ObjectOutputStream;
  36 import java.io.IOException;
  37 import java.util.Iterator;
  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  * @see JRadioButton
  72  * @see JCheckBox
  73  * @author Jeff Dinkins
  74  * @since 1.2
  75  */
  76 @JavaBean(defaultProperty = "UIClassID", description = "An implementation of a two-state button.")
  77 @SwingContainer(false)
  78 @SuppressWarnings("serial") // Same-version serialization only
  79 public class JToggleButton extends AbstractButton implements Accessible {
  80 
  81     /**
  82      * @see #getUIClassID
  83      * @see #readObject
  84      */
  85     private static final String uiClassID = "ToggleButtonUI";
  86 
  87     /**
  88      * Creates an initially unselected toggle button
  89      * without setting the text or image.
  90      */
  91     public JToggleButton () {
  92         this(null, null, false);
  93     }
  94 
  95     /**
  96      * Creates an initially unselected toggle button
  97      * with the specified image but no text.
  98      *
  99      * @param icon  the image that the button should display
 100      */
 101     public JToggleButton(Icon icon) {
 102         this(null, icon, false);
 103     }
 104 
 105     /**
 106      * Creates a toggle button with the specified image
 107      * and selection state, but no text.
 108      *
 109      * @param icon  the image that the button should display
 110      * @param selected  if true, the button is initially selected;
 111      *                  otherwise, the button is initially unselected
 112      */
 113     public JToggleButton(Icon icon, boolean selected) {
 114         this(null, icon, selected);
 115     }
 116 
 117     /**
 118      * Creates an unselected toggle button with the specified text.
 119      *
 120      * @param text  the string displayed on the toggle button
 121      */
 122     public JToggleButton (String text) {
 123         this(text, null, false);
 124     }
 125 
 126     /**
 127      * Creates a toggle button with the specified text
 128      * and selection state.
 129      *
 130      * @param text  the string displayed on the toggle button
 131      * @param selected  if true, the button is initially selected;
 132      *                  otherwise, the button is initially unselected
 133      */
 134     public JToggleButton (String text, boolean selected) {
 135         this(text, null, selected);
 136     }
 137 
 138     /**
 139      * Creates a toggle button where properties are taken from the
 140      * Action supplied.
 141      *
 142      * @param a an instance of an {@code Action}
 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      */
 197     @BeanProperty(bound = false, description
 198             = "A string that specifies the name of the L&amp;F class")
 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     private JToggleButton getGroupSelection(FocusEvent.Cause cause) {
 213         switch (cause) {
 214           case ACTIVATION:
 215           case TRAVERSAL:
 216           case TRAVERSAL_UP:
 217           case TRAVERSAL_DOWN:
 218           case TRAVERSAL_FORWARD:
 219           case TRAVERSAL_BACKWARD:
 220             ButtonModel model = getModel();
 221             JToggleButton selection = this;
 222             if (model != null) {
 223                 ButtonGroup group = model.getGroup();
 224                 if (group != null && group.getSelection() != null
 225                                                   && !group.isSelected(model)) {
 226                     Iterator<AbstractButton> iterator =
 227                                                group.getElements().asIterator();
 228                     while (iterator.hasNext()) {
 229                         AbstractButton member = iterator.next();
 230                         if (group.isSelected(member.getModel())) {
 231                             if (member instanceof JToggleButton &&
 232                                 member.isVisible() && member.isDisplayable() &&
 233                                 member.isEnabled() && member.isFocusable()) {
 234                                 selection = (JToggleButton) member;
 235                             }
 236                             break;
 237                         }
 238                     }
 239                 }
 240             }
 241             return selection;
 242           default:
 243             return this;
 244         }
 245     }
 246 
 247     /**
 248      * If this toggle button is a member of the {@link ButtonGroup} which has
 249      * another toggle button which is selected and can be the focus owner,
 250      * and the focus cause argument denotes window activation or focus
 251      * traversal action of any direction the result of the method execution
 252      * is the same as calling
 253      * {@link Component#requestFocus(FocusEvent.Cause)} on the toggle button
 254      * selected in the group.
 255      * In all other cases the result of the method is the same as calling
 256      * {@link Component#requestFocus(FocusEvent.Cause)} on this toggle button.
 257      *
 258      * @param  cause the cause why the focus is requested
 259      * @see ButtonGroup
 260      * @see Component#requestFocus(FocusEvent.Cause)
 261      * @see FocusEvent.Cause
 262      *
 263      * @since 9
 264      */
 265     @Override
 266     public void requestFocus(FocusEvent.Cause cause) {
 267         getGroupSelection(cause).requestFocusUnconditionally(cause);
 268     }
 269 
 270     private void requestFocusUnconditionally(FocusEvent.Cause cause) {
 271         super.requestFocus(cause);
 272     }
 273 
 274     /**
 275      * If this toggle button is a member of the {@link ButtonGroup} which has
 276      * another toggle button which is selected and can be the focus owner,
 277      * and the focus cause argument denotes window activation or focus
 278      * traversal action of any direction the result of the method execution
 279      * is the same as calling
 280      * {@link Component#requestFocusInWindow(FocusEvent.Cause)} on the toggle
 281      * button selected in the group.
 282      * In all other cases the result of the method is the same as calling
 283      * {@link Component#requestFocusInWindow(FocusEvent.Cause)} on this toggle
 284      * button.
 285      *
 286      * @param  cause the cause why the focus is requested
 287      * @see ButtonGroup
 288      * @see Component#requestFocusInWindow(FocusEvent.Cause)
 289      * @see FocusEvent.Cause
 290      *
 291      * @since 9
 292      */
 293     public boolean requestFocusInWindow(FocusEvent.Cause cause) {
 294         return getGroupSelection(cause)
 295                                     .requestFocusInWindowUnconditionally(cause);
 296     }
 297 
 298     private boolean requestFocusInWindowUnconditionally(FocusEvent.Cause cause) {
 299         return super.requestFocusInWindow(cause);
 300     }
 301 
 302     // *********************************************************************
 303 
 304     /**
 305      * The ToggleButton model
 306      * <p>
 307      * <strong>Warning:</strong>
 308      * Serialized objects of this class will not be compatible with
 309      * future Swing releases. The current serialization support is
 310      * appropriate for short term storage or RMI between applications running
 311      * the same version of Swing.  As of 1.4, support for long term storage
 312      * of all JavaBeans&trade;
 313      * has been added to the <code>java.beans</code> package.
 314      * Please see {@link java.beans.XMLEncoder}.
 315      */
 316     @SuppressWarnings("serial") // Same-version serialization only
 317     public static class ToggleButtonModel extends DefaultButtonModel {
 318 
 319         /**
 320          * Creates a new ToggleButton Model
 321          */
 322         public ToggleButtonModel () {
 323         }
 324 
 325         /**
 326          * Checks if the button is selected.
 327          */
 328         public boolean isSelected() {
 329 //              if(getGroup() != null) {
 330 //                  return getGroup().isSelected(this);
 331 //              } else {
 332                 return (stateMask & SELECTED) != 0;
 333 //              }
 334         }
 335 
 336 
 337         /**
 338          * Sets the selected state of the button.
 339          * @param b true selects the toggle button,
 340          *          false deselects the toggle button.
 341          */
 342         public void setSelected(boolean b) {
 343             ButtonGroup group = getGroup();
 344             if (group != null) {
 345                 // use the group model instead
 346                 group.setSelected(this, b);
 347                 b = group.isSelected(this);
 348             }
 349 
 350             if (isSelected() == b) {
 351                 return;
 352             }
 353 
 354             if (b) {
 355                 stateMask |= SELECTED;
 356             } else {
 357                 stateMask &= ~SELECTED;
 358             }
 359 
 360             // Send ChangeEvent
 361             fireStateChanged();
 362 
 363             // Send ItemEvent
 364             fireItemStateChanged(
 365                     new ItemEvent(this,
 366                                   ItemEvent.ITEM_STATE_CHANGED,
 367                                   this,
 368                                   this.isSelected() ?  ItemEvent.SELECTED : ItemEvent.DESELECTED));
 369 
 370         }
 371 
 372         /**
 373          * Sets the pressed state of the toggle button.
 374          */
 375         @SuppressWarnings("deprecation")
 376         public void setPressed(boolean b) {
 377             if ((isPressed() == b) || !isEnabled()) {
 378                 return;
 379             }
 380 
 381             if (b == false && isArmed()) {
 382                 setSelected(!this.isSelected());
 383             }
 384 
 385             if (b) {
 386                 stateMask |= PRESSED;
 387             } else {
 388                 stateMask &= ~PRESSED;
 389             }
 390 
 391             fireStateChanged();
 392 
 393             if(!isPressed() && isArmed()) {
 394                 int modifiers = 0;
 395                 AWTEvent currentEvent = EventQueue.getCurrentEvent();
 396                 if (currentEvent instanceof InputEvent) {
 397                     modifiers = ((InputEvent)currentEvent).getModifiers();
 398                 } else if (currentEvent instanceof ActionEvent) {
 399                     modifiers = ((ActionEvent)currentEvent).getModifiers();
 400                 }
 401                 fireActionPerformed(
 402                     new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
 403                                     getActionCommand(),
 404                                     EventQueue.getMostRecentEventTime(),
 405                                     modifiers));
 406             }
 407 
 408         }
 409     }
 410 
 411 
 412     /**
 413      * See readObject() and writeObject() in JComponent for more
 414      * information about serialization in Swing.
 415      */
 416     private void writeObject(ObjectOutputStream s) throws IOException {
 417         s.defaultWriteObject();
 418         if (getUIClassID().equals(uiClassID)) {
 419             byte count = JComponent.getWriteObjCounter(this);
 420             JComponent.setWriteObjCounter(this, --count);
 421             if (count == 0 && ui != null) {
 422                 ui.installUI(this);
 423             }
 424         }
 425     }
 426 
 427 
 428     /**
 429      * Returns a string representation of this JToggleButton. This method
 430      * is intended to be used only for debugging purposes, and the
 431      * content and format of the returned string may vary between
 432      * implementations. The returned string may be empty but may not
 433      * be <code>null</code>.
 434      *
 435      * @return  a string representation of this JToggleButton.
 436      */
 437     protected String paramString() {
 438         return super.paramString();
 439     }
 440 
 441 
 442 /////////////////
 443 // Accessibility support
 444 ////////////////
 445 
 446     /**
 447      * Gets the AccessibleContext associated with this JToggleButton.
 448      * For toggle buttons, the AccessibleContext takes the form of an
 449      * AccessibleJToggleButton.
 450      * A new AccessibleJToggleButton instance is created if necessary.
 451      *
 452      * @return an AccessibleJToggleButton that serves as the
 453      *         AccessibleContext of this JToggleButton
 454      */
 455     @BeanProperty(bound = false, expert = true, description
 456             = "The AccessibleContext associated with this ToggleButton.")
 457     public AccessibleContext getAccessibleContext() {
 458         if (accessibleContext == null) {
 459             accessibleContext = new AccessibleJToggleButton();
 460         }
 461         return accessibleContext;
 462     }
 463 
 464     /**
 465      * This class implements accessibility support for the
 466      * <code>JToggleButton</code> class.  It provides an implementation of the
 467      * Java Accessibility API appropriate to toggle button user-interface
 468      * elements.
 469      * <p>
 470      * <strong>Warning:</strong>
 471      * Serialized objects of this class will not be compatible with
 472      * future Swing releases. The current serialization support is
 473      * appropriate for short term storage or RMI between applications running
 474      * the same version of Swing.  As of 1.4, support for long term storage
 475      * of all JavaBeans&trade;
 476      * has been added to the <code>java.beans</code> package.
 477      * Please see {@link java.beans.XMLEncoder}.
 478      */
 479     @SuppressWarnings("serial") // Same-version serialization only
 480     protected class AccessibleJToggleButton extends AccessibleAbstractButton
 481             implements ItemListener {
 482 
 483         /**
 484          * Constructs {@code AccessibleJToggleButton}
 485          */
 486         public AccessibleJToggleButton() {
 487             super();
 488             JToggleButton.this.addItemListener(this);
 489         }
 490 
 491         /**
 492          * Fire accessible property change events when the state of the
 493          * toggle button changes.
 494          */
 495         public void itemStateChanged(ItemEvent e) {
 496             JToggleButton tb = (JToggleButton) e.getSource();
 497             if (JToggleButton.this.accessibleContext != null) {
 498                 if (tb.isSelected()) {
 499                     JToggleButton.this.accessibleContext.firePropertyChange(
 500                             AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
 501                             null, AccessibleState.CHECKED);
 502                 } else {
 503                     JToggleButton.this.accessibleContext.firePropertyChange(
 504                             AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
 505                             AccessibleState.CHECKED, null);
 506                 }
 507             }
 508         }
 509 
 510         /**
 511          * Get the role of this object.
 512          *
 513          * @return an instance of AccessibleRole describing the role of the
 514          * object
 515          */
 516         public AccessibleRole getAccessibleRole() {
 517             return AccessibleRole.TOGGLE_BUTTON;
 518         }
 519     } // inner class AccessibleJToggleButton
 520 }