所有类


javax.swing
类 JList

java.lang.Object
  继承者 java.awt.Component
      继承者 java.awt.Container
          继承者 javax.swing.JComponent
              继承者 javax.swing.JList
所有已实现的接口:
ImageObserver, MenuContainer, Serializable, Accessible, Scrollable

public class JList
   
   
   
   
   
extends JComponent
implements Scrollable, Accessible

该组件允许用户从列表中选择一个或多个对象。单独的模型 ListModel 表示列表的内容。使用构建 ListModel 实例的 JList 构造方法,可以方便地显示对象的数组或向量:

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

 String[] data = {"one", "two", "three", "four"};
 JList dataList = new JList(data);
 
 // The value of the JList model property is an object that provides
 // a read-only view of the data.  It was constructed automatically.

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

 // 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 = javax.swing.JList.class;
 for(Class cls = rootClass; cls != null; cls = cls.getSuperclass()) {
     superClasses.addElement(cls);
 }
 JList classList = new JList(superClasses);
 

JList 不支持直接滚动。要创建滚动列表,需要让 JList 作为 JScrollPane 的视口视图。例如:

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

默认情况下,JList 选择模型允许使用常量 MULTIPLE_INTERVAL_SELECTION 一次选择任何项的组合。选择状态由单独的委托对象(即 ListSelectionModel 的实例)实际管理。不过,JList 提供了便捷的属性,可用于管理选择。

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

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

JList 的内容可以是动态的,换句话说,在创建 JList 之后,列表元素可以改变值,列表的大小也可以改变。JList 利用 swing.event.ListDataListener 实现在其模型中观察更改。正确实现的 ListModel 在每次发生更改时向其侦听器发出通知。更改的特征由标识已修改、已添加或已移除的列表索引范围的 swing.event.ListDataEvent 来描述。简单动态内容 JList 应用程序可以使用 DefaultListModel 类存储列表元素。此类实现 ListModel 接口,同时提供 java.util.Vector API。需要提供自定义 ListModel 实现的应用程序可以为提供基本 ListDataListener 支持的 AbstractListModel 创建子类。例如:

 // 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 JList(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 使用 java.awt.Component(由名为 cellRendererer 的委派提供)在列表中绘制可见单元。单元渲染器组件类似于“橡皮图章”,用于绘制每个可见行。每当 JList 需要绘制单元时,它就要求单元渲染器提供组件,使用 setBounds() 将其移动到位,然后通过调用其绘制方法来绘制。默认的单元渲染器使用 JLabel 组件呈现每个组件的字符串值。用户还可以使用如下代码替代自己的单元渲染器:

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

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

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

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

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

JList 没有对处理两次或三次(或 N 次)鼠标单击提供特殊支持,不过可以使用 MouseListener 方便地处理这些操作。使用 JList 方法 locationToIndex() 确定单击的是哪一个单元。例如:

 final JList list = 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("Double clicked on Item " + index);
          }
     }
 };
 list.addMouseListener(mouseListener);
 
注意,在此例中,dataListfinal,因为它由匿名 MouseListener 类引用。

警告:此类的序列化对象将与以后的 Swing 版本不兼容。当前的序列化支持适用于短期存储或运行相同 Swing 版本的应用程序之间的 RMI。从 1.4 版本开始,已在 java.beans 包中添加了支持所有 JavaBeansTM 长期存储的功能。请参见 XMLEncoder

请参见《The Java Tutorial》中的 How to Use Lists 以获取更多文档。另请参见 The Swing Connection 中的文章 Advanced JList Programming

另请参见:
ListModel, AbstractListModel, DefaultListModel, ListSelectionModel, DefaultListSelectionModel, ListCellRenderer

嵌套类摘要
protected  classJList.AccessibleJList
          此类实现 JList 类的可访问性支持。
 
从类 javax.swing.JComponent 继承的嵌套类/接口
JComponent.AccessibleJComponent
 
从类 java.awt.Container 继承的嵌套类/接口
Container.AccessibleAWTContainer
 
从类 java.awt.Component 继承的嵌套类/接口
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
 
字段摘要
static intHORIZONTAL_WRAP
          指示“报纸样式”,单元按先横向后纵向流动。
static intVERTICAL
          指示默认布局:一列单元。
static intVERTICAL_WRAP
          指示“报纸样式”布局,单元按先纵向后横向流动。
 
从类 javax.swing.JComponent 继承的字段
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
从类 java.awt.Component 继承的字段
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
从接口 java.awt.image.ImageObserver 继承的字段
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
构造方法摘要
JList()
          构造一个使用空模型的 JList
JList(ListModel dataModel)
          构造一个 JList,使其使用指定的非 null 模型显示元素。
JList(Object[] listData)
          构造一个 JList,使其显示指定数组中的元素。
JList(Vector<?> listData)
          构造一个 JList,使其显示指定 Vector 中的元素。
 
