Docstoc

jcombobox & removeitemlistener & example

Document Sample
jcombobox & removeitemlistener & example Powered By Docstoc
					                                                                                        1 of 21


                                                                                       06/27/01
                JComboBox and JList common methods
                                                By
                             Sangeetha Parthasarathy




1. JComboBox:
javax.swing
Class JComboBox
java.lang.Object
  |
  +-java.awt.Component
        |
        +-java.awt.Container
              |
              +-javax.swing.JComponent
                    |
                    +-javax.swing.JComboBox



Swing's implementation of a ComboBox -- a combination of a text field and drop-down list
that lets the user either type in a value or select it from a list that is displayed when the user
asks for it. The editing capability can also be disabled so that the JComboBox acts only as a
drop down list.

JComboBox
public JComboBox(ComboBoxModel aModel)
        Creates a JComboBox that takes its items from an existing ComboBoxModel.
        Parameters:
        aModel - the ComboBoxModel that provides the displayed list of items



JComboBox
public JComboBox(Object[] items)
        Creates a JComboBox that contains the elements in the specified array.
                                                                                        2 of 21




JComboBox
public JComboBox(Vector items)
      Creates a JComboBox that contains the elements in the specified Vector.


JComboBox
public JComboBox()
      Creates a JComboBox with a default data model. The default data model is an empty
      list of objects. Use addItem to add items.


setModel
public void setModel(ComboBoxModel aModel)
      Sets the data model that the JComboBox uses to obtain the list of items.
      Parameters:
      aModel - the ComboBoxModel that provides the displayed list of items



getModel
public ComboBoxModel getModel()
      Returns the data model currently used by the JComboBox.
      Returns:
      the ComboBoxModel that provides the displayed list of items



setEditable
public void setEditable(boolean aFlag)
      Determines whether the JComboBox field is editable. An editable JComboBox allows
      the user to type into the field or selected an item from the list to initialize the field, after
      which it can be edited. (The editing affects only the field, the list item remains intact.)
      A non editable JComboBox displays the selected item inthe field, but the selection
      cannot be modified.
      Parameters:
      aFlag - a boolean value, where true indicates that the field is editable
                                                                                    3 of 21


isEditable
public boolean isEditable()
      Returns true if the JComboBox is editable.
      Returns:
      true if the JComboBox is editable, else false


setMaximumRowCount
public void setMaximumRowCount(int count)
      Sets the maximum number of rows the JComboBox displays. If the number of objects
      in the model is greater than count, the combo box uses a scrollbar.
      Parameters:
      count - an int specifying the maximum number of items to display in the list before
      using a scrollbar


getMaximumRowCount
public int getMaximumRowCount()
      Returns the maximum number of items the combo box can display without a scrollbar
      Returns:
      an int specifying the maximum number of items that are displayed in the list before
      using a scrollbar


setRenderer
public void setRenderer(ListCellRenderer aRenderer)
      Sets the renderer that paints the item selected from the list in the JComboBox field. The
      renderer is used if the JComboBox is not editable. If it is editable, the editor is used to
      render and edit the selected item.

      The default renderer displays a string, obtained by calling the selected object's
      toString method. Other renderers can handle graphic images and composite items.

      To display the selected item, aRenderer.getListCellRendererComponent is called,
      passing the list object and an index of -1.

      Parameters:
      aRenderer - the ListCellRenderer that displays the selected item.
                                                                                    4 of 21


getRenderer
public ListCellRenderer getRenderer()
      Returns the renderer used to display the selected item in the JComboBox field.
      Returns:
      the ListCellRenderer that displays the selected item.


setEditor
public void setEditor(ComboBoxEditor anEditor)
      Sets the editor used to paint and edit the selected item in the JComboBox field. The
      editor is used only if the receiving JComboBox is editable. If not editable, the combo
      box uses the renderer to paint the selected item.
      Parameters:
      anEditor - the ComboBoxEditor that displays the selected item
      See Also:
      setRenderer(javax.swing.ListCellRenderer)



