API java : JList


javax.swing
Class JList

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by javax.swing.JList
All Implemented Interfaces:
ImageObserver, MenuContainer, Serializable, Accessible, Scrollable

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 a ListModel instance for you:

  1. // Create a JList that displays the strings in data[]
  2.  
  3. String[] data = {"one", "two", "three", "four"};
  4. JList dataList = new JList(data);
  5.  
  6. // The value of the JList model property is an object that provides
  7. // a read-only view of the data. It was constructed automatically.
  8.  
  9. for(int i = 0; i < dataList.getModel().getSize(); i++) {
  10. System.out.println(dataList.getModel().getElementAt(i));
  11. }
  12.  
  13. // Create a JList that displays the superclass of JList.class.
  14. // We store the superclasses in a java.util.Vector.
  15.  
  16. Vector superClasses = new Vector();
  17. Class rootClass = javax.swing.JList.class;
  18. for(Class cls = rootClass; cls != null; cls = cls.getSuperclass()) {
  19. superClasses.addElement(cls);
  20. }
  21. JList classList = new JList(superClasses);

JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane. For example:

  1. JScrollPane scrollPane = new JScrollPane(dataList);
  2. // Or in two steps:
  3. JScrollPane scrollPane = new JScrollPane();
  4. scrollPane.getViewport().setView(dataList);

By default the JList selection model allows any combination of items to be selected at a time, using the constant MULTIPLE_INTERVAL_SELECTION. The selection state is actually managed by a separate delegate object, an instance of ListSelectionModel. However JList provides convenient properties for managing the selection.

  1. String[] data = {"one", "two", "three", "four"};
  2. JList dataList = new JList(data);
  3.  
  4. dataList.setSelectedIndex(1); // select "two"
  5. dataList.getSelectedValue(); // returns "two"

The contents of a JList can be dynamic, in other words, the list elements can change value and the size of the list can change after the JList has been created. The JList observes changes in its model with a swing.event.ListDataListener implementation. A correct implementation of ListModel notifies it's listeners each time a change occurs. The changes are characterized by a swing.event.ListDataEvent, which identifies the range of list indices that have been modified, added, or removed. Simple dynamic-content JList applications can use the DefaultListModel class to store list elements. This class implements the ListModel interface and provides the java.util.Vector API as well. Applications that need to provide custom ListModel implementations can subclass AbstractListModel, which provides basic ListDataListener support. For example:

  1. // This list model has about 2^16 elements. Enjoy scrolling.
  2.  
  3. <a name="prototype_example">
  4. ListModel bigData = new AbstractListModel() {
  5. public int getSize() { return Short.MAX_VALUE; }
  6. public Object getElementAt(int index) { return "Index " + index; }
  7. };
  8.  
  9. JList bigDataList = new JList(bigData);
  10.  
  11. // We don't want the JList implementation to compute the width
  12. // or height of all of the list cells, so we give it a string
  13. // that's as big as we'll need for any cell. It uses this to
  14. // compute values for the fixedCellWidth and fixedCellHeight
  15. // properties.
  16.  
  17. bigDataList.setPrototypeCellValue("Index 1234567890");

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:

  1. // Display an icon and a string for each object in the list.
  2.  
  3. <a name="cellrenderer_example">
  4. class MyCellRenderer extends JLabel implements ListCellRenderer {
  5. final static ImageIcon longIcon = new ImageIcon("long.gif");
  6. final static ImageIcon shortIcon = new ImageIcon("short.gif");
  7.  
  8. // This is the only method defined by ListCellRenderer.
  9. // We just reconfigure the JLabel each time we're called.
  10.  
  11. public Component getListCellRendererComponent(
  12. JList list,
  13. Object value, // value to display
  14. int index, // cell index
  15. boolean isSelected, // is the cell selected
  16. boolean cellHasFocus) // the list and the cell have the focus
  17. {
  18. String s = value.toString();
  19. setText(s);
  20. setIcon((s.length() > 10) ? longIcon : shortIcon);
  21. if (isSelected) {
  22. setBackground(list.getSelectionBackground());
  23. setForeground(list.getSelectionForeground());
  24. }
  25. else {
  26. setBackground(list.getBackground());
  27. setForeground(list.getForeground());
  28. }
  29. setEnabled(list.isEnabled());
  30. setFont(list.getFont());
  31. setOpaque(true);
  32. return this;
  33. }
  34. }
  35.  
  36. String[] data = {"one", "two", "three", "four"};
  37. JList dataList = new JList(data);
  38. dataList.setCellRenderer(new MyCellRenderer());

JList doesn'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:

  1. final JList list = new JList(dataModel);
  2. MouseListener mouseListener = new MouseAdapter() {
  3. public void mouseClicked(MouseEvent e) {
  4. if (e.getClickCount() == 2) {
  5. int index = list.locationToIndex(e.getPoint());
  6. System.out.println("Double clicked on Item " + index);
  7. }
  8. }
  9. };
  10. list.addMouseListener(mouseListener);
Note that in this example the dataList is final because it's referred to by the anonymous MouseListener class.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

See How to Use Lists in The Java Tutorial for further documentation. Also see the article Advanced JList Programming in The Swing Connection.

See Also:
ListModel, AbstractListModel, DefaultListModel, ListSelectionModel, DefaultListSelectionModel, ListCellRenderer

Nested Class Summary
protected  class JList.AccessibleJList
          This class implements accessibility support for the JList class.
 
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
 
Field Summary
static int HORIZONTAL_WRAP
          Indicates "newspaper style" with the cells flowing horizontally then vertically.
