0% found this document useful (0 votes)
90 views25 pages

Class Com - Sun.java - Swing.jlist

Uploaded by

Xavier Joaquim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views25 pages

Class Com - Sun.java - Swing.jlist

Uploaded by

Xavier Joaquim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Overview 

Package   Class  Use  Tree  Deprecated  Index  Help  Java Platform 1.2


Beta 4
 PREV CLASS   NEXT CLASS FRAMES   NO FRAMES

SUMMARY:  INNER | FIELD | CONSTR | METHOD DETAIL:  FIELD | CONSTR | METHOD

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

public class JList


extends JComponent
implementa Rolável , Acessível

Um componente que permite ao usuário selecionar um ou mais objetos de uma lista. Um


modelo separado, ListModel, representa o conteúdo da lista. É fácil exibir uma matriz ou
vetor de objetos usando um JListconstrutor que cria uma ListModel instância para você:
// Cria uma JList que exibe as strings em data[]

String[] dados = {"um", "dois", "grátis", "quatro"};


JList dataList = new JList(dados);

// A propriedade value do modelo JList é um objeto que fornece


// uma visão somente leitura dos dados. Foi construído automaticamente.

for(int i = 0; i < dataList.getModel().getSize(); i++) {


System.out.println(dataList.getModel().getElementAt(i));
}

// Create a JList that displays the superclass of JList.class.


// We store the superclasses in a java.util.Vector.

Vector superClasses = new Vector();


Class rootClass = com.sun.java.swing.JList.class;
for(Class cls = rootClass; cls != null; cls = cls.getSuperclass()) {
superClasses.addElement(cls);
}
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, e.g.
JScrollPane scrollPane = new JScrollPane(dataList);
// Or in two steps:
JScrollPane scrollPane = new JScrollPane();
scrollPane.getViewport().setView(dataList);

By default JList supports single selection, i.e. zero or one index can be selected. The
selection state is actually managed by a separate delegate object, an implementation of
ListSelectionModel however JList provides convenient properties for managing the
selection.
String[] data = {"one", "two", "free", "four"};
JList dataList = new JList(data);

dataList.setSelectedIndex(1); // select "two"


dataList.getSelectedValue(); // returns "two"

The contents of a JList can be dynamic, i.e. 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:

// This list model has about 2^16 elements. Enjoy scrolling.

ListModel bigData = new AbstractListModel() {


public int getSize() { return Short.MAX_VALUE; }
public Object getElementAt(int index) { return "Index " + index; }
};

JList bigDataList = new List(bigData);

// We don't want the JList implementation to compute the width


// or height of all of the list cells, so we give it a String
// that's as big as we'll need for any cell. It uses this to
// compute values for the fixedCellWidth and fixedCellHeight
// properties.

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:
// 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);
return this;
}
}
String[] data = {"one", "two", "free", "four"};
JList dataList = new JList(data);
dataList.setCellRenderer(new MyCellRenderer());

JListnãofornece nenhum suporte especial para lidar com cliques duplos ou triplos (ou N)
do mouse; no entanto, é fácil lidar com eles usando um arquivo MouseListener. Use o
JListmétodo locationToIndex()para determinar qual célula foi clicada. Por exemplo:

lista JList final = new JList(dataModel);


MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = list.locationToIndex(e.getPoint());
System.out.println("Cliquei duas vezes no Item " + index);
}
}
};
list.addMouseListener(mouseListener);

Observe que neste exemplo a variável JList é final porque ela é referenciada pela classe
MouseListener anônima.

Para as teclas do teclado usadas por este componente nas execuções padrão de Look and
Feel (L&F), consulte as atribuições de tecla JList .

Aviso: os objetos serializados desta classe não serão compatíveis com versões futuras do
swing. O suporte de serialização atual é apropriado para armazenamento de curto prazo ou
RMI entre aplicativos Swing1.0. Não será possível carregar objetos Swing1.0 serializados
com versões futuras do Swing. A versão JDK1.2 do Swing será a linha de base de
compatibilidade para a forma serializada dos objetos Swing.

Veja também:
ListModel, AbstractListModel, DefaultListModel, ListSelectionModel,
DefaultListSelectionModel, ListCellRenderer, Forma serializada

Resumo da classe interna


protegido JList.AccessibleJList
            A classe usada para obter a função acessível para este objeto.
 