getEditor
public ComboBoxEditor getEditor()
      Returns the editor used to paint and edit the selected item in the JComboBox field.
      Returns:
      the ComboBoxEditor that displays the selected item


setSelectedItem
public void setSelectedItem(Object anObject)
      Sets the selected item in the JComboBox by specifying the object in the list. If
      anObject is in the list, the list displays with anObject selected. If the object does not
      exist in the list, the default data model selects the first item in the list.
      Parameters:
      anObject - the list object to select



getSelectedItem
public Object getSelectedItem()
      Returns the currently selected item.
      Returns:
      the currently selected list object from the data model
                                                                                    5 of 21


setSelectedIndex
public void setSelectedIndex(int anIndex)
      Selects the item at index anIndex.
     Parameters:
     anIndex - an int specifying the list item to select, where 0 specifies the first item in the
     list


getSelectedIndex
public int getSelectedIndex()
     Returns the index of the currently selected item in the list. The result is not always
     defined if the JComboBox box allows selected items that are not in the list. Returns -1
     if there is no selected item or if the user specified an item which is not in the list.
     Returns:
     an int specifying the currently selected list item, where 0 specifies the first item in the
     list, or -1 if no item is selected or if the currently selected item is not in the list


addItem
public void addItem(Object anObject)
     Adds an item to the item list. This method works only if the JComboBox uses the
     default data model. JComboBox uses the default data model when created with the
     empty constructor and no other model has been set.
     Parameters:
     anObject - the Object to add to the list



insertItemAt
public void insertItemAt(Object anObject,
                         int index)
     Inserts an item into the item list at a given index. This method works only if the
     JComboBox uses the default data model. JComboBox uses the default data model when
     created with the empty constructor and no other model has been set.
     Parameters:
     anObject - the Object to add to the list
     index - an int specifying the position at which to add the item
                                                                                  6 of 21


removeItem
public void removeItem(Object anObject)
      Removes an item from the item list. This method works only if the JComboBox uses
      the default data model. JComboBox uses the default data model when created with the
      empty constructor and no other model has been set.
      Parameters:
      anObject - the object to remove from the item list



removeItemAt
public void removeItemAt(int anIndex)
      Removes the item at anIndex This method      works only if the JComboBox uses the
      default data model. JComboBox uses the default data model when created with the
      empty constructor and no other model has been set.
      Parameters:
      anIndex - an int specifying the idex of the item to remove, where 0 indicates the first
      item in the list


removeAllItems
public void removeAllItems()
      Removes all items from the item list. This method works only if the JComboBox uses
      the default data model. JComboBox uses the default data model when created with the
      empty constructor and no other model has been set.


addItemListener
public void addItemListener(ItemListener aListener)
      Adds an ItemListener. aListener will receive an event when     the selected item
      changes.
      Specified by:
      addItemListener in interface ItemSelectable
      Parameters:
      aListener - the ItemListener that is to be notified



removeItemListener
public void removeItemListener(ItemListener aListener)
      Removes an ItemListener
      Parameters:
      aListener - the ItemListener to remove
                                                                                 7 of 21




addActionListener
public void addActionListener(ActionListener l)
     Adds an ActionListener. The listener will receive an action event the user finishes
     making a selection.
     Parameters:
     l - the ActionListener that is to be notified



removeActionListener
public void removeActionListener(ActionListener l)
     Removes an ActionListener
     Parameters:
     l - the ActionListener to remove



setActionCommand
public void setActionCommand(String aCommand)
     Sets the action command that should be included in the event sent to action listeners.
     Parameters:
     aCommand - a string containing the "command" that is sent to action listeners. The same
     listener can then do different things depending on the command it receives.


getActionCommand
public String getActionCommand()
     Returns the action commnand that is included in the event sent to action listeners.
     Returns:
     the string containing the "command" that is sent to action listeners.


selectedItemChanged
protected void selectedItemChanged()
     This method is called when the selected item changes. Its default implementation
     notifies the item listeners
                                                                                  8 of 21


