KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > awt > CheckboxMenuItem


1 /*
2  * @(#)CheckboxMenuItem.java 1.69 04/05/05
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7 package java.awt;
8
9 import java.awt.peer.CheckboxMenuItemPeer;
10 import java.awt.event.*;
11 import java.util.EventListener JavaDoc;
12 import java.io.ObjectOutputStream JavaDoc;
13 import java.io.ObjectInputStream JavaDoc;
14 import java.io.IOException JavaDoc;
15 import javax.accessibility.*;
16
17
18 /**
19  * This class represents a check box that can be included in a menu.
20  * Selecting the check box in the menu changes its state from
21  * "on" to "off" or from "off" to "on."
22  * <p>
23  * The following picture depicts a menu which contains an instance
24  * of <code>CheckBoxMenuItem</code>:
25  * <p>
26  * <img SRC="doc-files/MenuBar-1.gif"
27  * alt="Menu labeled Examples, containing items Basic, Simple, Check, and More Examples. The Check item is a CheckBoxMenuItem instance, in the off state."
28  * ALIGN=center HSPACE=10 VSPACE=7>
29  * <p>
30  * The item labeled <code>Check</code> shows a check box menu item
31  * in its "off" state.
32  * <p>
33  * When a check box menu item is selected, AWT sends an item event to
34  * the item. Since the event is an instance of <code>ItemEvent</code>,
35  * the <code>processEvent</code> method examines the event and passes
36  * it along to <code>processItemEvent</code>. The latter method redirects
37  * the event to any <code>ItemListener</code> objects that have
38  * registered an interest in item events generated by this menu item.
39  *
40  * @version 1.69, 05/05/04
41  * @author Sami Shaio
42  * @see java.awt.event.ItemEvent
43  * @see java.awt.event.ItemListener
44  * @since JDK1.0
45  */