方法摘要
 voidaddListSelectionListener(ListSelectionListener listener)
          为每次选择发生更改时要通知的列表添加侦听器。
 voidaddSelectionInterval(int anchor, int lead)
          将选择设置为指定间隔与当前选择的并集。
 voidclearSelection()
          清除选择,调用此方法后,isSelectionEmpty 将返回 true。
protected  ListSelectionModelcreateSelectionModel()
          返回 DefaultListSelectionModel 实例。
 voidensureIndexIsVisible(int index)
          滚动视口,使指定单元完全可见。
protected  voidfireSelectionValueChanged(int firstIndex, int lastIndex, boolean isAdjusting)
          通知 JListListSelectionListener 选择模型已改变。
 AccessibleContextgetAccessibleContext()
          获取与此 JList 关联的 AccessibleContext。
 intgetAnchorSelectionIndex()
          返回最近一次 addSelectionModelsetSelectionInterval 调用中的第一个 index 参数。
 RectanglegetCellBounds(int index0, int index1)
          返回 JList 坐标中项的指定范围的边界。
 ListCellRenderergetCellRenderer()
          返回呈现列表项的对象。
 booleangetDragEnabled()
          获取 dragEnabled 属性。
 intgetFirstVisibleIndex()
          返回第一个可见单元的索引。
 intgetFixedCellHeight()
          返回固定单元高度值,该值通过设置 fixedCellHeight 属性指定,而不是根据列表元素计算。
 intgetFixedCellWidth()
          返回固定单元宽度值,该值通过设置 fixedCellWidth 属性指定,而不是根据列表元素计算。
 intgetLastVisibleIndex()
          返回最后一个可见单元的索引。
 intgetLayoutOrientation()
          如果布局是单列单元,则返回 JList.VERTICAL;如果布局是“报纸样式”并且内容按先纵向后横向流动,则返回 JList.VERTICAL_WRAP;如果布局是“报纸样式”并且内容按先横向后纵向流动,则返回 JList.HORIZONTAL_WRAP
 intgetLeadSelectionIndex()
          返回最近一次 addSelectionIntervalsetSelectionInterval 调用中的第二个 index 参数。
 ListSelectionListener[]getListSelectionListeners()
          返回使用 addListSelectionListener() 添加到此 JList 中的所有 ListSelectionListener 组成的数组。
 intgetMaxSelectionIndex()
          返回选择的最大单元索引。
 intgetMinSelectionIndex()
          返回选择的最小单元索引。
 ListModelgetModel()
          返回保存由 JList 组件显示的项列表的数据模型。
 intgetNextMatch(String prefix, int startIndex, Position.Bias bias)
          返回以某一前缀开头的下一个列表元素。
 DimensiongetPreferredScrollableViewportSize()
          计算显示 visibleRowCount 行所需的视口的大小。
 ObjectgetPrototypeCellValue()
          返回“原型单元”的单元宽度,原型单元是一个用于计算单元宽度的单元,因为它与所有其他列表项具有相同的值。
 intgetScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
          返回为显露上一个或下一个块而滚动的距离。
 booleangetScrollableTracksViewportHeight()
          如果此 JListJViewport 中显示并且视口的高度大于 JList 的首选高度,或者布局方向为 VERTICAL_WRAP 但可见行数 <= 0,则返回 true;否则返回 false。
 booleangetScrollableTracksViewportWidth()
          如果此 JListJViewport 中显示并且视口的宽度大于 JList 的首选宽度,或者布局方向为 HORIZONTAL_WRAP 但可见行数 <= 0,则返回 true;否则返回 false。
 intgetScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
          返回为显露上一个或下一个行(纵向滚动)或列(横向滚动)而滚动的距离。
 intgetSelectedIndex()
          返回所选的第一个索引;如果没有选择项,则返回 -1。
 int[]getSelectedIndices()
          返回所选的全部索引的数组(按升序排列)。
 ObjectgetSelectedValue()
          返回所选的第一个值,如果选择为空,则返回 null
 Object[]getSelectedValues()
          返回所选单元的一组值。
 ColorgetSelectionBackground()
          返回所选单元的背景色。
 ColorgetSelectionForeground()
          返回选择的前景色。
 intgetSelectionMode()
          返回允许单项选择还是多项选择。
 ListSelectionModelgetSelectionModel()
          返回当前选择模型的值。
 StringgetToolTipText(MouseEvent event)
          重写 JComponentgetToolTipText 方法,从而允许使用渲染器的提示(如果设置了文本)。
 ListUIgetUI()
          返回呈现此组件的外观 (L&F) 对象。
 StringgetUIClassID()
          返回用于构造呈现此组件时使用的外观 (L&F) 类名称的后缀。
 booleangetValueIsAdjusting()
          返回数据模型的 isAdjusting 属性的值。
 intgetVisibleRowCount()
          返回首选可见行数。
 PointindexToLocation(int index)
          返回 JList 坐标中指定项的原点。
 booleanisSelectedIndex(int index)
          如果选择了指定的索引,则返回 true。
 booleanisSelectionEmpty()
          如果什么也没有选择,则返回 true。
 intlocationToIndex(Point location)
          将 JList 坐标中的点转换为该处单元最接近的索引。