getSelectedObjects
public Object[] getSelectedObjects()
     Returns an array containing the selected item. This method is implemented for
     compatibility with ItemSelectable.
     Specified by:
     getSelectedObjects in interface ItemSelectable


actionPerformed
public void actionPerformed(ActionEvent e)
     This method is public as an implementation side effect. do not call or override.
     Specified by:
     actionPerformed in interface ActionListener


selectWithKeyChar
public boolean selectWithKeyChar(char keyChar)
     Selects the list item that correponds to the specified keyboard character and returns
     true, if there is an item corresponding to that character. Otherwise, returns false.
     Parameters:
     keyChar - a char, typically this is a keyboard key typed by the user



setEnabled
public void setEnabled(boolean b)
     Enables the combo box so that items can be selected. When the combo box is disabled,
     items cannot be selected and values cannot be typed into its field (if it is editable).
     Overrides:
     setEnabled in class JComponent
     Parameters:
     b - a boolean value, where true enables the component and false disables it



getItemCount
public int getItemCount()
     Returns the number of items in the list.
     Returns:
     an int equal to the number of items in the list
                                                                                          9 of 21


getItemAt
public Object getItemAt(int index)
       Returns the list item at the specified index.
       Parameters:
       index - an int indicating the list position, where the first item starts at zero
       Returns:
       the Object at that list position




2. JList:

javax.swing
Class JList
java.lang.Object
  |
  +-java.awt.Component
        |
        +-java.awt.Container
              |
              +-javax.swing.JComponent
                    |
                    +-javax.swing.JList

public class JList
extends JComponent
implements Scrollable, Accessible

A component that allows the user to select one or more objects from a list. A separate model,
ListModel, represents the contents of the list. It's easy to display an array or vector of objects,
using a JList constructor that builds an ListModel instance for you:

 // Create a JList that displays the strings in data[]

 String[] data = {"one", "two", "free", "four"};
 JList dataList = new JList(data);

 // The value of the JList model property is an object that provides
 // a read-only view of the data. It was constructed automatically.

 for(int i = 0; i < dataList.getModel().getSize(); i) {
     System.out.println(dataList.getModel().getElementAt(i));
 }
                                                                                    10 of 21




JList  uses a java.awt.Component, provided by a delegate called the cellRendererer, to
paint the visible cells in the list. The cell renderer component is used like a "rubber stamp" to
paint each visible row. Each time the JList needs to paint a cell it asks the cell renderer for the
component, moves it into place using setBounds() and then draws it by calling its paint
method. The default cell renderer uses a JLabel component to render the string value of each
component. You can substitute your own cell renderer, using code like this:

     // Display an icon and a string for each object in the list.

 class MyCellRenderer extends JLabel implements ListCellRenderer {
     final static ImageIcon longIcon = new ImageIcon("long.gif");
     final static ImageIcon shortIcon = new ImageIcon("short.gif");

        // This is the only method defined by ListCellRenderer.                 We just
        // reconfigure the Jlabel each time we're called.

        public Component getListCellRendererComponent(
          JList list,
          Object value,            // value to display
          int index,               // cell index
          boolean isSelected,      // is the cell selected
          boolean cellHasFocus)    // the list and the cell have the focus
        {
            String s = value.toString();
            setText(s);
            setIcon((s.length() > 10) ? longIcon : shortIcon);
              if (isSelected) {
                setBackground(list.getSelectionBackground());
                  setForeground(list.getSelectionForeground());
              }
            else {
                  setBackground(list.getBackground());
                  setForeground(list.getForeground());
              }
              setEnabled(list.isEnabled());
              setFont(list.getFont());
            return this;
        }
 }

 String[] data = {"one", "two", "free", "four"};
 JList dataList = new JList(data);
 dataList.setCellRenderer(new MyCellRenderer());