46 public class CheckboxMenuItem extends MenuItem JavaDoc implements ItemSelectable JavaDoc, Accessible {
47
48     static {
49         /* ensure that the necessary native libraries are loaded */
50     Toolkit.loadLibraries();
51         if (!GraphicsEnvironment.isHeadless()) {
52             initIDs();
53         }
54     }
55
56    /**
57     * The state of a checkbox menu item
58     * @serial
59     * @see #getState()
60     * @see #setState(boolean)
61     */

62     boolean state = false;
63
64     transient ItemListener itemListener;
65
66     private static final String JavaDoc base = "chkmenuitem";
67     private static int nameCounter = 0;
68
69     /*
70      * JDK 1.1 serialVersionUID
71      */

72      private static final long serialVersionUID = 6190621106981774043L;
73
74     /**
75      * Create a check box menu item with an empty label.
76      * The item's state is initially set to "off."
77      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
78      * returns true
79      * @see java.awt.GraphicsEnvironment#isHeadless
80      * @since JDK1.1
81      */

82     public CheckboxMenuItem() throws HeadlessException JavaDoc {
83     this("", false);
84     }
85
86     /**
87      * Create a check box menu item with the specified label.
88      * The item's state is initially set to "off."
89
90      * @param label a string label for the check box menu item,
91      * or <code>null</code> for an unlabeled menu item.
92      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
93      * returns true
94      * @see java.awt.GraphicsEnvironment#isHeadless
95      */

96     public CheckboxMenuItem(String JavaDoc label) throws HeadlessException JavaDoc {
97     this(label, false);
98     }
99
100     /**
101      * Create a check box menu item with the specified label and state.
102      * @param label a string label for the check box menu item,
103      * or <code>null</code> for an unlabeled menu item.
104      * @param state the initial state of the menu item, where
105      * <code>true</code> indicates "on" and
106      * <code>false</code> indicates "off."
107      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
108      * returns true
109      * @see java.awt.GraphicsEnvironment#isHeadless
110      * @since JDK1.1
111      */

112     public CheckboxMenuItem(String JavaDoc label, boolean state)
113         throws HeadlessException JavaDoc {
114         super(label);
115         this.state = state;
116     }
117
118     /**
119      * Construct a name for this MenuComponent. Called by getName() when
120      * the name is null.
121      */

122     String JavaDoc constructComponentName() {
123         synchronized (getClass()) {
124         return base + nameCounter++;
125     }
126     }
127
128     /**
129      * Creates the peer of the checkbox item. This peer allows us to
130      * change the look of the checkbox item without changing its
131      * functionality.
132      * Most applications do not call this method directly.
133      * @see java.awt.Toolkit#createCheckboxMenuItem(java.awt.CheckboxMenuItem)
134      * @see java.awt.Component#getToolkit()
135      */

136     public void addNotify() {
137         synchronized (getTreeLock()) {
138         if (peer == null)
139             peer = Toolkit.getDefaultToolkit().createCheckboxMenuItem(this);
140         super.addNotify();
141     }
142     }
143
144     /**
145      * Determines whether the state of this check box menu item
146      * is "on" or "off."
147      *
148      * @return the state of this check box menu item, where
149      * <code>true</code> indicates "on" and
150      * <code>false</code> indicates "off"
151      * @see #setState
152      */

153     public boolean getState() {
154     return state;
155     }
156
157     /**
158      * Sets this check box menu item to the specifed state.
159      * The boolean value <code>true</code> indicates "on" while
160      * <code>false</code> indicates "off."
161      *
162      * <p>Note that this method should be primarily used to
163      * initialize the state of the check box menu item.
164      * Programmatically setting the state of the check box
165      * menu item will <i>not</i> trigger
166      * an <code>ItemEvent</code>. The only way to trigger an
167      * <code>ItemEvent</code> is by user interaction.
168      *
169      * @param b <code>true</code> if the check box
170      * menu item is on, otherwise <code>false</code>
171      * @see #getState
172      */

173     public synchronized void setState(boolean b) {
174     state = b;
175     CheckboxMenuItemPeer peer = (CheckboxMenuItemPeer)this.peer;
176     if (peer != null) {
177         peer.setState(b);
178     }
179     }
180
181     /**
182      * Returns the an array (length 1) containing the checkbox menu item
183      * label or null if the checkbox is not selected.
184      * @see ItemSelectable
185      */

186     public synchronized Object JavaDoc[] getSelectedObjects() {
187         if (state) {
188             Object JavaDoc[] items = new Object JavaDoc[1];
189             items[0] = label;
190             return items;
191         }
192         return null;
193     }
194
195     /**
196      * Adds the specified item listener to receive item events from
197      * this check box menu item. Item events are sent in response to user
198      * actions, but not in response to calls to setState().
199      * If l is null, no exception is thrown and no action is performed.
200      *
201      * @param l the item listener
202      * @see #removeItemListener
203      * @see #getItemListeners
204      * @see #setState
205      * @see java.awt.event.ItemEvent
206      * @see java.awt.event.ItemListener
207      * @since JDK1.1
208      */

209     public synchronized void addItemListener(ItemListener l) {
210     if (l == null) {
211         return;
212     }
213         itemListener = AWTEventMulticaster.add(itemListener, l);
214         newEventsOnly = true;
215     }
216
217     /**
218      * Removes the specified item listener so that it no longer receives
219      * item events from this check box menu item.
220      * If l is null, no exception is thrown and no action is performed.
221      *
222      * @param l the item listener
223      * @see #addItemListener
224      * @see #getItemListeners
225      * @see java.awt.event.ItemEvent
226      * @see java.awt.event.ItemListener
227      * @since JDK1.1
228      */

229     public synchronized void removeItemListener(ItemListener l) {
230     if (l == null) {
231         return;
232     }
233         itemListener = AWTEventMulticaster.remove(itemListener, l);
234     }
235
236     /**
237      * Returns an array of all the item listeners
238      * registered on this checkbox menuitem.
239      *
240      * @return all of this checkbox menuitem's <code>ItemListener</code>s
241      * or an empty array if no item
242      * listeners are currently registered
243      *
244      * @see #addItemListener
245      * @see #removeItemListener
246      * @see java.awt.event.ItemEvent
247      * @see java.awt.event.ItemListener
248      * @since 1.4
249      */

250     public synchronized ItemListener[] getItemListeners() {
251         return (ItemListener[])(getListeners(ItemListener.class));
252     }
253
254     /**
255      * Returns an array of all the objects currently registered
256      * as <code><em>Foo</em>Listener</code>s
257      * upon this <code>CheckboxMenuItem</code>.
258      * <code><em>Foo</em>Listener</code>s are registered using the
259      * <code>add<em>Foo</em>Listener</code> method.
260      *
261      * <p>
262      * You can specify the <code>listenerType</code> argument
263      * with a class literal, such as
264      * <code><em>Foo</em>Listener.class</code>.
265      * For example, you can query a
266      * <code>CheckboxMenuItem</code> <code>c</code>
267      * for its item listeners with the following code:
268      *
269      * <pre>ItemListener[] ils = (ItemListener[])(c.getListeners(ItemListener.class));</pre>
270      *
271      * If no such listeners exist, this method returns an empty array.
272      *
273      * @param listenerType the type of listeners requested; this parameter
274      * should specify an interface that descends from
275      * <code>java.util.EventListener</code>
276      * @return an array of all objects registered as
277      * <code><em>Foo</em>Listener</code>s on this checkbox menuitem,
278      * or an empty array if no such
279      * listeners have been added
280      * @exception ClassCastException if <code>listenerType</code>
281      * doesn't specify a class or interface that implements
282      * <code>java.util.EventListener</code>
283      *
284      * @see #getItemListeners
285      * @since 1.3
286      */

287     public <T extends EventListener JavaDoc> T[] getListeners(Class JavaDoc<T> listenerType) {
288     EventListener JavaDoc l = null;
289     if (listenerType == ItemListener.class) {
290         l = itemListener;
291     } else {
292         return super.getListeners(listenerType);
293     }
294     return AWTEventMulticaster.getListeners(l, listenerType);
295     }
296
297     // REMIND: remove when filtering is done at lower level
298
boolean eventEnabled(AWTEvent JavaDoc e) {
299         if (e.id == ItemEvent.ITEM_STATE_CHANGED) {
300             if ((eventMask & AWTEvent.ITEM_EVENT_MASK) != 0 ||
301                 itemListener != null) {
302                 return true;
303             }
304             return false;
305         }
306         return super.eventEnabled(e);
307     }
308
309     /**
310      * Processes events on this check box menu item.
311      * If the event is an instance of <code>ItemEvent</code>,
312      * this method invokes the <code>processItemEvent</code> method.
313      * If the event is not an item event,
314      * it invokes <code>processEvent</code> on the superclass.
315      * <p>
316      * Check box menu items currently support only item events.
317      * <p>Note that if the event parameter is <code>null</code>
318      * the behavior is unspecified and may result in an
319      * exception.
320      *
321      * @param e the event
322      * @see java.awt.event.ItemEvent
323      * @see #processItemEvent
324      * @since JDK1.1
325      */

326     protected void processEvent(AWTEvent JavaDoc e) {
327         if (e instanceof ItemEvent) {
328             processItemEvent((ItemEvent)e);
329         return;
330         }
331     super.processEvent(e);
332     }
333
334     /**
335      * Processes item events occurring on this check box menu item by
336      * dispatching them to any registered <code>ItemListener</code> objects.
337      * <p>
338      * This method is not called unless item events are
339      * enabled for this menu item. Item events are enabled
340      * when one of the following occurs:
341      * <p><ul>
342      * <li>An <code>ItemListener</code> object is registered
343      * via <code>addItemListener</code>.
344      * <li>Item events are enabled via <code>enableEvents</code>.
345      * </ul>
346      * <p>Note that if the event parameter is <code>null</code>
347      * the behavior is unspecified and may result in an
348      * exception.
349      *
350      * @param e the item event
351      * @see java.awt.event.ItemEvent
352      * @see java.awt.event.ItemListener
353      * @see #addItemListener
354      * @see java.awt.MenuItem#enableEvents
355      * @since JDK1.1
356      */

357     protected void processItemEvent(ItemEvent e) {
358         ItemListener listener = itemListener;
359         if (listener != null) {
360             listener.itemStateChanged(e);
361         }
362     }
363
364     /*
365      * Post an ItemEvent and toggle state.
366      */

367     void doMenuEvent(long when, int modifiers) {
368         setState(!state);
369         Toolkit.getEventQueue().postEvent(
370             new ItemEvent(this, ItemEvent.ITEM_STATE_CHANGED,
371                           getLabel(),
372                           state ? ItemEvent.SELECTED :
373                                   ItemEvent.DESELECTED));
374     }
375
376     /**
377      * Returns a string representing the state of this
378      * <code>CheckBoxMenuItem</code>. This
379      * method is intended to be used only for debugging purposes, and the
380      * content and format of the returned string may vary between
381      * implementations. The returned string may be empty but may not be
382      * <code>null</code>.
383      *
384      * @return the parameter string of this check box menu item
385      */

386     public String JavaDoc paramString() {
387     return super.paramString() + ",state=" + state;
388     }
389
390     /* Serialization support.
391      */

392     
393     /*
394      * Serial Data Version
395      * @serial
396      */

397     private int checkboxMenuItemSerializedDataVersion = 1;
398
399     /**
400      * Writes default serializable fields to stream. Writes
401      * a list of serializable <code>ItemListeners</code>
402      * as optional data. The non-serializable
403      * <code>ItemListeners</code> are detected and
404      * no attempt is made to serialize them.
405      *
406      * @param s the <code>ObjectOutputStream</code> to write
407      * @serialData <code>null</code> terminated sequence of
408      * 0 or more pairs; the pair consists of a <code>String</code>
409      * and an <code>Object</code>; the <code>String</code> indicates
410      * the type of object and is one of the following:
411      * <code>itemListenerK</code> indicating an
412      * <code>ItemListener</code> object
413      *
414      * @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
415      * @see java.awt.Component#itemListenerK
416      * @see #readObject(ObjectInputStream)
417      */

418     private void writeObject(ObjectOutputStream JavaDoc s)
419       throws java.io.IOException JavaDoc
420     {
421       s.defaultWriteObject();
422
423       AWTEventMulticaster.save(s, itemListenerK, itemListener);
424       s.writeObject(null);
425     }
426
427     /*
428      * Reads the <code>ObjectInputStream</code> and if it
429      * isn't <code>null</code> adds a listener to receive
430      * item events fired by the <code>Checkbox</code> menu item.
431      * Unrecognized keys or values will be ignored.
432      *
433      * @param s the <code>ObjectInputStream</code> to read
434      * @serial
435      * @see removeActionListener()
436      * @see addActionListener()
437      * @see #writeObject
438      */

439     private void readObject(ObjectInputStream JavaDoc s)
440       throws ClassNotFoundException JavaDoc, IOException JavaDoc
441     {
442       s.defaultReadObject();
443
444       Object JavaDoc keyOrNull;
445       while(null != (keyOrNull = s.readObject())) {
446     String JavaDoc key = ((String JavaDoc)keyOrNull).intern();
447
448     if (itemListenerK == key)
449       addItemListener((ItemListener)(s.readObject()));
450
451     else // skip value for unrecognized key
452
s.readObject();
453       }
454     }
455
456     /**
457      * Initialize JNI field and method IDs
458      */

459     private static native void initIDs();
460
461
462 /////////////////
463
// Accessibility support
464
////////////////
465

466     /**
467      * Gets the AccessibleContext associated with this CheckboxMenuItem.
468      * For checkbox menu items, the AccessibleContext takes the
469      * form of an AccessibleAWTCheckboxMenuItem.
470      * A new AccessibleAWTCheckboxMenuItem is created if necessary.
471      *
472      * @return an AccessibleAWTCheckboxMenuItem that serves as the
473      * AccessibleContext of this CheckboxMenuItem
474      */

475     public AccessibleContext getAccessibleContext() {
476         if (accessibleContext == null) {
477             accessibleContext = new AccessibleAWTCheckboxMenuItem();
478         }
479         return accessibleContext;
480     }
481
482     /**
483      * Inner class of CheckboxMenuItem used to provide default support for
484      * accessibility. This class is not meant to be used directly by
485      * application developers, but is instead meant only to be
486      * subclassed by menu component developers.
487      * <p>
488      * This class implements accessibility support for the
489      * <code>CheckboxMenuItem</code> class. It provides an implementation
490      * of the Java Accessibility API appropriate to checkbox menu item
491      * user-interface elements.
492      */

493     protected class AccessibleAWTCheckboxMenuItem extends AccessibleAWTMenuItem
494         implements AccessibleAction, AccessibleValue
495     {
496         /*
497          * JDK 1.3 serialVersionUID
498          */

499         private static final long serialVersionUID = -1122642964303476L;
500
501         /**
502          * Get the AccessibleAction associated with this object. In the
503          * implementation of the Java Accessibility API for this class,
504      * return this object, which is responsible for implementing the
505          * AccessibleAction interface on behalf of itself.
506      *
507      * @return this object
508          */

509         public AccessibleAction getAccessibleAction() {
510             return this;
511         }
512
513         /**
514          * Get the AccessibleValue associated with this object. In the
515          * implementation of the Java Accessibility API for this class,
516      * return this object, which is responsible for implementing the
517          * AccessibleValue interface on behalf of itself.
518      *
519      * @return this object
520          */

521         public AccessibleValue getAccessibleValue() {
522             return this;
523         }
524
525         /**
526          * Returns the number of Actions available in this object.
527          * If there is more than one, the first one is the "default"
528          * action.
529          *
530          * @return the number of Actions in this object
531          */

532         public int getAccessibleActionCount() {
533             return 0; // To be fully implemented in a future release
534
}
535
536         /**
537          * Return a description of the specified action of the object.
538          *
539          * @param i zero-based index of the actions
540          */

541         public String JavaDoc getAccessibleActionDescription(int i) {
542             return null; // To be fully implemented in a future release
543
}
544
545         /**
546          * Perform the specified Action on the object
547          *
548          * @param i zero-based index of actions
549          * @return true if the action was performed; otherwise false.
550          */

551         public boolean doAccessibleAction(int i) {
552             return false; // To be fully implemented in a future release
553
}
554
555     /**
556      * Get the value of this object as a Number. If the value has not been
557      * set, the return value will be null.
558      *
559      * @return value of the object
560      * @see #setCurrentAccessibleValue
561      */

562     public Number JavaDoc getCurrentAccessibleValue() {
563         return null; // To be fully implemented in a future release
564
}
565
566     /**
567      * Set the value of this object as a Number.
568      *
569      * @return true if the value was set; otherwise false
570      * @see #getCurrentAccessibleValue
571      */

572     public boolean setCurrentAccessibleValue(Number JavaDoc n) {
573         return false; // To be fully implemented in a future release
574
}
575
576     /**
577      * Get the minimum value of this object as a Number.
578      *
579      * @return Minimum value of the object; null if this object does not
580      * have a minimum value
581      * @see #getMaximumAccessibleValue
582      */

583     public Number JavaDoc getMinimumAccessibleValue() {
584         return null; // To be fully implemented in a future release
585
}
586
587     /**
588      * Get the maximum value of this object as a Number.
589      *
590      * @return Maximum value of the object; null if this object does not
591      * have a maximum value
592      * @see #getMinimumAccessibleValue
593      */

594     public Number JavaDoc getMaximumAccessibleValue() {
595         return null; // To be fully implemented in a future release
596
}
597
598         /**
599          * Get the role of this object.
600          *
601          * @return an instance of AccessibleRole describing the role of the
602          * object
603          */

604         public AccessibleRole getAccessibleRole() {
605             return AccessibleRole.CHECK_BOX;
606         }
607
608     } // class AccessibleAWTMenuItem
609

610 }
611
Popular Tags