Classes internas herdadas da classe com.sun.java.swing. JComponent
JComponent.AccessibleJComponent
 
Campos herdados da classe com.sun.java.swing. JComponent
accessContext , listenerList , TOOL_TIP_TEXT_KEY , ui , UNDEFINED_CONDITION ,
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT , WHEN_FOCUSED ,
WHEN_IN_FOCUSED_WINDOW
 
Campos herdados da classe java.awt. Componente
BOTTOM_ALIGNMENT , CENTER_ALIGNMENT , LEFT_ALIGNMENT , RIGHT_ALIGNMENT ,
TOP_ALIGNMENT
 
Resumo do Construtor
JList ()
          Constrói uma JList com um modelo vazio.
JList ( ListModel  dataModel)
          Construa uma JList que exibe os elementos no modelo não nulo especificado.
JList ( Object [] listData)
          Constrói uma JList que exibe os elementos no array especificado.
JList ( Vector  listData)
          Constrói uma JList que exibe os elementos no Vetor especificado.
 
Resumo do método
 vazio addListSelectionListener ( ListSelectionListener  listener)
          Adiciona um listener à lista que é notificado sempre que ocorre uma
alteração na seleção.
 vazio addSelectionInterval (int anchor, int lead)
          Define a seleção para ser a união do intervalo especificado com a
seleção atual.
 vazio clearSelection ()
          Limpa a seleção - depois de chamar este método isSelectionEmpty ()
retornará true.
ListSelectionModel createSelectionModel ()
protegido             Retorna uma instância de DefaultListSelectionModel.
 vazio assegurarIndexIsVisible (índice int)
          Se este JList estiver sendo exibido em um JViewport e a célula
especificada não estiver completamente visível, role a viewport.
vazio protegido fireSelectionValueChanged (int firstIndex, int lastIndex, boolean
isAdjusting)
          Este método notifica JList ListSelectionListeners que o modelo de
seleção foi alterado.
 Contexto Acessível getAccessibleContext ()
          Obtenha o AccessibleContext associado a este JComponent
 int getAnchorSelectionIndex ()
          Retorna o primeiro argumento de índice da chamada
addSelectionInterval ou setSelectionInterval mais recente.
 Retângulo getCellBounds (int index1, int index2)
          Retorna os limites do intervalo especificado de itens nas
coordenadas JList, nulo se o índice não for válido.
 ListCellRenderer getCellRenderer ()
          Retorna o objeto que renderiza os itens da lista.
 int getFirstVisibleIndex ()
          Retorna o índice da célula no canto superior esquerdo da JList ou -1
se nada estiver visível ou a lista estiver vazia.
 int getFixedCellHeight ()
          Retorna o valor fixo da largura da célula -- o valor especificado pela
definição da propriedade fixedCellHeight, em vez de calculado a partir
dos elementos da lista.
 int getFixedCellWidth ()
          Retorna o valor fixo da largura da célula -- o valor especificado pela
configuração da propriedade fixedCellWidth, em vez de calculado a partir
dos elementos da lista.
 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.
 int getLeadSelectionIndex()
          Returns the second index argument from the most recent
addSelectionInterval or setSelectionInterval call.
 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.
 Dimension getPreferredScrollableViewportSize()
          Compute 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, instead of forcing the calculation to inspect every item in the list.
 int getScrollableBlockIncrement(Rectangle visibleRect, int orientation,
int direction)
           
 boolean getScrollableTracksViewportHeight()
          If this JList is displayed in a JViewport, don't change its height when
the viewports height changes.
 boolean getScrollableTracksViewportWidth()
          If this JList is displayed in a JViewport, don't change its width when
the viewports width changes.
 int getScrollableUnitIncrement(Rectangle visibleRect, int orientation,
int direction)
          Horizontal scrolling: return the lists font size or 1 if the font is null.
 int getSelectedIndex()
          A convenience method that returns the first selected index.
 int[] getSelectedIndices()
          Return an array of all of the selected indices in increasing order.
 Object getSelectedValue()
          A convenience method that returns the first selected value or null, if
