Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/awt/CheckboxMenuItem.java
38829 views
/*1* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package java.awt;2526import java.awt.peer.CheckboxMenuItemPeer;27import java.awt.event.*;28import java.util.EventListener;29import java.io.ObjectOutputStream;30import java.io.ObjectInputStream;31import java.io.IOException;32import javax.accessibility.*;33import sun.awt.AWTAccessor;343536/**37* This class represents a check box that can be included in a menu.38* Selecting the check box in the menu changes its state from39* "on" to "off" or from "off" to "on."40* <p>41* The following picture depicts a menu which contains an instance42* of <code>CheckBoxMenuItem</code>:43* <p>44* <img src="doc-files/MenuBar-1.gif"45* alt="Menu labeled Examples, containing items Basic, Simple, Check, and More Examples. The Check item is a CheckBoxMenuItem instance, in the off state."46* style="float:center; margin: 7px 10px;">47* <p>48* The item labeled <code>Check</code> shows a check box menu item49* in its "off" state.50* <p>51* When a check box menu item is selected, AWT sends an item event to52* the item. Since the event is an instance of <code>ItemEvent</code>,53* the <code>processEvent</code> method examines the event and passes54* it along to <code>processItemEvent</code>. The latter method redirects55* the event to any <code>ItemListener</code> objects that have56* registered an interest in item events generated by this menu item.57*58* @author Sami Shaio59* @see java.awt.event.ItemEvent60* @see java.awt.event.ItemListener61* @since JDK1.062*/63public class CheckboxMenuItem extends MenuItem implements ItemSelectable, Accessible {6465static {66/* ensure that the necessary native libraries are loaded */67Toolkit.loadLibraries();68if (!GraphicsEnvironment.isHeadless()) {69initIDs();70}7172AWTAccessor.setCheckboxMenuItemAccessor(73new AWTAccessor.CheckboxMenuItemAccessor() {74public boolean getState(CheckboxMenuItem cmi) {75return cmi.state;76}77});78}7980/**81* The state of a checkbox menu item82* @serial83* @see #getState()84* @see #setState(boolean)85*/86boolean state = false;8788transient ItemListener itemListener;8990private static final String base = "chkmenuitem";91private static int nameCounter = 0;9293/*94* JDK 1.1 serialVersionUID95*/96private static final long serialVersionUID = 6190621106981774043L;9798/**99* Create a check box menu item with an empty label.100* The item's state is initially set to "off."101* @exception HeadlessException if GraphicsEnvironment.isHeadless()102* returns true103* @see java.awt.GraphicsEnvironment#isHeadless104* @since JDK1.1105*/106public CheckboxMenuItem() throws HeadlessException {107this("", false);108}109110/**111* Create a check box menu item with the specified label.112* The item's state is initially set to "off."113114* @param label a string label for the check box menu item,115* or <code>null</code> for an unlabeled menu item.116* @exception HeadlessException if GraphicsEnvironment.isHeadless()117* returns true118* @see java.awt.GraphicsEnvironment#isHeadless119*/120public CheckboxMenuItem(String label) throws HeadlessException {121this(label, false);122}123124/**125* Create a check box menu item with the specified label and state.126* @param label a string label for the check box menu item,127* or <code>null</code> for an unlabeled menu item.128* @param state the initial state of the menu item, where129* <code>true</code> indicates "on" and130* <code>false</code> indicates "off."131* @exception HeadlessException if GraphicsEnvironment.isHeadless()132* returns true133* @see java.awt.GraphicsEnvironment#isHeadless134* @since JDK1.1135*/136public CheckboxMenuItem(String label, boolean state)137throws HeadlessException {138super(label);139this.state = state;140}141142/**143* Construct a name for this MenuComponent. Called by getName() when144* the name is null.145*/146String constructComponentName() {147synchronized (CheckboxMenuItem.class) {148return base + nameCounter++;149}150}151152/**153* Creates the peer of the checkbox item. This peer allows us to154* change the look of the checkbox item without changing its155* functionality.156* Most applications do not call this method directly.157* @see java.awt.Toolkit#createCheckboxMenuItem(java.awt.CheckboxMenuItem)158* @see java.awt.Component#getToolkit()159*/160public void addNotify() {161synchronized (getTreeLock()) {162if (peer == null)163peer = Toolkit.getDefaultToolkit().createCheckboxMenuItem(this);164super.addNotify();165}166}167168/**169* Determines whether the state of this check box menu item170* is "on" or "off."171*172* @return the state of this check box menu item, where173* <code>true</code> indicates "on" and174* <code>false</code> indicates "off"175* @see #setState176*/177public boolean getState() {178return state;179}180181/**182* Sets this check box menu item to the specified state.183* The boolean value <code>true</code> indicates "on" while184* <code>false</code> indicates "off."185*186* <p>Note that this method should be primarily used to187* initialize the state of the check box menu item.188* Programmatically setting the state of the check box189* menu item will <i>not</i> trigger190* an <code>ItemEvent</code>. The only way to trigger an191* <code>ItemEvent</code> is by user interaction.192*193* @param b <code>true</code> if the check box194* menu item is on, otherwise <code>false</code>195* @see #getState196*/197public synchronized void setState(boolean b) {198state = b;199CheckboxMenuItemPeer peer = (CheckboxMenuItemPeer)this.peer;200if (peer != null) {201peer.setState(b);202}203}204205/**206* Returns the an array (length 1) containing the checkbox menu item207* label or null if the checkbox is not selected.208* @see ItemSelectable209*/210public synchronized Object[] getSelectedObjects() {211if (state) {212Object[] items = new Object[1];213items[0] = label;214return items;215}216return null;217}218219/**220* Adds the specified item listener to receive item events from221* this check box menu item. Item events are sent in response to user222* actions, but not in response to calls to setState().223* If l is null, no exception is thrown and no action is performed.224* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"225* >AWT Threading Issues</a> for details on AWT's threading model.226*227* @param l the item listener228* @see #removeItemListener229* @see #getItemListeners230* @see #setState231* @see java.awt.event.ItemEvent232* @see java.awt.event.ItemListener233* @since JDK1.1234*/235public synchronized void addItemListener(ItemListener l) {236if (l == null) {237return;238}239itemListener = AWTEventMulticaster.add(itemListener, l);240newEventsOnly = true;241}242243/**244* Removes the specified item listener so that it no longer receives245* item events from this check box menu item.246* If l is null, no exception is thrown and no action is performed.247* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"248* >AWT Threading Issues</a> for details on AWT's threading model.249*250* @param l the item listener251* @see #addItemListener252* @see #getItemListeners253* @see java.awt.event.ItemEvent254* @see java.awt.event.ItemListener255* @since JDK1.1256*/257public synchronized void removeItemListener(ItemListener l) {258if (l == null) {259return;260}261itemListener = AWTEventMulticaster.remove(itemListener, l);262}263264/**265* Returns an array of all the item listeners266* registered on this checkbox menuitem.267*268* @return all of this checkbox menuitem's <code>ItemListener</code>s269* or an empty array if no item270* listeners are currently registered271*272* @see #addItemListener273* @see #removeItemListener274* @see java.awt.event.ItemEvent275* @see java.awt.event.ItemListener276* @since 1.4277*/278public synchronized ItemListener[] getItemListeners() {279return getListeners(ItemListener.class);280}281282/**283* Returns an array of all the objects currently registered284* as <code><em>Foo</em>Listener</code>s285* upon this <code>CheckboxMenuItem</code>.286* <code><em>Foo</em>Listener</code>s are registered using the287* <code>add<em>Foo</em>Listener</code> method.288*289* <p>290* You can specify the <code>listenerType</code> argument291* with a class literal, such as292* <code><em>Foo</em>Listener.class</code>.293* For example, you can query a294* <code>CheckboxMenuItem</code> <code>c</code>295* for its item listeners with the following code:296*297* <pre>ItemListener[] ils = (ItemListener[])(c.getListeners(ItemListener.class));</pre>298*299* If no such listeners exist, this method returns an empty array.300*301* @param listenerType the type of listeners requested; this parameter302* should specify an interface that descends from303* <code>java.util.EventListener</code>304* @return an array of all objects registered as305* <code><em>Foo</em>Listener</code>s on this checkbox menuitem,306* or an empty array if no such307* listeners have been added308* @exception ClassCastException if <code>listenerType</code>309* doesn't specify a class or interface that implements310* <code>java.util.EventListener</code>311*312* @see #getItemListeners313* @since 1.3314*/315public <T extends EventListener> T[] getListeners(Class<T> listenerType) {316EventListener l = null;317if (listenerType == ItemListener.class) {318l = itemListener;319} else {320return super.getListeners(listenerType);321}322return AWTEventMulticaster.getListeners(l, listenerType);323}324325// REMIND: remove when filtering is done at lower level326boolean eventEnabled(AWTEvent e) {327if (e.id == ItemEvent.ITEM_STATE_CHANGED) {328if ((eventMask & AWTEvent.ITEM_EVENT_MASK) != 0 ||329itemListener != null) {330return true;331}332return false;333}334return super.eventEnabled(e);335}336337/**338* Processes events on this check box menu item.339* If the event is an instance of <code>ItemEvent</code>,340* this method invokes the <code>processItemEvent</code> method.341* If the event is not an item event,342* it invokes <code>processEvent</code> on the superclass.343* <p>344* Check box menu items currently support only item events.345* <p>Note that if the event parameter is <code>null</code>346* the behavior is unspecified and may result in an347* exception.348*349* @param e the event350* @see java.awt.event.ItemEvent351* @see #processItemEvent352* @since JDK1.1353*/354protected void processEvent(AWTEvent e) {355if (e instanceof ItemEvent) {356processItemEvent((ItemEvent)e);357return;358}359super.processEvent(e);360}361362/**363* Processes item events occurring on this check box menu item by364* dispatching them to any registered <code>ItemListener</code> objects.365* <p>366* This method is not called unless item events are367* enabled for this menu item. Item events are enabled368* when one of the following occurs:369* <ul>370* <li>An <code>ItemListener</code> object is registered371* via <code>addItemListener</code>.372* <li>Item events are enabled via <code>enableEvents</code>.373* </ul>374* <p>Note that if the event parameter is <code>null</code>375* the behavior is unspecified and may result in an376* exception.377*378* @param e the item event379* @see java.awt.event.ItemEvent380* @see java.awt.event.ItemListener381* @see #addItemListener382* @see java.awt.MenuItem#enableEvents383* @since JDK1.1384*/385protected void processItemEvent(ItemEvent e) {386ItemListener listener = itemListener;387if (listener != null) {388listener.itemStateChanged(e);389}390}391392/*393* Post an ItemEvent and toggle state.394*/395void doMenuEvent(long when, int modifiers) {396setState(!state);397Toolkit.getEventQueue().postEvent(398new ItemEvent(this, ItemEvent.ITEM_STATE_CHANGED,399getLabel(),400state ? ItemEvent.SELECTED :401ItemEvent.DESELECTED));402}403404/**405* Returns a string representing the state of this406* <code>CheckBoxMenuItem</code>. This407* method is intended to be used only for debugging purposes, and the408* content and format of the returned string may vary between409* implementations. The returned string may be empty but may not be410* <code>null</code>.411*412* @return the parameter string of this check box menu item413*/414public String paramString() {415return super.paramString() + ",state=" + state;416}417418/* Serialization support.419*/420421/*422* Serial Data Version423* @serial424*/425private int checkboxMenuItemSerializedDataVersion = 1;426427/**428* Writes default serializable fields to stream. Writes429* a list of serializable <code>ItemListeners</code>430* as optional data. The non-serializable431* <code>ItemListeners</code> are detected and432* no attempt is made to serialize them.433*434* @param s the <code>ObjectOutputStream</code> to write435* @serialData <code>null</code> terminated sequence of436* 0 or more pairs; the pair consists of a <code>String</code>437* and an <code>Object</code>; the <code>String</code> indicates438* the type of object and is one of the following:439* <code>itemListenerK</code> indicating an440* <code>ItemListener</code> object441*442* @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)443* @see java.awt.Component#itemListenerK444* @see #readObject(ObjectInputStream)445*/446private void writeObject(ObjectOutputStream s)447throws java.io.IOException448{449s.defaultWriteObject();450451AWTEventMulticaster.save(s, itemListenerK, itemListener);452s.writeObject(null);453}454455/*456* Reads the <code>ObjectInputStream</code> and if it457* isn't <code>null</code> adds a listener to receive458* item events fired by the <code>Checkbox</code> menu item.459* Unrecognized keys or values will be ignored.460*461* @param s the <code>ObjectInputStream</code> to read462* @serial463* @see removeActionListener()464* @see addActionListener()465* @see #writeObject466*/467private void readObject(ObjectInputStream s)468throws ClassNotFoundException, IOException469{470s.defaultReadObject();471472Object keyOrNull;473while(null != (keyOrNull = s.readObject())) {474String key = ((String)keyOrNull).intern();475476if (itemListenerK == key)477addItemListener((ItemListener)(s.readObject()));478479else // skip value for unrecognized key480s.readObject();481}482}483484/**485* Initialize JNI field and method IDs486*/487private static native void initIDs();488489490/////////////////491// Accessibility support492////////////////493494/**495* Gets the AccessibleContext associated with this CheckboxMenuItem.496* For checkbox menu items, the AccessibleContext takes the497* form of an AccessibleAWTCheckboxMenuItem.498* A new AccessibleAWTCheckboxMenuItem is created if necessary.499*500* @return an AccessibleAWTCheckboxMenuItem that serves as the501* AccessibleContext of this CheckboxMenuItem502* @since 1.3503*/504public AccessibleContext getAccessibleContext() {505if (accessibleContext == null) {506accessibleContext = new AccessibleAWTCheckboxMenuItem();507}508return accessibleContext;509}510511/**512* Inner class of CheckboxMenuItem used to provide default support for513* accessibility. This class is not meant to be used directly by514* application developers, but is instead meant only to be515* subclassed by menu component developers.516* <p>517* This class implements accessibility support for the518* <code>CheckboxMenuItem</code> class. It provides an implementation519* of the Java Accessibility API appropriate to checkbox menu item520* user-interface elements.521* @since 1.3522*/523protected class AccessibleAWTCheckboxMenuItem extends AccessibleAWTMenuItem524implements AccessibleAction, AccessibleValue525{526/*527* JDK 1.3 serialVersionUID528*/529private static final long serialVersionUID = -1122642964303476L;530531/**532* Get the AccessibleAction associated with this object. In the533* implementation of the Java Accessibility API for this class,534* return this object, which is responsible for implementing the535* AccessibleAction interface on behalf of itself.536*537* @return this object538*/539public AccessibleAction getAccessibleAction() {540return this;541}542543/**544* Get the AccessibleValue associated with this object. In the545* implementation of the Java Accessibility API for this class,546* return this object, which is responsible for implementing the547* AccessibleValue interface on behalf of itself.548*549* @return this object550*/551public AccessibleValue getAccessibleValue() {552return this;553}554555/**556* Returns the number of Actions available in this object.557* If there is more than one, the first one is the "default"558* action.559*560* @return the number of Actions in this object561*/562public int getAccessibleActionCount() {563return 0; // To be fully implemented in a future release564}565566/**567* Return a description of the specified action of the object.568*569* @param i zero-based index of the actions570*/571public String getAccessibleActionDescription(int i) {572return null; // To be fully implemented in a future release573}574575/**576* Perform the specified Action on the object577*578* @param i zero-based index of actions579* @return true if the action was performed; otherwise false.580*/581public boolean doAccessibleAction(int i) {582return false; // To be fully implemented in a future release583}584585/**586* Get the value of this object as a Number. If the value has not been587* set, the return value will be null.588*589* @return value of the object590* @see #setCurrentAccessibleValue591*/592public Number getCurrentAccessibleValue() {593return null; // To be fully implemented in a future release594}595596/**597* Set the value of this object as a Number.598*599* @return true if the value was set; otherwise false600* @see #getCurrentAccessibleValue601*/602public boolean setCurrentAccessibleValue(Number n) {603return false; // To be fully implemented in a future release604}605606/**607* Get the minimum value of this object as a Number.608*609* @return Minimum value of the object; null if this object does not610* have a minimum value611* @see #getMaximumAccessibleValue612*/613public Number getMinimumAccessibleValue() {614return null; // To be fully implemented in a future release615}616617/**618* Get the maximum value of this object as a Number.619*620* @return Maximum value of the object; null if this object does not621* have a maximum value622* @see #getMinimumAccessibleValue623*/624public Number getMaximumAccessibleValue() {625return null; // To be fully implemented in a future release626}627628/**629* Get the role of this object.630*631* @return an instance of AccessibleRole describing the role of the632* object633*/634public AccessibleRole getAccessibleRole() {635return AccessibleRole.CHECK_BOX;636}637638} // class AccessibleAWTMenuItem639640}641642643