JListdoesn't provide any special support for handling double or triple (or N) mouse clicks
however it's easy to handle them using a MouseListener. Use the JList method
locationToIndex() to determine what cell was clicked. For example:

 final JList list = new JList(dataModel);
 MouseListener mouseListener = new MouseAdapter() {
     public void mouseClicked(MouseEvent e) {
                                                                                    11 of 21

           if (e.getClickCount() == 2) {
               int index = list.locationToIndex(e.getPoint());
               System.out.println("Double clicked on Item " index);
            }
     }
 };
 list.addMouseListener(mouseListener);

Note that in this example the JList variable is final because it's referred to by the anonymous
MouseListener class.



JList
public JList(ListModel dataModel)
        Construct a JList that displays the elements in the specified, non-null model. All JList
        constructors delegate to this one.


JList
public JList(Object[] listData)
        Construct a JList that displays the elements in the specified array. This constructor just
        delegates to the ListModel constructor.


JList
public JList(Vector listData)
        Construct a JList that displays the elements in the specified Vector. This constructor
        just delegates to the ListModel constructor.


JList
public JList()
        Constructs a JList with an empty model.

Method Detail


getFixedCellWidth
public int getFixedCellWidth()
        Returns the fixed cell width value -- the value specified by setting the fixedCellWidth
        property, rather than calculated from the list elements.
                                                                                    12 of 21


     Returns:
     the fixed cell width


setFixedCellWidth
public void setFixedCellWidth(int width)
     If this value is greater than zero it defines the width of every cell in the list. Otherwise
     cell widths are computed by applying getPreferredSize() to the cellRenderer component
     for each list element.

     The default value of this property is -1.

     This is a JavaBeans bound property.

     Parameters:
     the - width for all cells in this list




getFixedCellHeight
public int getFixedCellHeight()
     Returns the fixed cell width value -- the value specified by setting the fixedCellHeight
     property, rather than calculated from the list elements.
     Returns:
     the fixed cell height


setFixedCellHeight
public void setFixedCellHeight(int height)
     If this value is greater than zero it defines the height of every cell in the list. Otherwise
     cell heights are computed by applying getPreferredSize() to the cellRenderer
     component for each list element.

     The default value of this property is -1.

     This is a JavaBeans bound property.

     Parameters:
     height - an int giving the height in pixels for all cells in this list
                                                                                   13 of 21


getCellRenderer
public ListCellRenderer getCellRenderer()
     Returns the object that renders the list items.
     Returns:
     the ListCellRenderer


setCellRenderer
public void setCellRenderer(ListCellRenderer cellRenderer)
     Sets the delegate that's used to paint each cell in the list. If prototypeCellValue was set
     then the fixedCellWidth and fixedCellHeight properties are set as well. Only one
     PropertyChangeEvent is generated however - for the "cellRenderer" property.

     The default value of this property is provided by the ListUI delegate, i.e. by the look
     and feel implementation.

     This is a JavaBeans bound property.

     Parameters:
     cellRenderer    - the ListCellRenderer that paints list cells


getSelectionForeground
public Color getSelectionForeground()
     Returns the foreground color.
     Returns:
     the Color object for the foreground property


setSelectionForeground
public void setSelectionForeground(Color selectionForeground)
     Set the foreground color for selected cells. Cell renderers can use this color to render
     text and graphics for selected cells.

     The default value of this property is defined by the look and feel implementation.

     This is a JavaBeans bound property.

     Parameters:
     selectionForeground      - the Color to use in the foreground for selected list items
                                                                                  14 of 21




getSelectionBackground
public Color getSelectionBackground()
     Returns the background color for selected cells.
     Returns:
     the Color used for the background of selected list items


setSelectionBackground
public void setSelectionBackground(Color selectionBackground)
     Set the background color for selected cells. Cell renderers can use this color to the fill
     selected cells.

     The default value of this property is defined by the look and feel implementation.

     This is a JavaBeans bound property.

     Parameters:
     selectionBackground      - the Color to use for the background of selected cells


getVisibleRowCount
public int getVisibleRowCount()
     Return the preferred number of visible rows.
     Returns:
     an int indicating the preferred number of rows to display without using a scrollbar


