home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / 3rdParty / jbuilder / unsupported / JDK1.2beta3 / SOURCE / SRC.ZIP / java / awt / Choice.java < prev    next >
Encoding:
Java Source  |  1998-03-20  |  12.7 KB  |  436 lines

  1. /*
  2.  * @(#)Choice.java    1.42 98/03/18
  3.  *
  4.  * Copyright 1995-1997 by Sun Microsystems, Inc.,
  5.  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
  6.  * All rights reserved.
  7.  *
  8.  * This software is the confidential and proprietary information
  9.  * of Sun Microsystems, Inc. ("Confidential Information").  You
  10.  * shall not disclose such Confidential Information and shall use
  11.  * it only in accordance with the terms of the license agreement
  12.  * you entered into with Sun.
  13.  */
  14. package java.awt;
  15.  
  16. import java.util.*;
  17. import java.awt.peer.ChoicePeer;
  18. import java.awt.event.*;
  19. import java.io.ObjectOutputStream;
  20. import java.io.ObjectInputStream;
  21. import java.io.IOException;
  22.  
  23.  
  24. /**
  25.  * The <code>Choice</code> class presents a pop-up menu of choices. 
  26.  * The current choice is displayed as the title of the menu. 
  27.  * <p>
  28.  * The following code example produces a pop-up menu: 
  29.  * <p>
  30.  * <hr><blockquote><pre>
  31.  * Choice ColorChooser = new Choice();
  32.  * ColorChooser.add("Green");
  33.  * ColorChooser.add("Red");
  34.  * ColorChooser.add("Blue");
  35.  * </pre></blockquote><hr>
  36.  * <p>
  37.  * After this choice menu has been added to a panel, 
  38.  * it appears as follows in its normal state:
  39.  * <p>
  40.  * <img src="images-awt/Choice-1.gif"
  41.  * ALIGN=center HSPACE=10 VSPACE=7> 
  42.  * <p>
  43.  * In the picture, <code>"Green"</code> is the current choice. 
  44.  * Pushing the mouse button down on the object causes a menu to 
  45.  * appear with the current choice highlighted. 
  46.  * <p>
  47.  * @version    1.42 03/18/98
  48.  * @author     Sami Shaio
  49.  * @author     Arthur van Hoff
  50.  * @since       JDK1.0
  51.  */
  52. public class Choice extends Component implements ItemSelectable {
  53.     /**
  54.      * The items for the Choice.
  55.      */
  56.     Vector pItems;
  57.  
  58.     /** 
  59.      * The index of the current choice for this Choice.
  60.      */
  61.     int selectedIndex = -1;
  62.  
  63.     transient ItemListener itemListener;
  64.  
  65.     private static final String base = "choice";
  66.     private static int nameCounter = 0;
  67.  
  68.     /*
  69.      * JDK 1.1 serialVersionUID 
  70.      */
  71.      private static final long serialVersionUID = -4075310674757313071L;
  72.  
  73.     /** 
  74.      * Creates a new choice menu. The menu initially has no items in it. 
  75.      * <p>
  76.      * By default, the first item added to the choice menu becomes the 
  77.      * selected item, until a different selection is made by the user  
  78.      * by calling one of the <code>select</code> methods. 
  79.      * @see       java.awt.Choice#select(int)
  80.      * @see       java.awt.Choice#select(java.lang.String)
  81.      */
  82.     public Choice() {
  83.         this.name = base + nameCounter++;
  84.     pItems = new Vector();
  85.     }
  86.  
  87.     /**
  88.      * Creates the Choice's peer.  This peer allows us to change the look
  89.      * of the Choice without changing its functionality.
  90.      * @see     java.awt.Toolkit#createChoice(java.awt.Choice)
  91.      * @see     java.awt.Component#getToolkit()
  92.      */
  93.     public void addNotify() {
  94.     peer = getToolkit().createChoice(this);
  95.     super.addNotify();
  96.     }
  97.  
  98.     /**
  99.      * Returns the number of items in this <code>Choice</code> menu.
  100.      * @see     java.awt.Choice#getItem
  101.      * @since   JDK1.1
  102.      */
  103.     public int getItemCount() {
  104.     return countItems();
  105.     }
  106.  
  107.     /**
  108.      * @deprecated As of JDK version 1.1,
  109.      * replaced by <code>getItemCount()</code>.
  110.      */
  111.     public int countItems() {
  112.     return pItems.size();
  113.     }
  114.  
  115.     /**
  116.      * Gets the string at the specified index in this 
  117.      * <code>Choice</code> menu.
  118.      * @param      index the index at which to begin.
  119.      * @see        java.awt.Choice#getItemCount
  120.      */
  121.     public String getItem(int index) {
  122.     return (String)pItems.elementAt(index);
  123.     }
  124.  
  125.     /**
  126.      * Adds an item to this <code>Choice</code> menu.
  127.      * @param      item    the item to be added
  128.      * @exception  NullPointerException   if the item's value is <code>null</code>.
  129.      * @since      JDK1.1
  130.      */
  131.     public synchronized void add(String item) {
  132.     addItem(item);
  133.     }
  134.  
  135.     /**
  136.      * Adds an item to this Choice.
  137.      * @param item the item to be added
  138.      * @exception NullPointerException If the item's value is equal to null.
  139.      */
  140.     public synchronized void addItem(String item) {
  141.     if (item == null) {
  142.         throw new NullPointerException("cannot add null item to Choice");
  143.     }
  144.     pItems.addElement(item);
  145.     ChoicePeer peer = (ChoicePeer)this.peer;
  146.     if (peer != null) {
  147.         peer.addItem(item, pItems.size() - 1);
  148.     }
  149.     if (selectedIndex < 0) {
  150.         select(0);
  151.     }
  152.     }
  153.  
  154.  
  155.     /**
  156.      * Inserts the item into this choice at the specified position.
  157.      * @param item the item to be inserted
  158.      * @param index the position at which the item should be inserted
  159.      * @exception IllegalArgumentException if index is less than 0.
  160.      */
  161.  
  162.     public synchronized void insert(String item, int index) {
  163.     if (index < 0) {
  164.         throw new IllegalArgumentException("index less than zero.");
  165.     }
  166.  
  167.         int nitems = getItemCount();
  168.     Vector tempItems = new Vector();
  169.  
  170.     /* Remove the item at index, nitems-index times 
  171.        storing them in a temporary vector in the
  172.        order they appear on the choice menu.
  173.        */
  174.     for (int i = index ; i < nitems; i++) {
  175.         tempItems.addElement(getItem(index));
  176.         remove(index);
  177.     }
  178.  
  179.     add(item);
  180.  
  181.     /* Add the removed items back to the choice menu, they 
  182.        are already in the correct order in the temp vector.
  183.        */
  184.     for (int i = 0; i < tempItems.size()  ; i++) {
  185.         add((String)tempItems.elementAt(i));
  186.     }
  187.     }
  188.  
  189.     /**
  190.      * Remove the first occurrence of <code>item</code> 
  191.      * from the <code>Choice</code> menu.
  192.      * @param      item  the item to remove from this <code>Choice</code> menu.
  193.      * @exception  IllegalArgumentException  if the item doesn't 
  194.      *                     exist in the choice menu.
  195.      * @since      JDK1.1
  196.      */
  197.     public synchronized void remove(String item) {
  198.         int index = pItems.indexOf(item);
  199.         if (index < 0) {
  200.         throw new IllegalArgumentException("item " + item +
  201.                            " not found in choice");
  202.     } else {
  203.         remove(index);
  204.     }
  205.     }
  206.  
  207.     /**
  208.      * Removes an item from the choice menu 
  209.      * at the specified position.
  210.      * @param      position the position of the item.
  211.      * @since      JDK1.1
  212.      */
  213.     public synchronized void remove(int position) {
  214.         pItems.removeElementAt(position);
  215.         ChoicePeer peer = (ChoicePeer)this.peer;
  216.         if (peer != null) {
  217.         peer.remove(position);
  218.     }
  219.         /* Adjust selectedIndex if selected item was removed. */
  220.         if (pItems.size() == 0) {
  221.         selectedIndex = -1;
  222.     } else if (selectedIndex == position) {
  223.         select(0);
  224.     }
  225.     }
  226.  
  227.     /**
  228.      * Removes all items from the choice menu.
  229.      * @see       java.awt.Choice#remove
  230.      * @since     JDK1.1
  231.      */
  232.     public synchronized void removeAll() {
  233.         int nitems = getItemCount();
  234.     for (int i = 0 ; i < nitems ; i++) {
  235.         remove(0);
  236.     }
  237.     }
  238.  
  239.     /**
  240.      * Gets a representation of the current choice as a string.
  241.      * @return    a string representation of the currently 
  242.      *                     selected item in this choice menu.
  243.      * @see       java.awt.Choice#getSelectedIndex
  244.      */
  245.     public synchronized String getSelectedItem() {
  246.     return (selectedIndex >= 0) ? getItem(selectedIndex) : null;
  247.     }
  248.  
  249.     /**
  250.      * Returns an array (length 1) containing the currently selected
  251.      * item.  If this choice has no items, returns null.
  252.      * @see ItemSelectable
  253.      */
  254.     public synchronized Object[] getSelectedObjects() {
  255.     if (selectedIndex >= 0) {
  256.             Object[] items = new Object[1];
  257.             items[0] = getItem(selectedIndex);
  258.             return items;
  259.         }
  260.         return null;
  261.     }
  262.  
  263.     /**
  264.      * Returns the index of the currently selected item.
  265.      * @see #getSelectedItem
  266.      */
  267.     public int getSelectedIndex() {
  268.     return selectedIndex;
  269.     }
  270.  
  271.     /**
  272.      * Sets the selected item in this <code>Choice</code> menu to be the 
  273.      * item at the specified position. 
  274.      * @param      pos      the positon of the selected item.
  275.      * @exception  IllegalArgumentException if the specified
  276.      *                            position is invalid.
  277.      * @see        java.awt.Choice#getSelectedItem
  278.      * @see        java.awt.Choice#getSelectedIndex
  279.      */
  280.     public synchronized void select(int pos) {
  281.     if (pos >= pItems.size()) {
  282.         throw new IllegalArgumentException("illegal Choice item position: " + pos);
  283.     }
  284.     if (pItems.size() > 0) {
  285.         selectedIndex = pos;
  286.         ChoicePeer peer = (ChoicePeer)this.peer;
  287.         if (peer != null) {
  288.         peer.select(pos);
  289.         }
  290.     }
  291.     }
  292.  
  293.     /**
  294.      * Sets the selected item in this <code>Choice</code> menu 
  295.      * to be the item whose name is equal to the specified string. 
  296.      * If more than one item matches (is equal to) the specified string, 
  297.      * the one with the smallest index is selected. 
  298.      * @param       str     the specified string
  299.      * @see         java.awt.Choice#getSelectedItem
  300.      * @see         java.awt.Choice#getSelectedIndex
  301.      */
  302.     public synchronized void select(String str) {
  303.     int index = pItems.indexOf(str);
  304.     if (index >= 0) {
  305.         select(index);
  306.     }
  307.     }
  308.  
  309.     /**
  310.      * Adds the specified item listener to receive item events from
  311.      * this <code>Choice</code> menu.
  312.      * @param         l    the item listener.
  313.      * @see           java.awt.event.ItemEvent
  314.      * @see           java.awt.event.ItemListener
  315.      * @see           java.awt.Choice#removeItemListener
  316.      * @since         JDK1.1
  317.      */ 
  318.     public synchronized void addItemListener(ItemListener l) {
  319.         itemListener = AWTEventMulticaster.add(itemListener, l);
  320.         newEventsOnly = true;
  321.     }
  322.  
  323.     /**
  324.      * Removes the specified item listener so that it no longer receives 
  325.      * item events from this <code>Choice</code> menu. 
  326.      * @param         l    the item listener.
  327.      * @see           java.awt.event.ItemEvent
  328.      * @see           java.awt.event.ItemListener
  329.      * @see           java.awt.Choice#addItemListener
  330.      * @since         JDK1.1
  331.      */ 
  332.     public synchronized void removeItemListener(ItemListener l) {
  333.         itemListener = AWTEventMulticaster.remove(itemListener, l);
  334.     }
  335.  
  336.     // REMIND: remove when filtering is done at lower level
  337.     boolean eventEnabled(AWTEvent e) {
  338.         if (e.id == ItemEvent.ITEM_STATE_CHANGED) {
  339.             if ((eventMask & AWTEvent.ITEM_EVENT_MASK) != 0 ||
  340.                 itemListener != null) {
  341.                 return true;
  342.             } 
  343.             return false;
  344.         }
  345.         return super.eventEnabled(e);
  346.     }        
  347.  
  348.     /**
  349.      * Processes events on this choice. If the event is an 
  350.      * instance of <code>ItemEvent</code>, it invokes the 
  351.      * <code>processItemEvent</code> method. Otherwise, it calls its
  352.      * superclass's <code>processEvent</code> method.
  353.      * @param      e the event.
  354.      * @see        java.awt.event.ItemEvent
  355.      * @see        java.awt.Choice#processItemEvent
  356.      * @since      JDK1.1
  357.      */
  358.     protected void processEvent(AWTEvent e) {
  359.         if (e instanceof ItemEvent) {
  360.             processItemEvent((ItemEvent)e);
  361.             return;
  362.         }
  363.     super.processEvent(e);
  364.     }
  365.  
  366.     /** 
  367.      * Processes item events occurring on this <code>Choice</code> 
  368.      * menu by dispatching them to any registered 
  369.      * <code>ItemListener</code> objects. 
  370.      * <p>
  371.      * This method is not called unless item events are 
  372.      * enabled for this component. Item events are enabled 
  373.      * when one of the following occurs:
  374.      * <p><ul>
  375.      * <li>An <code>ItemListener</code> object is registered 
  376.      * via <code>addItemListener</code>.
  377.      * <li>Item events are enabled via <code>enableEvents</code>.
  378.      * </ul>
  379.      * @param       e the item event.
  380.      * @see         java.awt.event.ItemEvent
  381.      * @see         java.awt.event.ItemListener
  382.      * @see         java.awt.Choice#addItemListener
  383.      * @see         java.awt.Component#enableEvents
  384.      * @since       JDK1.1
  385.      */  
  386.     protected void processItemEvent(ItemEvent e) {
  387.         if (itemListener != null) {
  388.             itemListener.itemStateChanged(e);
  389.         }
  390.     }
  391.  
  392.     /**
  393.      * Returns the parameter string representing the state of this 
  394.      * choice menu. This string is useful for debugging. 
  395.      * @return    the parameter string of this <code>Choice</code> menu.
  396.      */
  397.     protected String paramString() {
  398.     return super.paramString() + ",current=" + getSelectedItem();
  399.     }
  400.  
  401.  
  402.     /* Serialization support. 
  403.      */
  404.  
  405.     private int choiceSerializedDataVersion = 1;
  406.  
  407.  
  408.     private void writeObject(ObjectOutputStream s)
  409.       throws java.io.IOException 
  410.     {
  411.       s.defaultWriteObject();
  412.  
  413.       AWTEventMulticaster.save(s, itemListenerK, itemListener);
  414.       s.writeObject(null);
  415.     }
  416.  
  417.  
  418.     private void readObject(ObjectInputStream s)
  419.       throws ClassNotFoundException, IOException 
  420.     {
  421.       s.defaultReadObject();
  422.  
  423.       Object keyOrNull;
  424.       while(null != (keyOrNull = s.readObject())) {
  425.     String key = ((String)keyOrNull).intern();
  426.  
  427.     if (itemListenerK == key) 
  428.       addItemListener((ItemListener)(s.readObject()));
  429.  
  430.     else // skip value for unrecognized key
  431.       s.readObject();
  432.       }
  433.     }
  434.  
  435. }
  436.