the selection is empty.
 Object[] getSelectedValues()
          Return an array of the values for the selected cells.
 Color getSelectionBackground()
          Returns the background color for selected cells.
 Color getSelectionForeground()
          Returns the foreground color.
 int getSelectionMode()
           
 ListSelectionModel getSelectionModel()
          Returns the value of the current selection model.
 ListUI getUI()
          Returns the L&F object that renders this component.
 String getUIClassID()
          Returns the name of the UIFactory class that generates the look and
feel for this component.
 boolean getValueIsAdjusting()
          Returns the value of the data model's isAdjusting property.
 int getVisibleRowCount()
          Return the preferred number of visible rows.
 Point indexToLocation(int index)
          Returns the origin of the specified item in JList coordinates, null if
index isn't valid.
 boolean isSelectedIndex(int index)
          Returns true if the specified index is selected.
 boolean isSelectionEmpty()
          Returns true if nothing is selected This is a convenience method that
just delegates to the selectionModel.
 int locationToIndex(Point location)
          Convert a point in JList coordinates to the index of the cell at that
location.
 void removeListSelectionListener(ListSelectionListener listener)
          Remove a listener from the list that's notified each time a change to
the selection occurs.
 void removeSelectionInterval(int index0, int index1)
          Set 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 setFixedCellHeight(int height)
          If this value is greater than zero it defines the height of every cell in
the list.
 void setFixedCellWidth(int width)
          If this value is greater than zero it defines the width of every cell in
the list.
 void setListData(Object[] listData)
          A convenience method that constructs a ListModel from an array of
Objects and then applies setModel to it.
 void setListData(Vector listData)
          A convenience method that 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)
          If this value is non-null it's used to compute fixedCellWidth and
fixedCellHeight by configuring the cellRenderer at index equals zero for
the specified value and then computing the renderer components
preferred size.
 void setSelectedIndex(int index)
          Select a single cell.
 void setSelectedIndices(int[] indices)
          Select a set of cells.
 void setSelectedValue(Object anObject, boolean shouldScroll)
           
 void setSelectionBackground(Color selectionBackground)
          Set the background color for selected cells.
 void setSelectionForeground(Color selectionForeground)
          Set the foreground color for selected cells.
 void setSelectionInterval(int anchor, int lead)
          Select the specified interval.
 void setSelectionMode(int selectionMode)
          Determines whether single-item or multiple-item selections are
allowed.
 void setSelectionModel(ListSelectionModel selectionModel)
          Set the selectionModel for the list to a non-null ListSelectionModel
implementation.
 void setUI(ListUI ui)
          Sets the L&F object that renders this component.
 void setValueIsAdjusting(boolean b)
          Sets the data model's isAdjusting property 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)
          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.
 void updateUI()
          Set the UI property with the "ListUI" from the current default
UIFactory.
 
Methods inherited from class com.sun.java.swing.JComponent
addAncestorListener , addNotify , addPropertyChangeListener ,
addVetoableChangeListener , computeVisibleRect , contains , createToolTip ,
firePropertyChange , firePropertyChange , firePropertyChange , firePropertyChange ,
firePropertyChange , firePropertyChange , firePropertyChange , firePropertyChange ,
firePropertyChange , fireVetoableChange , getActionForKeyStroke , getAlignmentX ,
getAlignmentY , getAutoscrolls , getBorder , getBounds , getClientProperty ,
getComponentGraphics , getConditionForKeyStroke , getDebugGraphicsOptions ,
getGraphics , getHeight , getInsets , getInsets , getLocation , getMaximumSize ,
getMinimumSize , getNextFocusableComponent , getPreferredSize ,
getRegisteredKeyStrokes , getRootPane , getSize , getToolTipLocation , getToolTipText ,
getToolTipText , getTopLevelAncestor , getVisibleRect , getWidth , getX , getY , grabFocus ,
hasFocus , isDoubleBuffered , isFocusCycleRoot , isFocusTraversable ,
isLightweightComponent , isManagingFocus , isOpaque , isOptimizedDrawingEnabled ,
isPaintingTile , isRequestFocusEnabled , isValidateRoot , paint , paintBorder ,
paintChildren , paintComponent , paintImmediately , paintImmediately ,
processComponentKeyEvent , processFocusEvent , processKeyEvent ,
processMouseMotionEvent , putClientProperty , registerKeyboardAction ,
registerKeyboardAction , removeAncestorListener , removeNotify ,
removePropertyChangeListener , removeVetoableChangeListener , repaint , repaint ,
requestDefaultFocus , requestFocus , resetKeyboardActions , reshape , revalidate ,
scrollRectToVisible , setAlignmentX , setAlignmentY , setAutoscrolls , setBorder ,
setDebugGraphicsOptions , setDoubleBuffered , setEnabled , setMaximumSize ,
setMinimumSize , setNextFocusableComponent , setOpaque , setPreferredSize ,
setRequestFocusEnabled , setToolTipText , setUI , setVisible , unregisterKeyboardAction ,
update
 