protected  StringparamString()
          返回此 JList 的字符串表示形式。
 voidremoveListSelectionListener(ListSelectionListener listener)
          从每次选择发生更改时要通知的列表中移除侦听器。
 voidremoveSelectionInterval(int index0, int index1)
          将选择设置为指定间隔和当前选择的差集。
 voidsetCellRenderer(ListCellRenderer cellRenderer)
          设置用于绘制列表中每个单元的委托。
 voidsetDragEnabled(boolean b)
          设置 dragEnabled 属性,该属性必须为 true 才能启用对此组件的自动拖动处理(拖放操作的第一部分)。
 voidsetFixedCellHeight(int height)
          设置列表中每个单元的高度。
 voidsetFixedCellWidth(int width)
          设置列表中每个单元的宽度。
 voidsetLayoutOrientation(int layoutOrientation)
          定义布置列表单元的方式。
 voidsetListData(Object[] listData)
          根据一个 object 数组构造 ListModel,然后对其应用 setModel
 voidsetListData(Vector<?> listData)
          根据 Vector 构造 ListModel,然后对其应用 setModel
 voidsetModel(ListModel model)
          设置表示列表内容或“值”的模型,并在通知 PropertyChangeListener 之后清除列表选择。
 voidsetPrototypeCellValue(Object prototypeCellValue)
          计算 fixedCellWidthfixedCellHeight 属性,方法是针对指定值将 cellRenderer 配置为索引等于零,然后计算渲染器组件的首选大小。
 voidsetSelectedIndex(int index)
          选择单个单元。
 voidsetSelectedIndices(int[] indices)
          选择一组单元。
 voidsetSelectedValue(Object anObject, boolean shouldScroll)
          从列表中选择指定的对象。
 voidsetSelectionBackground(Color selectionBackground)
          设置所选单元的背景色。
 voidsetSelectionForeground(Color selectionForeground)
          设置所选单元的前景色。
 voidsetSelectionInterval(int anchor, int lead)
          选择指定的间隔。
 voidsetSelectionMode(int selectionMode)
          确定允许单项选择还是多项选择。
 voidsetSelectionModel(ListSelectionModel selectionModel)
          将列表的 selectionModel 设置为非 nullListSelectionModel 实现。
 voidsetUI(ListUI ui)
          设置呈现此组件的外观 (L&F) 对象。
 voidsetValueIsAdjusting(boolean b)
          将数据模型的 isAdjusting 属性设置为 true,这样完成所有选择事件时就会生成单个事件(例如,在选择模式的列表上拖动鼠标时)。
 voidsetVisibleRowCount(int visibleRowCount)
          设置不使用滚动条可以在列表中显示的首选行数,这一点由最近的 JViewport 祖先(如果有)确定。
 voidupdateUI()
          根据当前外观的值重置 UI 属性。
 
从类 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
 
从类 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
 
从类 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
 
从类 java.lang.Object 继承的方法
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

字段详细信息

VERTICAL

public static final int VERTICAL
指示默认布局:一列单元。

从以下版本开始:
1.4
另请参见:
setLayoutOrientation(int), 常量字段值

VERTICAL_WRAP

public static final int VERTICAL_WRAP
指示“报纸样式”布局,单元按先纵向后横向流动。

从以下版本开始:
1.4
另请参见:
setLayoutOrientation(int), 常量字段值

HORIZONTAL_WRAP

public static final int HORIZONTAL_WRAP
指示“报纸样式”,单元按先横向后纵向流动。

从以下版本开始:
1.4
另请参见:
setLayoutOrientation(int), 常量字段值
构造方法详细信息

JList

public JList(ListModel dataModel)
构造一个 JList,使其使用指定的非 null 模型显示元素。所有 JList 构造方法都委派给此方法。

参数:
dataModel - 此列表的数据模型
抛出:
IllegalArgumentException - 如果 dataModelnull

JList

public JList(Object[] listData)
构造一个 JList,使其显示指定数组中的元素。此构造方法仅委派给 ListModel 构造方法。

参数:
listData - 要加载到数据模型中的 Object 的数组

JList

public JList(Vector<?> listData)
构造一个 JList,使其显示指定 Vector 中的元素。此构造方法仅委派给 ListModel 构造方法。

参数:
listData - 要加载到数据模型中的 Vector

JList

public JList()
构造一个使用空模型的 JList

方法详细信息

getUI

public ListUI getUI()
返回呈现此组件的外观 (L&F) 对象。

返回:
呈现此组件的 ListUI 对象

setUI

public void setUI(ListUI ui)
设置呈现此组件的外观 (L&F) 对象。

参数:
ui - ListUI L&F 对象
另请参见:
UIDefaults.getUI(javax.swing.JComponent)