setVisibleRowCount
public void setVisibleRowCount(int visibleRowCount)
     Set the preferred number of rows in the list that can be displayed without a scollbar, as
     determined by the nearest JViewport ancestor, if any. The value of this property only
     affects the value of the JLists preferredScrollableViewportSize. The default value of
     this property is 8.

     This is a JavaBeans bound property.
                                                                                     15 of 21


      Parameters:

      visibleRowCount     - an int specifying the preferred number of visible rows


getFirstVisibleIndex
public int getFirstVisibleIndex()
      Return the index of the cell in the upper left corner of the JList or -1 if nothing is visible
      or the list is empty. Note that this cell may only be partially visible.
      Returns:
      an int -- the index of the first visible cell.


getLastVisibleIndex
public int getLastVisibleIndex()
      Return the index of the cell in the lower right corner of the JList or -1 if nothing is
      visible or the list is empty. Note that this cell may only be partially visible.
      Returns:
      an int -- the index of the last visible cell.


getModel
public ListModel getModel()
      Returns the data model that holds the list of items displayed by the JList component.
      Returns:
      the ListModel that provides the displayed list of items


setModel
public void setModel(ListModel model)
      Sets the model that represents the contents or "value" of the list and clears the list
      selection after notifying PropertyChangeListeners.

      This is a JavaBeans bound property.

      Parameters:
      model - the ListModel that provides the list of items for display
                                                                                 16 of 21


setListData
public void setListData(Object[] listData)
     A convenience method that constructs a ListModel from an array of Objects and then
     applies setModel to it.
     Parameters:
     listData - an array of Objects containing the items to display in the list



setListData
public void setListData(Vector listData)
     A convenience method that constructs a ListModel from a Vector and then applies
     setModel to it.
     Parameters:
     listData - a Vector containing the items to display in the list



getSelectionModel
public ListSelectionModel getSelectionModel()
     Returns the value of the current selection model. The selection model handles the task
     of making single selections, selections of contiguous ranges, and non-contiguous
     selections.
     Returns:
     the ListSelectionModel that implements list selections


addListSelectionListener
public void addListSelectionListener(ListSelectionListener listener)
     Add a listener to the list that's notified each time a change to the selection occurs.
     Listeners added directly to the JList will have their ListSelectionEvent.getSource() ==
     this JList (instead of the ListSelectionModel).
     Parameters:
     listener - The ListSelectionListener to add.



removeListSelectionListener
public void removeListSelectionListener(ListSelectionListener listener)
     Remove a listener from the list that's notified each time a change to the selection
     occurs.
     Parameters:
     listener - The ListSelectionListener to remove.
                                                                                  17 of 21


setSelectionModel
public void setSelectionModel(ListSelectionModel selectionModel)
     Set the selectionModel for the list to a non-null ListSelectionModel implementation.
     The selection model handles the task of making single selections, selections of
     contiguous ranges, and non-contiguous selections.

     This is a JavaBeans bound property.

     Returns:
     selectionModel the ListSelectionModel that implements list selections


setSelectionMode
public void setSelectionMode(int selectionMode)
     Determines whether single-item or multiple-item selections are allowed. The following
     selectionMode values are allowed:

           SINGLE_SELECTION      Only one list index can be selected at a time. In this mode
            the setSelectionInterval and addSelectionInterval methods are equivalent, and
            they only the first index argument is used.
           SINGLE_INTERVAL_SELECTION One contiguous index interval can be selected at
            a time. In this mode setSelectionInterval and addSelectionInterval are
            equivalent.
           MULTIPLE_INTERVAL_SELECTION In this mode, there's no restriction on what
            can be selected.

     Parameters:
     selectionMode    - an int specifying the type of selections that are permissible


getSelectionMode
public int getSelectionMode()
     Returns whether single-item or multiple-item selections are allowed.
     Returns:
     The value of the selectionMode property.