Methods inherited from class java.awt.Container
add , add , add , add , add , addContainerListener , addImpl , countComponents ,
deliverEvent , doLayout , findComponentAt , findComponentAt , getComponent ,
getComponentAt , getComponentAt , getComponentCount , getComponents , getLayout ,
insets , invalidate , isAncestorOf , layout , list , list , locate , minimumSize ,
paintComponents , paramString , preferredSize , print , printComponents ,
processContainerEvent , processEvent , remove , remove , removeAll ,
removeContainerListener , setLayout , validate , validateTree
 
Methods inherited from class java.awt.Component
action , add , addComponentListener , addFocusListener , addInputMethodListener ,
addKeyListener , addMouseListener , addMouseMotionListener ,
addPropertyChangeListener , bounds , checkImage , checkImage , coalesceEvents ,
contains , createImage , createImage , disable , disableEvents , dispatchEvent , enable ,
enable , enableEvents , enableInputMethods , getBackground , getBounds , getColorModel ,
getComponentOrientation , getCursor , getDropTarget , getFont , getFontMetrics ,
getForeground , getInputContext , getInputMethodRequests , getLocale , getLocation ,
getLocationOnScreen , getName , getParent , getPeer , getSize , getToolkit , getTreeLock ,
gotFocus , handleEvent , hide , imageUpdate , inside , isDisplayable , isEnabled ,
isLightweight , isShowing , isValid , isVisible , keyDown , keyUp , list , list , list , location ,
lostFocus , mouseDown , mouseDrag , mouseEnter , mouseExit , mouseMove , mouseUp ,
move , nextFocus , paintAll , postEvent , prepareImage , prepareImage , printAll ,
processComponentEvent , processInputMethodEvent , processMouseEvent , remove ,
removeComponentListener , removeFocusListener , removeInputMethodListener ,
removeKeyListener , removeMouseListener , removeMouseMotionListener ,
removePropertyChangeListener , repaint , repaint , repaint , resize , resize , setBackground
, setBounds , setBounds , setComponentOrientation , setCursor , setDropTarget , setFont ,
setForeground , setLocale , setLocation , setLocation , setName , setSize , setSize , show ,
show , size , toString , transferFocus
 
Methods inherited from class java.lang.Object
clone , equals , finalize , getClass , hashCode , notify , notifyAll , wait , wait , wait
 

Constructor Detail
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
getUI
public ListUI getUI()

Returns the L&F object that renders this component.

Returns:
the ListUI object that renders this component

setUI
public void setUI(ListUI ui)

Sets the L&F object that renders this component.

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

updateUI
public void updateUI()

Set the UI property with the "ListUI" from the current default UIFactory. This method is
called by the JList constructor and to update the Lists look and feel at runtime.

Overrides:
updateUI in class JComponent
See Also:
UIManager.getUI(com.sun.java.swing.JComponent)

getUIClassID
public String getUIClassID()

Returns the name of the UIFactory class that generates the look and feel for this
component.