static int VERTICAL
          Indicates the default layout: one column of cells.
static int VERTICAL_WRAP
          Indicates "newspaper style" layout with the cells flowing vertically then horizontally.
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
JList()
          Constructs a JList with an empty model.
JList(ListModel dataModel)
          Constructs a JList that displays the elements in the specified, non-null model.
JList(Object[] listData)
          Constructs a JList that displays the elements in the specified array.
JList(Vector<?> listData)
          Constructs a JList that displays the elements in the specified Vector.
 
Method Summary
 void addListSelectionListener(ListSelectionListener listener)
          Adds a listener to the list that's notified each time a change to the selection occurs.
 void addSelectionInterval(int anchor, int lead)
          Sets the selection to be the union of the specified interval with current selection.
 void clearSelection()
          Clears the selection - after calling this method isSelectionEmpty will return true.
protected  ListSelectionModel createSelectionModel()
          Returns an instance of DefaultListSelectionModel.
 void ensureIndexIsVisible(int index)
          Scrolls the viewport to make the specified cell completely visible.
protected  void fireSelectionValueChanged(int firstIndex, int lastIndex, boolean isAdjusting)
          Notifies JList ListSelectionListeners that the selection model has changed.
 AccessibleContext getAccessibleContext()
          Gets the AccessibleContext associated with this JList.
 int getAnchorSelectionIndex()
          Returns the first index argument from the most recent addSelectionModel or setSelectionInterval call.
 Rectangle getCellBounds(int index0, int index1)
          Returns the bounds of the specified range of items in JList coordinates.
 ListCellRenderer getCellRenderer()
          Returns the object that renders the list items.
 boolean getDragEnabled()
          Gets the dragEnabled property.
 int getFirstVisibleIndex()
          Returns the index of the first visible cell.
 int getFixedCellHeight()
          Returns the fixed cell height value -- the value specified by setting the fixedCellHeight property, rather than that calculated from the list elements.
 int getFixedCellWidth()
          Returns the fixed cell width value -- the value specified by setting the fixedCellWidth property, rather than that calculated from the list elements.
 int getLastVisibleIndex()
          Returns the index of the last visible cell.
 int getLayoutOrientation()
          Returns JList.VERTICAL if the layout is a single column of cells, or JList.VERTICAL_WRAP if the layout is "newspaper style" with the content flowing vertically then horizontally or JList.HORIZONTAL_WRAP if the layout is "newspaper style" with the content flowing horizontally then vertically.
 int getLeadSelectionIndex()
          Returns the second index argument from the most recent addSelectionInterval or setSelectionInterval call.
 ListSelectionListener[] getListSelectionListeners()
          Returns an array of all the ListSelectionListeners added to this JList with addListSelectionListener().
 int getMaxSelectionIndex()
          Returns the largest selected cell index.
 int getMinSelectionIndex()
          Returns the smallest selected cell index.
 ListModel getModel()
          Returns the data model that holds the list of items displayed by the JList component.
 int getNextMatch(String prefix, int startIndex, Position.Bias bias)
          Returns the next list element that starts with a prefix.
 Dimension getPreferredScrollableViewportSize()
          Computes the size of the viewport needed to display visibleRowCount rows.
 Object getPrototypeCellValue()
          Returns the cell width of the "prototypical cell" -- a cell used for the calculation of cell widths, because it has the same value as all other list items.
 int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
          Returns the distance to scroll to expose the next or previous block.
 boolean getScrollableTracksViewportHeight()
          Returns true if this JList is displayed in a JViewport and the viewport is taller than JList's preferred height, or if the layout orientation is VERTICAL_WRAP and the number of visible rows is <= 0; otherwise returns false.
 boolean getScrollableTracksViewportWidth()
          Returns true if this JList is displayed in a JViewport and the viewport is wider than JList's preferred width; or if the layout orientation is HORIZONTAL_WRAP and the visible row count is <= 0; otherwise returns false.
 int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
          Returns the distance to scroll to expose the next or previous row (for vertical scrolling) or column (for horizontal scrolling).
 int getSelectedIndex()
          Returns the first selected index; returns -1 if there is no selected item.
 int[] getSelectedIndices()
          Returns an array of all of the selected indices in increasing order.
 Object getSelectedValue()
          Returns the first selected value, or null if the selection is empty.
 Object[] getSelectedValues()
          Returns an array of the values for the selected cells.
 Color getSelectionBackground()
          Returns the background color for selected cells.
 Color getSelectionForeground()
          Returns the selection foreground color.
 int getSelectionMode()
          Returns whether single-item or multiple-item selections are allowed.
 ListSelectionModel getSelectionModel()
          Returns the value of the current selection model.
 String getToolTipText(MouseEvent event)
          Overrides JComponent's getToolTipText method in order to allow the renderer's tips to be used if it has text set.
 ListUI getUI()
          Returns the look and feel (L&F) object that renders this component.
 String getUIClassID()
          Returns the suffix used to construct the name of the look and feel (L&F) class used to render this component.
 boolean getValueIsAdjusting()
          Returns the value of the data model's isAdjusting property.
 int getVisibleRowCount()
          Returns the preferred number of visible rows.
 Point indexToLocation(int index)
          Returns the origin of the specified item in JList coordinates.
 boolean isSelectedIndex(int index)
          Returns true if the specified index is selected.
 boolean isSelectionEmpty()
          Returns true if nothing is selected.
 int locationToIndex(Point location)
          Convert a point in JList coordinates to the closest index of the cell at that location.