getAnchorSelectionIndex
public int getAnchorSelectionIndex()
     Returns the first index argument from the most recent addSelectionInterval or
     setSelectionInterval call. This is a convenience method that just delegates to the
     selectionModel.
                                                                                  18 of 21


      Returns:
      The index that most recently anchored an interval selection.


getLeadSelectionIndex
public int getLeadSelectionIndex()
      Returns the second index argument from the most recent addSelectionInterval or
      setSelectionInterval call. This is a convenience method that just delegates to the
      selectionModel.
      Returns:
      The index that most recently ended a interval selection.


getMinSelectionIndex
public int getMinSelectionIndex()
      Returns the smallest selected cell index. This is a convenience method that just
      delegates to the selectionModel.
      Returns:
      The smallest selected cell index.


getMaxSelectionIndex
public int getMaxSelectionIndex()
      Returns the largest selected cell index. This is a convenience method that just delegates
      to the selectionModel.
      Returns:
      The largest selected cell index.


isSelectedIndex
public boolean isSelectedIndex(int index)
      Returns true if the specified index is selected. This is a convenience method that just
      delegates to the selectionModel.
      Returns:
      True if the specified index is selected.


isSelectionEmpty
public boolean isSelectionEmpty()
      Returns true if nothing is selected This is a convenience method that just delegates to
      the selectionModel.
                                                                                   19 of 21


      Returns:
      True if nothing is selected


clearSelection
public void clearSelection()
      Clears the selection - after calling this method isSelectionEmpty() will return true. This
      is a convenience method that just delegates to the selectionModel.


setSelectionInterval
public void setSelectionInterval(int anchor,
                                 int lead)
      Select the specified interval. Both the anchor and lead indices are included. It's not
      neccessary for anchor to be less than lead. This is a convenience method that just
      delegates to the selectionModel.
      Parameters:
      anchor - The first index to select
      lead - The last index to select



addSelectionInterval
public void addSelectionInterval(int anchor,
                                 int lead)
      Set the selection to be the union of the specified interval with current selection. Both
      the anchor and lead indices are included. It's not neccessary for anchor to be less than
      lead. This is a convenience method that just delegates to the selectionModel.
      Parameters:
      anchor - The first index to add to the selection
      lead - The last index to add to the selection



removeSelectionInterval
public void removeSelectionInterval(int index0,
                                    int index1)
      Set the selection to be the set difference of the specified interval and the current
      selection. Both the anchor and lead indices are removed. It's not neccessary for anchor
      to be less than lead. This is a convenience method that just delegates to the
      selectionModel.
      Parameters:
      anchor - The first index to remove from the selection
      lead - The last index to remove from the selection
                                                                                   20 of 21


getSelectedIndices
public int[] getSelectedIndices()
      Return an array of all of the selected indices in increasing order.
      Returns:
      All of the selected indices, in increasing order.


setSelectedIndex
public void setSelectedIndex(int index)
      Select a single cell.
      Parameters:
      index - The index of the one cell to select



setSelectedIndices
public void setSelectedIndices(int[] indices)
      Select a set of cells.
      Parameters:
      indices - The indices of the cells to select



getSelectedValues
public Object[] getSelectedValues()
      Return an array of the values for the selected cells. The returned values are sorted in
      increasing index order.
      Returns:
      the selected values


getSelectedIndex
public int getSelectedIndex()
      A convenience method that returns the first selected index. Returns -1 if there is no
      selected item.
      Returns:
      The first selected index.


getSelectedValue
public Object getSelectedValue()
      A convenience method that returns the first selected value or null, if the selection is
      empty.
                                                                                    21 of 21


     Returns:
     The first selected value.


setSelectedValue
public void setSelectedValue(Object anObject,
                             boolean shouldScroll)
     Selects the specified object from the list.
     Parameters:
     anObject - the Object to select
     shouldScroll - true if the list should scroll to display the selected object

				
DOCUMENT INFO
Shared By:
Stats:
views:64
posted:3/17/2009
language:English
pages:21