Returns:
"ListUI"
Overrides:
getUIClassID in class JComponent
See Also:
JComponent.getUIClassID(), UIDefaults.getUI(com.sun.java.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, instead of forcing the
calculation to inspect every item in the list.

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

setPrototypeCellValue
public void setPrototypeCellValue(Object prototypeCellValue)
If this value is non-null it's used to compute fixedCellWidth and fixedCellHeight by
configuring the cellRenderer at index equals zero for the specified value and then
computing the renderer components preferred size. This property is useful when the
list is too long to allow JList to just compute the width/height of each cell and there's
single cell value that's known to occupy as much space as any of the others.

The default value of this property is null.

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

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

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.

Returns:
the fixed cell width
See Also:
setFixedCellWidth

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
See Also:
getPrototypeCellValue(), setFixedCellWidth(int),
JComponent.addPropertyChangeListener(java.beans.PropertyChangeListener)

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
See Also:
setFixedCellHeight

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
See Also:
getPrototypeCellValue(), setFixedCellWidth(int),
JComponent.addPropertyChangeListener(java.beans.PropertyChangeListener)

getCellRenderer
public ListCellRenderer getCellRenderer()

Returns the object that renders the list items.

Returns:
the ListCellRenderer
See Also:
setCellRenderer(com.sun.java.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.

This is a JavaBeans bound property.

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

Returns the 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)

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
See Also:
getSelectionForeground(), setSelectionBackground(java.awt.Color),
Component.setForeground(java.awt.Color), Component.setBackground(java.awt.Color),
Component.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)

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
See Also:
getSelectionBackground(), setSelectionForeground(java.awt.Color),
Component.setForeground(java.awt.Color), Component.setBackground(java.awt.Color),
Component.setFont(java.awt.Font)

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
See Also:
setVisibleRowCount(int)

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.

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

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.
See Also:
getLastVisibleIndex(), JComponent.getVisibleRect()

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.
See Also:
getLastVisibleIndex(), JComponent.getVisibleRect()

ensureIndexIsVisible
public void ensureIndexIsVisible(int index)

If this JList is being displayed within a JViewport and the specified cell isn't completely
visible, scroll the viewport.

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

locationToIndex
public int locationToIndex(Point location)

Convert a point in JList coordinates to the index of the cell at that location. Returns -1
if there's no cell the specified location.

Parameters:
location - The JList relative coordinates of the cell
Returns:
an int -- 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, 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 index1,
int index2)

Returns the bounds of the specified range of items in JList coordinates, null if index
isn't valid.