protected  String paramString()
          Returns a string representation of this JList.
 void removeListSelectionListener(ListSelectionListener listener)
          Removes a listener from the list that's notified each time a change to the selection occurs.
 void removeSelectionInterval(int index0, int index1)
          Sets the selection to be the set difference of the specified interval and the current selection.
 void setCellRenderer(ListCellRenderer cellRenderer)
          Sets the delegate that's used to paint each cell in the list.
 void setDragEnabled(boolean b)
          Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component.
 void setFixedCellHeight(int height)
          Sets the height of every cell in the list.
 void setFixedCellWidth(int width)
          Sets the width of every cell in the list.
 void setLayoutOrientation(int layoutOrientation)
          Defines the way list cells are layed out.
 void setListData(Object[] listData)
          Constructs a ListModel from an array of objects and then applies setModel to it.
 void setListData(Vector<?> listData)
          Constructs a ListModel from a Vector and then applies setModel to it.
 void setModel(ListModel model)
          Sets the model that represents the contents or "value" of the list and clears the list selection after notifying PropertyChangeListeners.
 void setPrototypeCellValue(Object prototypeCellValue)
          Computes the fixedCellWidth and fixedCellHeight properties by configuring the cellRenderer to index equals zero for the specified value and then computing the renderer component's preferred size.
 void setSelectedIndex(int index)
          Selects a single cell.
 void setSelectedIndices(int[] indices)
          Selects a set of cells.
 void setSelectedValue(Object anObject, boolean shouldScroll)
          Selects the specified object from the list.
 void setSelectionBackground(Color selectionBackground)
          Sets the background color for selected cells.
 void setSelectionForeground(Color selectionForeground)
          Sets the foreground color for selected cells.
 void setSelectionInterval(int anchor, int lead)
          Selects the specified interval.
 void setSelectionMode(int selectionMode)
          Determines whether single-item or multiple-item selections are allowed.
 void setSelectionModel(ListSelectionModel selectionModel)
          Sets the selectionModel for the list to a non-null ListSelectionModel implementation.
 void setUI(ListUI ui)
          Sets the look and feel (L&F) object that renders this component.
 void setValueIsAdjusting(boolean b)
          Sets the data model's isAdjusting property to true, so that a single event will be generated when all of the selection events have finished (for example, when the mouse is being dragged over the list in selection mode).
 void setVisibleRowCount(int visibleRowCount)
          Sets the preferred number of rows in the list that can be displayed without a scrollbar, as determined by the nearest JViewport ancestor, if any.
 void updateUI()
          Resets the UI property with the value from the current look and feel.
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

VERTICAL

public static final int VERTICAL
Indicates the default layout: one column of cells.

Since:
1.4
See Also:
setLayoutOrientation(int), Constant Field Values

VERTICAL_WRAP

public static final int VERTICAL_WRAP
Indicates "newspaper style" layout with the cells flowing vertically then horizontally.

Since:
1.4
See Also:
setLayoutOrientation(int), Constant Field Values

HORIZONTAL_WRAP

public static final int HORIZONTAL_WRAP
Indicates "newspaper style" with the cells flowing horizontally then vertically.

Since:
1.4
See Also:
setLayoutOrientation(int), Constant Field Values
Constructor Detail

JList

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

Parameters:
dataModel - the data model for this list
Throws:
IllegalArgumentException - if dataModel is null

JList

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

Parameters:
listData - the array of Objects to be loaded into the data model

JList

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

Parameters:
listData - the Vector to be loaded into the data model

JList

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

Method Detail

getUI

public ListUI getUI()
Returns the look and feel (L&F) object that renders this component.

Returns:
the ListUI object that renders this component

setUI

public void setUI(ListUI ui)
Sets the look and feel (L&F) object that renders this component.

Parameters:
ui - the ListUI L&F object
See Also:
UIDefaults.getUI(javax.swing.JComponent)

updateUI

public void updateUI()
Resets the UI property with the value from the current look and feel.

Overrides:
updateUI in class JComponent
See Also:
UIManager.getUI(javax.swing.JComponent)

getUIClassID

public String getUIClassID()
Returns the suffix used to construct the name of the look and feel (L&F) class used to render this component.

Overrides:
getUIClassID in class JComponent
Returns:
the string "ListUI"
See Also:
JComponent.getUIClassID(), UIDefaults.getUI(javax.swing.JComponent)

getPrototypeCellValue

public Object getPrototypeCellValue()
Returns the cell width of the "prototypical cell" -- a cell used for the calculation of cell widths, because it has the same value as all other list items.

Returns:
the value of the prototypeCellValue property
See Also:
setPrototypeCellValue(java.lang.Object)

setPrototypeCellValue

public void setPrototypeCellValue(Object prototypeCellValue)
Computes the fixedCellWidth and fixedCellHeight properties by configuring the cellRenderer to index equals zero for the specified value and then computing the renderer component's preferred size. These properties are useful when the list is too long to allow JList to compute the width/height of each cell and there is a single cell value that is known to occupy as much space as any of the others.

Note that we do set the fixedCellWidth and fixedCellHeight properties here but only a prototypeCellValue PropertyChangeEvent is fired.

To see an example which sets this property, see the class description above.

The default value of this property is null.

This is a JavaBeans bound property.

Parameters:
prototypeCellValue - the value on which to base fixedCellWidth and fixedCellHeight
See Also:
getPrototypeCellValue(), setFixedCellWidth(int), setFixedCellHeight(int), Container.addPropertyChangeListener(java.beans.PropertyChangeListener)