Parameters:
index1 - the index of the first JList cell in the range
index2 - the index of the last JList cell in the range
Returns:
the bounds of the indexed cells
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(com.sun.java.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
See Also:
getModel()

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

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
See Also:
setModel(com.sun.java.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(com.sun.java.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(com.sun.java.swing.ListSelectionModel), ListSelectionModel

fireSelectionValueChanged
protected void fireSelectionValueChanged(int firstIndex,
int lastIndex,
boolean isAdjusting)

This method 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.

See Also:
addListSelectionListener(com.sun.java.swing.event.ListSelectionListener),
removeListSelectionListener(com.sun.java.swing.event.ListSelectionListener),
EventListenerList

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.
See Also:
getSelectionModel()

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.
See Also:
addListSelectionListener(com.sun.java.swing.event.ListSelectionListener),
getSelectionModel()

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
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:

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
See Also:
getSelectionMode()

getSelectionMode
public int getSelectionMode()

Returns:
The value of the selectionMode property.
See Also:
setSelectionMode(int)
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.

Returns:
The index that most recently anchored an interval selection.
See Also:
ListSelectionModel.getAnchorSelectionIndex(), addSelectionInterval(int, int),
setSelectionInterval(int, int),
addListSelectionListener(com.sun.java.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(com.sun.java.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(com.sun.java.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(com.sun.java.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.

Returns:
True if the specified index is selected.
See Also:
ListSelectionModel.isSelectedIndex(int), setSelectedIndex(int),
addListSelectionListener(com.sun.java.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(com.sun.java.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(com.sun.java.swing.event.ListSelectionListener)

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
See Also:
ListSelectionModel.setSelectionInterval(int, int), addSelectionInterval(int,
int), removeSelectionInterval(int, int),
addListSelectionListener(com.sun.java.swing.event.ListSelectionListener)

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
See Also:
ListSelectionModel.addSelectionInterval(int, int), setSelectionInterval(int,
int), removeSelectionInterval(int, int),
addListSelectionListener(com.sun.java.swing.event.ListSelectionListener)

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
See Also:
ListSelectionModel.removeSelectionInterval(int, int), setSelectionInterval(int,
int), addSelectionInterval(int, int),
addListSelectionListener(com.sun.java.swing.event.ListSelectionListener)

setValueIsAdjusting
public void setValueIsAdjusting(boolean b)

Sets the data model's isAdjusting property 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 occuring, as when the mouse is being
dragged over the list
See Also:
ListSelectionModel.getValueIsAdjusting()

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.
See Also:
removeSelectionInterval(int, int),
addListSelectionListener(com.sun.java.swing.event.ListSelectionListener)

setSelectedIndex
public void setSelectedIndex(int index)

Select a single cell.

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

setSelectedIndices
public void setSelectedIndices(int[] indices)

Select a set of cells.

Parameters:
indices - The indices of the cells to select
See Also:
ListSelectionModel.addSelectionInterval(int, int), isSelectedIndex(int),
addListSelectionListener(com.sun.java.swing.event.ListSelectionListener)

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
See Also:
isSelectedIndex(int), getModel(),
addListSelectionListener(com.sun.java.swing.event.ListSelectionListener)

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

getSelectedValue
public Object getSelectedValue()

A convenience method that returns the first selected value or null, if the selection is
empty.

Returns:
The first selected value.
See Also:
getMinSelectionIndex(), getModel(),
addListSelectionListener(com.sun.java.swing.event.ListSelectionListener)

setSelectedValue
public void setSelectedValue(Object anObject,
boolean shouldScroll)

getPreferredScrollableViewportSize
public Dimension getPreferredScrollableViewportSize()

Compute the size of the viewport needed to display visibleRowCount rows. This is
trivial if fixedCellWidth and fixedCellHeight were specified. Note that they can
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, i.e. 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.

Specified by:
getPreferredScrollableViewportSize in interface Scrollable
See Also:
getPreferredScrollableViewportSize(), setPrototypeCellValue(java.lang.Object)

getScrollableUnitIncrement
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation,
int direction)

Horizontal scrolling: return the lists font size or 1 if the font is null. We're using the
font size instead of the width of some canonical string, e.g. "m", because it's cheaper.

Vertical scrolling: if we're scrolling downwards (direction is greater than 0), and the
first row is completely visible with respect to visibleRect, then return its height. If
we're scrolling downwards and the first row is only partially visible, return the height
of the visible part of the first row. Similarly if we're scrolling upwards we return the
height of the row above the first row, unless the first row is partially visible.

Specified by:
getScrollableUnitIncrement in interface Scrollable
Returns:
The distance to scroll to expose the next or previous row.
See Also:
Scrollable.getScrollableUnitIncrement(java.awt.Rectangle, int, int)

getScrollableBlockIncrement
public int getScrollableBlockIncrement(Rectangle visibleRect,
int orientation,
int direction)

Specified by:
getScrollableBlockIncrement in interface Scrollable
Returns:
The visibleRect.height or visibleRect.width per the orientation.
See Also:
Scrollable.getScrollableUnitIncrement(java.awt.Rectangle, int, int)

getScrollableTracksViewportWidth
public boolean getScrollableTracksViewportWidth()

If this JList is displayed in a JViewport, don't change its width when the viewports
width changes. This allows horizontal scrolling if the JViewport is itself embedded in a
JScrollPane.

Specified by:
getScrollableTracksViewportWidth in interface Scrollable
Returns:
False - don't track the viewports width.
See Also:
Scrollable.getScrollableTracksViewportWidth()

getScrollableTracksViewportHeight
public boolean getScrollableTracksViewportHeight()

If this JList is displayed in a JViewport, don't change its height when the viewports
height changes. This allows vertical scrolling if the JViewport is itself embedded in a
JScrollPane.

Specified by:
getScrollableTracksViewportHeight in interface Scrollable
Returns:
False - don't track the viewports width.
See Also:
Scrollable.getScrollableTracksViewportWidth()

getAccessibleContext
public AccessibleContext getAccessibleContext()

Get the AccessibleContext associated with this JComponent

Specified by:
getAccessibleContext in interface Accessible
Returns:
the AccessibleContext of this JComponent
Overrides:
getAccessibleContext in class JComponent

Overview  Package   Class  Use  Tree  Deprecated  Index  Help  Java Platform 1.2


Beta 4
 PREV CLASS   NEXT CLASS FRAMES   NO FRAMES

SUMMARY:  INNER | FIELD | CONSTR | METHOD DETAIL:  FIELD | CONSTR | METHOD

Submit a bug or feature


Submit comments/suggestions about new javadoc look
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-1998 Sun Microsystems, Inc. 901 San Antonio Road,
Palo Alto, California, 94303, U.S.A. All Rights Reserved.
This documentation was generated with a post-Beta4 version of Javadoc.

You might also like