getFixedCellWidth

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

Returns:
the fixed cell width
See Also:
setFixedCellWidth(int)

setFixedCellWidth

public void setFixedCellWidth(int width)
Sets the width of every cell in the list. If width is -1, 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:
width - the width, in pixels, for all cells in this list
See Also:
getPrototypeCellValue(), setFixedCellWidth(int), Container.addPropertyChangeListener(java.beans.PropertyChangeListener)

getFixedCellHeight

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

Returns:
the fixed cell height, in pixels
See Also:
setFixedCellHeight(int)

setFixedCellHeight

public void setFixedCellHeight(int height)
Sets the height of every cell in the list. If height is -1, 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 integer giving the height, in pixels, for all cells in this list
See Also:
getPrototypeCellValue(), setFixedCellWidth(int), Container.addPropertyChangeListener(java.beans.PropertyChangeListener)

getCellRenderer

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

Returns:
the ListCellRenderer
See Also:
setCellRenderer(javax.swing.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.

To see an example which sets the cell renderer, see the class description above.

This is a JavaBeans bound property.

Parameters:
cellRenderer - the ListCellRenderer that paints list cells
See Also:
getCellRenderer()

getSelectionForeground

public Color getSelectionForeground()
Returns the selection foreground color.

Returns:
the Color object for the foreground property
See Also:
setSelectionForeground(java.awt.Color), setSelectionBackground(java.awt.Color)

setSelectionForeground

public void setSelectionForeground(Color selectionForeground)
Sets 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
See Also:
getSelectionForeground(), setSelectionBackground(java.awt.Color), JComponent.setForeground(java.awt.Color), JComponent.setBackground(java.awt.Color), JComponent.setFont(java.awt.Font)

getSelectionBackground

public Color getSelectionBackground()
Returns the background color for selected cells.

Returns:
the Color used for the background of selected list items
See Also:
setSelectionBackground(java.awt.Color), setSelectionForeground(java.awt.Color)

setSelectionBackground

public void setSelectionBackground(Color selectionBackground)
Sets 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
See Also:
getSelectionBackground(), setSelectionForeground(java.awt.Color), JComponent.setForeground(java.awt.Color), JComponent.setBackground(java.awt.Color), JComponent.setFont(java.awt.Font)

getVisibleRowCount

public int getVisibleRowCount()
Returns the preferred number of visible rows.

Returns:
an integer indicating the preferred number of rows to display without using a scroll bar
See Also:
setVisibleRowCount(int)

setVisibleRowCount

public void setVisibleRowCount(int visibleRowCount)
Sets the preferred number of rows in the list that can be displayed without a scrollbar, as determined by the nearest JViewport ancestor, if any. The value of this property only affects the value of the JList's preferredScrollableViewportSize.

The default value of this property is 8.

This is a JavaBeans bound property.

Parameters:
visibleRowCount - an integer specifying the preferred number of visible rows
See Also:
getVisibleRowCount(), JComponent.getVisibleRect(), JViewport

getLayoutOrientation

public int getLayoutOrientation()
Returns JList.VERTICAL if the layout is a single column of cells, or JList.VERTICAL_WRAP if the layout is "newspaper style" with the content flowing vertically then horizontally or JList.HORIZONTAL_WRAP if the layout is "newspaper style" with the content flowing horizontally then vertically.

Returns:
the value of the layoutOrientation property
Since:
1.4
See Also:
setLayoutOrientation(int)

setLayoutOrientation

public void setLayoutOrientation(int layoutOrientation)
Defines the way list cells are layed out. Consider a JList with four cells, this can be layed out in one of the following ways:
  1. 0
  2. 1
  3. 2
  4. 3
  1. 0 1
  2. 2 3
  1. 0 2
  2. 1 3

These correspond to the following values:

Value

Description

JList.VERTICAL The cells should be layed out vertically in one column.
JList.HORIZONTAL_WRAP The cells should be layed out horizontally, wrapping to a new row as necessary. The number of rows to use will either be defined by getVisibleRowCount if > 0, otherwise the number of rows will be determined by the width of the JList.
JList.VERTICAL_WRAP The cells should be layed out vertically, wrapping to a new column as necessary. The number of rows to use will either be defined by getVisibleRowCount if > 0, otherwise the number of rows will be determined by the height of the JList.
The default value of this property is JList.VERTICAL.

This will throw an IllegalArgumentException if layoutOrientation is not one of JList.HORIZONTAL_WRAP or JList.VERTICAL or JList.VERTICAL_WRAP

Parameters:
layoutOrientation - New orientation, one of JList.HORIZONTAL_WRAP, JList.VERTICAL or JList.VERTICAL_WRAP.
Since:
1.4
See Also:
getLayoutOrientation(), setVisibleRowCount(int), getScrollableTracksViewportHeight()

getFirstVisibleIndex

public int getFirstVisibleIndex()
Returns the index of the first visible cell. The cell considered to be "first" depends on the list's componentOrientation property. If the orientation is horizontal left-to-right, then the first visible cell is in the list's upper-left corner. If the orientation is horizontal right-to-left, then the first visible cell is in the list's upper-right corner. If nothing is visible or the list is empty, a -1 is returned. Note that the returned cell may only be partially visible.

Returns:
the index of the first visible cell
See Also:
getLastVisibleIndex(), JComponent.getVisibleRect()

getLastVisibleIndex

public int getLastVisibleIndex()
Returns the index of the last visible cell. The cell considered to be "last" depends on the list's componentOrientation property. If the orientation is horizontal left-to-right, then the last visible cell is in the JList's lower-right corner. If the orientation is horizontal right-to-left, then the last visible cell is in the JList's lower-left corner. If nothing is visible or the list is empty, a -1 is returned. Note that the returned cell may only be partially visible.

Returns:
the index of the last visible cell
See Also:
getFirstVisibleIndex(), JComponent.getVisibleRect()

ensureIndexIsVisible

public void ensureIndexIsVisible(int index)
Scrolls the viewport to make the specified cell completely visible. Note, for this method to work, the JList must be displayed within a JViewport.

Parameters:
index - the index of the cell to make visible
See Also:
JComponent.scrollRectToVisible(java.awt.Rectangle), JComponent.getVisibleRect()

setDragEnabled

public void setDragEnabled(boolean b)
Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component. The transferHandler property needs to be set to a non-null value for the drag to do anything. The default value of the dragEnabled property is false.

When automatic drag handling is enabled, most look and feels begin a drag-and-drop operation whenever the user presses the mouse button over a selection and then moves the mouse a few pixels. Setting this property to true can therefore have a subtle effect on how selections behave.

Some look and feels might not support automatic drag and drop; they will ignore this property. You can work around such look and feels by modifying the component to directly call the exportAsDrag method of a TransferHandler.

Parameters:
b - the value to set the dragEnabled property to
Throws:
HeadlessException - if b is true and GraphicsEnvironment.isHeadless() returns true
Since:
1.4
See Also:
GraphicsEnvironment.isHeadless(), getDragEnabled(), JComponent.setTransferHandler(javax.swing.TransferHandler), TransferHandler

getDragEnabled

public boolean getDragEnabled()
Gets the dragEnabled property.

Returns:
the value of the dragEnabled property
Since:
1.4
See Also:
setDragEnabled(boolean)

getNextMatch

public int getNextMatch(String prefix,
                        int startIndex,
                        Position.Bias bias)
Returns the next list element that starts with a prefix.

Parameters:
prefix - the string to test for a match
startIndex - the index for starting the search
bias - the search direction, either Position.Bias.Forward or Position.Bias.Backward.
Returns:
the index of the next list element that starts with the prefix; otherwise -1
Throws:
IllegalArgumentException - if prefix is null or startIndex is out of bounds
Since:
1.4

getToolTipText

public String getToolTipText(MouseEvent event)
Overrides JComponent's getToolTipText method in order to allow the renderer's tips to be used if it has text set.

Note: For JList to properly display tooltips of its renderers JList must be a registered component with the ToolTipManager. This is done automatically in the constructor, but if at a later point JList is told setToolTipText(null) it will unregister the list component, and no tips from renderers will display anymore.

Overrides:
getToolTipText in class JComponent
See Also:
JComponent.getToolTipText()

locationToIndex

public int locationToIndex(Point location)
Convert a point in JList coordinates to the closest index of the cell at that location. To determine if the cell actually contains the specified location use a combination of this method and getCellBounds. Returns -1 if the model is empty.

Parameters:
location - the coordinates of the cell, relative to JList
Returns:
an integer -- the index of the cell at the given location, or -1.

indexToLocation

public Point indexToLocation(int index)
Returns the origin of the specified item in JList coordinates. Returns null if index isn't valid.

Parameters:
index - the index of the JList cell
Returns:
the origin of the index'th cell

getCellBounds

public Rectangle getCellBounds(int index0,
                               int index1)
Returns the bounds of the specified range of items in JList coordinates. Returns null if index isn't valid.

Parameters:
index0 - the index of the first JList cell in the range
index1 - the index of the last JList cell in the range
Returns:
the bounds of the indexed cells in pixels

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
See Also:
setModel(javax.swing.ListModel)

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
Throws:
IllegalArgumentException - if model is null
See Also:
getModel()

setListData

public void setListData(Object[] listData)
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
See Also:
setModel(javax.swing.ListModel)

setListData

public void setListData(Vector<?> listData)
Constructs a ListModel from a Vector and then applies setModel to it.

Parameters:
listData - a Vector containing the items to display in the list
See Also:
setModel(javax.swing.ListModel)

createSelectionModel

protected ListSelectionModel createSelectionModel()
Returns an instance of DefaultListSelectionModel. This method is used by the constructor to initialize the selectionModel property.

Returns:
the ListSelectionModel used by this JList.
See Also:
setSelectionModel(javax.swing.ListSelectionModel), DefaultListSelectionModel

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
See Also:
setSelectionModel(javax.swing.ListSelectionModel), ListSelectionModel

fireSelectionValueChanged

protected void fireSelectionValueChanged(int firstIndex,
                                         int lastIndex,
                                         boolean isAdjusting)
Notifies JList ListSelectionListeners that the selection model has changed. It's used to forward ListSelectionEvents from the selectionModel to the ListSelectionListeners added directly to the JList.

Parameters:
firstIndex - the first selected index
lastIndex - the last selected index
isAdjusting - true if multiple changes are being made
See Also:
addListSelectionListener(javax.swing.event.ListSelectionListener), removeListSelectionListener(javax.swing.event.ListSelectionListener), EventListenerList

addListSelectionListener

public void addListSelectionListener(ListSelectionListener listener)
Adds 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
See Also:
getSelectionModel(), getListSelectionListeners()

removeListSelectionListener

public void removeListSelectionListener(ListSelectionListener listener)
Removes a listener from the list that's notified each time a change to the selection occurs.

Parameters:
listener - the ListSelectionListener to remove
See Also:
addListSelectionListener(javax.swing.event.ListSelectionListener), getSelectionModel()

getListSelectionListeners

public ListSelectionListener[] getListSelectionListeners()
Returns an array of all the ListSelectionListeners added to this JList with addListSelectionListener().

Returns:
all of the ListSelectionListeners added or an empty array if no listeners have been added
Since:
1.4
See Also:
addListSelectionListener(javax.swing.event.ListSelectionListener)

setSelectionModel

public void setSelectionModel(ListSelectionModel selectionModel)
Sets 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.

Parameters:
selectionModel - the ListSelectionModel that implements the selections
Throws:
IllegalArgumentException - if selectionModel is null
See Also:
getSelectionModel()

setSelectionMode

public void setSelectionMode(int selectionMode)
Determines whether single-item or multiple-item selections are allowed. The following selectionMode values are allowed:
  • ListSelectionModel.SINGLE_SELECTION Only one list index can be selected at a time. In this mode the setSelectionInterval and addSelectionInterval methods are equivalent, and only the second index argument is used.
  • ListSelectionModel.SINGLE_INTERVAL_SELECTION One contiguous index interval can be selected at a time. In this mode setSelectionInterval and addSelectionInterval are equivalent.
  • ListSelectionModel.MULTIPLE_INTERVAL_SELECTION In this mode, there's no restriction on what can be selected. This is the default.

Parameters:
selectionMode - an integer specifying the type of selections that are permissible
See Also:
getSelectionMode()

getSelectionMode

public int getSelectionMode()
Returns whether single-item or multiple-item selections are allowed.

Returns:
the value of the selectionMode property
See Also:
setSelectionMode(int)

getAnchorSelectionIndex

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

Returns:
the index that most recently anchored an interval selection
See Also:
ListSelectionModel.getAnchorSelectionIndex(), addSelectionInterval(int, int), setSelectionInterval(int, int), addListSelectionListener(javax.swing.event.ListSelectionListener)

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
See Also:
ListSelectionModel.getLeadSelectionIndex(), addSelectionInterval(int, int), setSelectionInterval(int, int), addListSelectionListener(javax.swing.event.ListSelectionListener)

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
See Also:
ListSelectionModel.getMinSelectionIndex(), addListSelectionListener(javax.swing.event.ListSelectionListener)

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
See Also:
ListSelectionModel.getMaxSelectionIndex(), addListSelectionListener(javax.swing.event.ListSelectionListener)

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.

Parameters:
index - index to be queried for selection state
Returns:
true if the specified index is selected
See Also:
ListSelectionModel.isSelectedIndex(int), setSelectedIndex(int), addListSelectionListener(javax.swing.event.ListSelectionListener)

isSelectionEmpty

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

Returns:
true if nothing is selected
See Also:
ListSelectionModel.isSelectionEmpty(), clearSelection(), addListSelectionListener(javax.swing.event.ListSelectionListener)

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.

See Also:
ListSelectionModel.clearSelection(), isSelectionEmpty(), addListSelectionListener(javax.swing.event.ListSelectionListener)

setSelectionInterval

public void setSelectionInterval(int anchor,
                                 int lead)
Selects the specified interval. Both the anchor and lead indices are included. It's not necessary for anchor to be less than lead. This is a convenience method that just delegates to the selectionModel. The DefaultListSelectionModel implementation will do nothing if either anchor or lead are -1. If anchor or lead are less than -1, IndexOutOfBoundsException is thrown.

Parameters:
anchor - the first index to select
lead - the last index to select
Throws:
IndexOutOfBoundsException - if either anchor or lead are less than -1
See Also:
ListSelectionModel.setSelectionInterval(int, int), addSelectionInterval(int, int), removeSelectionInterval(int, int), addListSelectionListener(javax.swing.event.ListSelectionListener)

addSelectionInterval

public void addSelectionInterval(int anchor,
                                 int lead)
Sets the selection to be the union of the specified interval with current selection. Both the anchor and lead indices are included. It's not necessary for anchor to be less than lead. This is a convenience method that just delegates to the selectionModel. The DefaultListSelectionModel implementation will do nothing if either anchor or lead are -1. If anchor or lead are less than -1, IndexOutOfBoundsException is thrown.

Parameters:
anchor - the first index to add to the selection
lead - the last index to add to the selection
Throws:
IndexOutOfBoundsException - if either anchor or lead are less than -1
See Also:
ListSelectionModel.addSelectionInterval(int, int), setSelectionInterval(int, int), removeSelectionInterval(int, int), addListSelectionListener(javax.swing.event.ListSelectionListener)

removeSelectionInterval

public void removeSelectionInterval(int index0,
                                    int index1)
Sets the selection to be the set difference of the specified interval and the current selection. Both the index0 and index1 indices are removed. It's not necessary for index0 to be less than index1. This is a convenience method that just delegates to the selectionModel. The DefaultListSelectionModel implementation will do nothing if either index0 or index1 are -1. If index0 or index1 are less than -1, IndexOutOfBoundsException is thrown.

Parameters:
index0 - the first index to remove from the selection
index1 - the last index to remove from the selection
Throws:
IndexOutOfBoundsException - if either index0 or index1 are less than -1
See Also:
ListSelectionModel.removeSelectionInterval(int, int), setSelectionInterval(int, int), addSelectionInterval(int, int), addListSelectionListener(javax.swing.event.ListSelectionListener)

setValueIsAdjusting

public void setValueIsAdjusting(boolean b)
Sets the data model's isAdjusting property to true, so that a single event will be generated when all of the selection events have finished (for example, when the mouse is being dragged over the list in selection mode).

Parameters:
b - the boolean value for the property value
See Also:
ListSelectionModel.setValueIsAdjusting(boolean)

getValueIsAdjusting

public boolean getValueIsAdjusting()
Returns the value of the data model's isAdjusting property. This value is true if multiple changes are being made.

Returns:
true if multiple selection-changes are occurring, as when the mouse is being dragged over the list
See Also:
ListSelectionModel.getValueIsAdjusting()

getSelectedIndices

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

Returns:
all of the selected indices, in increasing order
See Also:
removeSelectionInterval(int, int), addListSelectionListener(javax.swing.event.ListSelectionListener)

setSelectedIndex

public void setSelectedIndex(int index)
Selects a single cell.

Parameters:
index - the index of the one cell to select
See Also:
ListSelectionModel.setSelectionInterval(int, int), isSelectedIndex(int), addListSelectionListener(javax.swing.event.ListSelectionListener)

setSelectedIndices

public void setSelectedIndices(int[] indices)
Selects a set of cells.

Parameters:
indices - an array of the indices of the cells to select
See Also:
ListSelectionModel.addSelectionInterval(int, int), isSelectedIndex(int), addListSelectionListener(javax.swing.event.ListSelectionListener)

getSelectedValues

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

Returns:
the selected values or an empty list if nothing is selected
See Also:
isSelectedIndex(int), getModel(), addListSelectionListener(javax.swing.event.ListSelectionListener)

getSelectedIndex

public int getSelectedIndex()
Returns the first selected index; returns -1 if there is no selected item.

Returns:
the value of getMinSelectionIndex
See Also:
getMinSelectionIndex(), addListSelectionListener(javax.swing.event.ListSelectionListener)

getSelectedValue

public Object getSelectedValue()
Returns the first selected value, or null if the selection is empty.

Returns:
the first selected value
See Also:
getMinSelectionIndex(), getModel(), addListSelectionListener(javax.swing.event.ListSelectionListener)

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, if one exists; otherwise false

getPreferredScrollableViewportSize

public Dimension getPreferredScrollableViewportSize()
Computes the size of the viewport needed to display visibleRowCount rows. This is trivial if fixedCellWidth and fixedCellHeight were specified. Note that they can be specified implicitly with the prototypeCellValue property. If fixedCellWidth wasn't specified, it's computed by finding the widest list element. If fixedCellHeight wasn't specified then we resort to heuristics:
  • If the model isn't empty we just multiply the height of the first row by visibleRowCount.
  • If the model is empty, (JList.getModel().getSize() == 0), then we just allocate 16 pixels per visible row, and 256 pixels for the width (unless fixedCellWidth was set), and hope for the best.
If the layout orientation is not VERTICAL, than this will return the value from getPreferredSize. The current ListUI is expected to override getPreferredSize to return an appropriate value.

Specified by:
getPreferredScrollableViewportSize in interface Scrollable
Returns:
a dimension containing the size of the viewport needed to display visibleRowCount rows
See Also:
getPreferredScrollableViewportSize(), setPrototypeCellValue(java.lang.Object)

getScrollableUnitIncrement

public int getScrollableUnitIncrement(Rectangle visibleRect,
                                      int orientation,
                                      int direction)
Returns the distance to scroll to expose the next or previous row (for vertical scrolling) or column (for horizontal scrolling).

For horizontal scrolling if the list is layed out vertically (the orientation is VERTICAL) than the lists font size or 1 is returned if the font is null is used.

Note that the value of visibleRect must be the equal to this.getVisibleRect().

Specified by:
getScrollableUnitIncrement in interface Scrollable
Parameters:
visibleRect - the visible rectangle
orientation - HORIZONTAL or VERTICAL
direction - if <= 0, then scroll UP; if > 0, then scroll DOWN
Returns:
the distance, in pixels, to scroll to expose the next or previous unit
Throws:
IllegalArgumentException - if visibleRect is null, or orientation isn't one of SwingConstants.VERTICAL, SwingConstants.HORIZONTAL.
See Also:
Scrollable.getScrollableUnitIncrement(java.awt.Rectangle, int, int)

getScrollableBlockIncrement

public int getScrollableBlockIncrement(Rectangle visibleRect,
                                       int orientation,
                                       int direction)
Returns the distance to scroll to expose the next or previous block. For vertical scrolling we are using the follows rules:
  • if scrolling down (direction is greater than 0), the last visible element should become the first completely visible element
  • if scrolling up, the first visible element should become the last completely visible element
  • visibleRect.height if the list is empty

For horizontal scrolling if the list is layed out horizontally (the orientation is VERTICAL_WRAP or HORIZONTAL_WRAP):

  • if scrolling right (direction is greater than 0), the last visible element should become the first completely visible element
  • if scrolling left, the first visible element should become the last completely visible element
  • visibleRect.width if the list is empty

    Return visibleRect.width if the list is layed out vertically.

    Note that the value of visibleRect must be the equal to this.getVisibleRect().

    Specified by:
    getScrollableBlockIncrement in interface Scrollable
    Parameters:
    visibleRect - the visible rectangle
    orientation - HORIZONTAL or VERTICAL
    direction - if <= 0, then scroll UP; if > 0, then scroll DOWN
    Returns:
    the block increment amount.
    Throws:
    IllegalArgumentException - if visibleRect is null, or orientation isn't one of SwingConstants.VERTICAL, SwingConstants.HORIZONTAL.
    See Also:
    Scrollable.getScrollableUnitIncrement(java.awt.Rectangle, int, int)

  • getScrollableTracksViewportWidth

    public boolean getScrollableTracksViewportWidth()
    Returns true if this JList is displayed in a JViewport and the viewport is wider than JList's preferred width; or if the layout orientation is HORIZONTAL_WRAP and the visible row count is <= 0; otherwise returns false. If false, then don't track the viewport's width. This allows horizontal scrolling if the JViewport is itself embedded in a JScrollPane.

    Specified by:
    getScrollableTracksViewportWidth in interface Scrollable
    Returns:
    true if viewport is wider than the JList's preferred width, otherwise false
    See Also:
    Scrollable.getScrollableTracksViewportWidth()

    getScrollableTracksViewportHeight

    public boolean getScrollableTracksViewportHeight()
    Returns true if this JList is displayed in a JViewport and the viewport is taller than JList's preferred height, or if the layout orientation is VERTICAL_WRAP and the number of visible rows is <= 0; otherwise returns false. If false, then don't track the viewport's height. This allows vertical scrolling if the JViewport is itself embedded in a JScrollPane.

    Specified by:
    getScrollableTracksViewportHeight in interface Scrollable
    Returns:
    true if viewport is taller than Jlist's preferred height, otherwise false
    See Also:
    Scrollable.getScrollableTracksViewportHeight()

    paramString

    protected String paramString()
    Returns a string representation of this JList. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null.

    Overrides:
    paramString in class JComponent
    Returns:
    a string representation of this JList.

    getAccessibleContext

    public AccessibleContext getAccessibleContext()
    Gets the AccessibleContext associated with this JList. For JLists, the AccessibleContext takes the form of an AccessibleJList. A new AccessibleJList instance is created if necessary.

    Specified by:
    getAccessibleContext in interface Accessible
    Overrides:
    getAccessibleContext in class JComponent
    Returns:
    an AccessibleJList that serves as the AccessibleContext of this JList

    Ces informations proviennent du site de http://java.sun.com

    Remarques

    Contenu

    Le contenu de cette page provient du site de Sun, et est généré depuis un cache sur l'infobrol après certains traitements automatisés. La présentation peut donc différer du document original, mais le contenu aussi. Vous pouvez utiliser ce bouton pour afficher la page originale du site de Sun :

    Quels sont les motivations de cette démarche?

    Maintenir les pages en cache sur différents sites peut offrir plus de disponibilité.

    Chaque page est indexée dans la base de donnée, ce qui permet de retrouver facilement les informations, au moyen des sommaires, du moteur de recherche interne, etc.

    Des facilités sont mises en place pour que les membres de l'infobrol puissent effectuer des traductions en français des différents documents. Ceci devrait permettre aux débutants en programmation Java de consulter les API en français s'ils maîtrisent moins bien la langue de Shakespeare. Dans le cas où une traduction a été soumise, elle est disponible au moyen d'un lien en bas de page. Si la traduction a été validée, la page s'affiche par défaut en français, et un lien en bas de page permet d'atteindre la version en anglais.

    Le code sur l'infobrol est automatiquement coloré selon la syntaxe, et les différents mots clés sont transformés en liens pour accéder rapidement aux informations.

    Vous avez la possibilité de partager vos expériences en proposant vos propres extraits de code en utilisant le bouton "ajouter un commentaire" en bas de page. Si vous visitez simplement l'infobrol, vous avez déjà accès à cette fonction, mais si vous étes membre du brol, vous pouvez en plus utiliser des boutons supplémentaires de mise en forme, dont la coloration automatique de vos extraits de codes.

    Réseaux sociaux

    Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher les interactions avec les réseaux sociaux sur ces pages.

     

    Nuage de mots clés

    6 mots clés dont 0 définis manuellement (plus d'information...).

    Avertissement

    Cette page ne possède pas encore de mots clés manuels, ceci est donc un exemple automatique (les niveaux de pertinence sont fictifs, mais les liens sont valables). Pour tester le nuage avec une page qui contient des mots définis manuellement, vous pouvez cliquer ici.

    Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher le nuage de mots clés.

     

    Astuce pour imprimer les couleurs des cellules de tableaux : http://www.gaudry.be/ast-rf-450.html
    Aucun commentaire pour cette page

    © Ce document issu de l′infobrol est enregistré sous le certificat Cyber PrInterDeposit Digital Numbertection. Enregistrement IDDN n° 5329-3465
    Document créé le 16/09/06 01:31, dernière modification le Vendredi 17 Juin 2011, 11:12
    Source du document imprimé : http:///www.gaudry.be/java-api-rf-javax/swing/JList.html
    St.Gaudry©07.01.02
    Outils (masquer)
    ||
    Recherche (afficher)
    Recherche :

    Utilisateur (masquer)
    Navigation (masquer)
    Apparence (afficher)
    Stats (afficher)
    15838 documents
    455 astuces.
    550 niouzes.
    3107 definitions.
    447 membres.
    8121 messages.

    Document genere en :
    0,69 seconde

    Mises à jour :
    Mises à jour du site
    Citation (masquer)
    Moi, je n'ai pas d'ami. C'est trop fatigant d'être aimable.

    Jean Gabin
     
    l'infobrol
    Nous sommes le Dimanche 21 Janvier 2018, 17:37, toutes les heures sont au format GMT+1.00 Heure, heure d'hiver