Documentation

The Java™ Tutorials
Hide TOC
How to Use Lists如何使用列表
Trail: Creating a GUI With Swing
Lesson: Using Swing Components
Section: How to Use Various Components

How to Use Lists如何使用列表

A JList presents the user with a group of items, displayed in one or more columns, to choose from. JList向用户提供一组项目,显示在一列或多列中,供用户选择。Lists can have many items, so they are often put in scroll panes.列表可以有许多项,因此它们通常放在滚动窗格中。

In addition to lists, the following Swing components present multiple selectable items to the user: combo boxes, menus, tables, and groups of check boxes or radio buttons. 除了列表之外,以下Swing组件还为用户提供了多个可选项:组合框菜单表格以及复选框单选按钮组。To display hierarchical data, use a tree.要显示分层数据,请使用

The following figures shows two applications that use lists. 下图显示了两个使用列表的应用程序。This section uses these examples as a basis for the discussions that follow.本节使用这些示例作为后续讨论的基础。

A snapshot of ListDialog, which displays a simple list A snapshot of ListDemo, which lets you add and remove list items
ListDialog
(used by ListDialogRunner)(由ListDialogRunner使用)
ListDemo

Try this: 
  1. Click the Launch button to run ListDemo using Java™ Web Start (download JDK 7 or later). 单击启动按钮,使用Java™Web启动运行ListDemo(下载JDK 7或更高版本)。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引Launches the ListDemo example
  2. Click the Launch button to run ListDialogRunner. 单击启动按钮运行ListDialogRunner。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引Launches the ListDialogRunner example
  3. To bring up the ListDialog, click the Pick a new name... button in the window titled Name That Baby.要打开列表对话框,请单击标题为“给婴儿命名”窗口中的“选择新名称…”按钮。
    The resulting dialog is a ListDialog instance that has been customized to have the title Name Chooser.生成的对话框是一个ListDialog实例,该实例已自定义为具有标题名称选择器。
  4. In ListDemo, try adding (hiring) and removing (firing) a few items.在ListDemo中,尝试添加(招聘)和删除(解雇)一些项目。

This rest of this section discusses the following topics:本节其余部分讨论以下主题:

Creating a Model创建模型

There are three ways to create a list model:创建列表模型有三种方法:

Initializing a List初始化列表

Here is the code from ListDialog.java that creates and sets up its list:下面是ListDialog.java中创建和设置列表的代码:

list = new JList(data); //data has type Object[]
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
...
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(250, 80));

The code passes an array to the list's constructor. 代码将数组传递给列表的构造函数。The array is filled with strings that were passed in from another object. 数组中填充了从另一个对象传入的字符串。In our example, the strings happen to be boys' names.在示例中,字符串恰好是男孩的名字。

Other JList constructors let you initialize a list from a Vector or from an object that adheres to the ListModel interface. 其他JList构造函数允许您从Vector或遵循ListModel接口的对象初始化列表。If you initialize a list with an array or vector, the constructor implicitly creates a default list model. 如果使用数组或向量初始化列表,构造函数将隐式创建默认列表模型。The default list model is immutable — you cannot add, remove, or replace items in the list. 默认列表模型是不可变的;无法添加、删除或替换列表中的项目。To create a list whose items can be changed individually, set the list's model to an instance of a mutable list model class, such as an instance of DefaultListModel. 要创建其项可以单独更改的列表,请将列表的模型设置为可变列表模型类的实例,例如DefaultListModel的实例。You can set a list's model when you create the list or by calling the setModel method. 您可以在创建列表时或通过调用setModel方法来设置列表的模型。See Adding Items to and Removing Items from a List for an example.有关示例,请参阅向列表中添加项目和从列表中删除项目

The call to setSelectionMode specifies how many items the user can select, and whether they must be contiguous; the next section tells you more about selection modes.setSelectionMode的调用指定用户可以选择多少项,以及它们是否必须连续;下一节将详细介绍选择模式。

The call to setLayoutOrientation lets the list display its data in multiple columns. 调用setLayoutOrientation可以让列表在多列中显示其数据。The value JList.HORIZONTAL_WRAP specifies that the list should display its items from left to right before wrapping to a new row. Another possible value is JList.VERTICAL_WRAP, which specifies that the data be displayed from top to bottom (as usual) before wrapping to a new column. JList.VERTICAL_WRAP指定列表应在换行到新行之前从左到右显示其项。另一个可能的值是JList.HORIZONTAL_WRAP,它指定数据在包装到新列之前从上到下(通常)显示。The following figures show these two wrapping possibilities, together with the default, JList.VERTICAL.下图显示了这两种包装可能性,以及默认的JList.VERTICAL

HORIZONTAL_WRAP VERTICAL_WRAP VERTICAL
HORIZONTAL_WRAP VERTICAL_WRAP VERTICAL

In combination with the call to setLayoutOrientation, invoking setVisibleRowCount(-1) makes the list display the maximum number of items possible in the available space onscreen. 结合调用setLayoutOrientation,调用setVisibleRowCount(-1)将使列表显示屏幕上可用空间中的最大项目数。Another common use of setVisibleRowCount is to specify to the lists's scroll pane how many rows the list prefers to display.setVisibleRowCount的另一个常见用法是在列表的滚动窗格中指定列表希望显示的行数。

Selecting Items in a List选择列表中的项目

A list uses an instance of ListSelectionModel to manage its selection. 列表使用ListSelectionModel的实例来管理其选择。By default, a list selection model allows any combination of items to be selected at a time. 默认情况下,列表选择模型允许一次选择项目的任意组合。You can specify a different selection mode by calling the setSelectionMode method on the list. 通过调用列表上的setSelectionMode方法,可以指定不同的选择模式。For example, both ListDialog and ListDemo set the selection mode to SINGLE_SELECTION (a constant defined by ListSelectionModel) so that only one item in the list can be selected. 例如,ListDialogListDemo都将选择模式设置为SINGLE_SELECTION(由ListSelectionModel定义的常量),以便只能选择列表中的一项。The following table describes the three list selection modes:下表描述了三种列表选择模式:

Mode模式 Description描述
SINGLE_SELECTION
Single selection means only one item can be selected at once

Only one item can be selected at a time. 一次只能选择一个项目。When the user selects an item, any previously selected item is deselected first.当用户选择一个项目时,将首先取消选择任何先前选择的项目。
SINGLE_INTERVAL_SELECTION
Single interval selection means multiple, contiguous items can be selected at once

Multiple, contiguous items can be selected. 可以选择多个连续项。When the user begins a new selection range, any previously selected items are deselected first.当用户开始一个新的选择范围时,将首先取消选择任何先前选择的项目。
MULTIPLE_INTERVAL_SELECTION 
Multiple interval selection means any combination of items can be selected at once

The default. 默认值。Any combination of items can be selected. 可以选择项目的任意组合。The user must explicitly deselect items.用户必须明确取消选择项目。

No matter which selection mode your list uses, the list fires list selection events whenever the selection changes. 无论列表使用哪种选择模式,只要选择发生更改,列表都会触发列表选择事件。You can process these events by adding a list selection listener to the list with the addListSelectionListener method. 您可以通过使用addListSelectionListener方法向列表添加列表选择侦听器来处理这些事件。A list selection listener must implement one method: valueChanged. 列表选择侦听器必须实现一个方法:valueChangedHere is the valueChanged method for the listener in ListDemo:下面是ListDemo中监听器的valueChanged方法:

public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting() == false) {

        if (list.getSelectedIndex() == -1) {
        //No selection, disable fire button.
            fireButton.setEnabled(false);

        } else {
        //Selection, enable the fire button.
            fireButton.setEnabled(true);
        }
    }
}

Many list selection events can be generated from a single user action such as a mouse click. 许多列表选择事件可以从单个用户操作(如鼠标单击)生成。The getValueIsAdjusting method returns true if the user is still manipulating the selection. 如果用户仍在操作选择,则getValueIsAdjusting方法返回trueThis particular program is interested only in the final result of the user's action, so the valueChanged method does something only if getValueIsAdjusting returns false.这个特定程序只对用户操作的最终结果感兴趣,因此valueChanged方法仅在getValueIsAdjusting返回false时才执行某些操作。

Because the list is in single-selection mode, this code can use getSelectedIndex to get the index of the just-selected item. 由于列表处于单选模式,因此此代码可以使用getSelectedIndex获取刚刚选择的项的索引。JList provides other methods for setting or getting the selection when the selection mode allows more than one item to be selected. 当选择模式允许选择多个项目时,JList提供设置或获取选择的其他方法。If you want, you can listen for events on the list's list selection model rather than on the list itself. 如果需要,可以侦听列表的列表选择模型上的事件,而不是列表本身上的事件。ListSelectionDemo is an example that shows how to listen for list selection events on the list selection model and lets you change the selection mode of a list dynamically.是一个示例,演示如何在列表选择模型上侦听列表选择事件,并允许您动态更改列表的选择模式。

Adding Items to and Removing Items from a List向列表中添加项目和从列表中删除项目

The ListDemo example that we showed previously features a list whose contents can change. 我们之前展示的ListDemo示例提供了一个内容可以更改的列表。You can find the source code for ListDemo in ListDemo.java. 您可以在ListDemo.java中找到ListDemo的源代码。Here is the ListDemo code that creates a mutable list model object, puts the initial items in it, and uses the list model to create a list:下面是创建可变列表模型对象的ListDemo代码,将初始项放入其中,并使用列表模型创建列表:

listModel = new DefaultListModel();
listModel.addElement("Jane Doe");
listModel.addElement("John Smith");
listModel.addElement("Kathy Green");


list = new JList(listModel);

This particular program uses an instance of DefaultListModel, a class provided by Swing. 这个特定的程序使用了DefaultListModel的一个实例,这是Swing提供的一个类。In spite of the class name, a list does not have a DefaultListModel unless your program explicitly makes it so. 不管类名如何,列表都没有DefaultListModel,除非程序显式地这样做。If DefaultListModel does not suit your needs, you can write a custom list model, which must adhere to the ListModel interface.如果DefaultListModel不适合您的需要,您可以编写一个自定义列表模型,它必须符合ListModels接口。

The following code snippet shows the actionPerformed method for the action listener registered on the Fire button. 下面的代码片段显示了在Fire按钮上注册的操作监听器的actionPerformed方法。The bold line of code removes the selected item in the list. 粗体代码行将删除列表中的选定项。The remaining lines in the method disable the fire button if the list is now empty, and make another selection if it is not.如果列表现在为空,则该方法中的其余行将禁用fire按钮,如果列表为空,请进行另一选择。

public void actionPerformed(ActionEvent e) {
    int index = list.getSelectedIndex();
    listModel.remove(index);

    int size = listModel.getSize();

    if (size == 0) { //Nobody's left, disable firing.
        fireButton.setEnabled(false);

    } else { //Select an index.
        if (index == listModel.getSize()) {
            //removed item in last position
            index--;
        }

        list.setSelectedIndex(index);
        list.ensureIndexIsVisible(index);
    }
}

Here is the actionPerformed method for the action listener shared by the Hire button and the text field:以下是由“雇佣”按钮和文本字段共享的操作侦听器的actionPerformed方法:

public void actionPerformed(ActionEvent e) {
    String name = employeeName.getText();

    //User did not type in a unique name...
    if (name.equals("") || alreadyInList(name)) {
        Toolkit.getDefaultToolkit().beep();
        employeeName.requestFocusInWindow();
        employeeName.selectAll();
        return;
    }

    int index = list.getSelectedIndex(); //get selected index
    if (index == -1) { //no selection, so insert at beginning
        index = 0;
    } else {           //add after the selected item
        index++;
    }
listModel.insertElementAt(employeeName.getText(), index);

    //Reset the text field.
    employeeName.requestFocusInWindow();
    employeeName.setText("");

    //Select the new item and make it visible.
    list.setSelectedIndex(index);
    list.ensureIndexIsVisible(index);
}

This code uses the list model's insertElementAt method to insert the new name after the current selection or, if no selection exists, at the beginning of the list. 此代码使用列表模型的insertElementAt方法在当前选择后插入新名称,如果不存在选择,则在列表的开头插入新名称。If you just wish to add to the end of the list, you can use DefaultListModel's addElement method instead.如果您只想添加到列表的末尾,可以使用DefaultListModeladdElement方法。

Whenever items are added to, removed from, or modified in a list, the list model fires list data events. 无论何时在列表中添加、删除或修改项,列表模型都会触发列表数据事件。Refer to How to Write a List Data Listener for information about listening for these events. 有关侦听这些事件的信息,请参阅如何编写列表数据侦听器That section contains an example that is similar to ListDemo, but adds buttons that move items up or down in the list.该部分包含一个类似于ListDemo的示例,但添加了在列表中向上或向下移动项目的按钮。

Writing a Custom Cell Renderer编写自定义单元格渲染器

A list uses an object called a cell renderer to display each of its items. 列表使用称为单元渲染器的对象来显示其每个项。The default cell renderer knows how to display strings and icons and it displays Objects by invoking toString. 默认单元格渲染器知道如何显示字符串和图标,并通过调用toString显示ObjectIf you want to change the way the default renderer display icons or strings, or if you want behavior different than what is provided by toString, you can implement a custom cell renderer. 如果希望更改默认渲染器显示图标或字符串的方式,或者希望行为与toString提供的不同,可以实现自定义单元格渲染器。Take these steps to provide a custom cell renderer for a list:采取以下步骤为列表提供自定义单元格渲染器:

We do not provide an example of a list with a custom cell renderer, but we do have an example of a combo box with a custom renderer — and combo boxes use the same type of renderer as lists. 我们不提供具有自定义单元格渲染器的列表示例,但我们确实提供了具有自定义渲染器的组合框示例;组合框使用与列表相同类型的渲染器。See the example described in Providing a Custom Renderer.请参见提供自定义渲染器中描述的示例。

The List API列表API

The following tables list the commonly used JList constructors and methods. 下表列出了常用的JList构造函数和方法。Other methods you are most likely to invoke on a JList object are those such as setPreferredSize that its superclasses provide. 您最可能在JList对象上调用的其他方法是其超类提供的setPreferredSizeSee The JComponent API for tables of commonly used inherited methods.有关常用继承方法的表,请参阅JComponent API

Much of the operation of a list is managed by other objects. 列表的大部分操作由其他对象管理。The items in the list are managed by a list model object, the selection is managed by a list selection model object, and most programs put a list in a scroll pane to handle scrolling. 列表中的项目由列表模型对象管理,选择由列表选择模型对象管理。大多数程序将列表放在滚动窗格中以处理滚动。For the most part, you do not need to worry about the models because JList creates them as necessary and you interact with them implicitly with JList's convenience methods.在大多数情况下,您不需要担心模型,因为JList根据需要创建模型,您可以使用JList的方便方法隐式地与它们交互。

That said, the API for using lists falls into these categories:也就是说,使用列表的API分为以下几类:

Initializing List Data初始化列表数据
Method or Constructor方法或构造函数 Purpose目的
JList(ListModel)
JList(Object[])
JList(Vector)
JList()
Create a list with the initial list items specified. 使用指定的初始列表项创建列表。The second and third constructors implicitly create an immutable ListModel; you should not subsequently modify the passed-in array or Vector.第二和第三构造函数隐式地创建不可变ListModel;随后不应修改传入的数组或Vector
void setModel(ListModel)
ListModel getModel()
Set or get the model that contains the contents of the list.设置或获取包含列表内容的模型。
void setListData(Object[])
void setListData(Vector)
Set the items in the list. 设置列表中的项目。These methods implicitly create an immutable ListModel.这些方法隐式地创建了一个不可变的ListModel
Displaying the List显示列表
Method方法 Purpose目的
void setVisibleRowCount(int)
int getVisibleRowCount()
Set or get the visibleRowCount property. 设置或获取visibleRowCount属性。For a VERTICAL layout orientation, this sets or gets the preferred number of rows to display without requiring scrolling. 对于VERTICAL布局方向,这设置或获取不需要滚动即可显示的首选行数。For the HORIZONTAL_WRAP or VERTICAL_WRAP layout orientations, it defines how the cells wrap. 对于HORIZONTAL_WRAP(水平缠绕)或VERTICAL_WRAP(垂直缠绕)布局方向,它定义了单元格的缠绕方式。See the setLayoutOrientation(int) for more information. 有关更多信息,请参阅setLayoutOrientation(int)The default value of this property is VERTICAL.此属性的默认值为VERTICAL
void setLayoutOrientation(int)
int getLayoutOrientation()
Set or get the way list cells are laid out. 设置或获取列表单元格的布局方式。The possible layout formats are specified by the JList-defined values VERTICAL (a single column of cells; the default), HORIZONTAL_WRAP ("newspaper" style with the content flowing horizontally then vertically), and VERTICAL_WRAP ("newspaper" style with the content flowing vertically then horizontally).可能的布局格式由JList定义的值指定:VERTICAL(一列单元格;默认值)、HORIZONTAL_WRAP(“报纸”样式,内容先水平后垂直流动)和VERTICAL_WRAP(“报纸”风格,内容先垂直后水平流动)。
int getFirstVisibleIndex()
int getLastVisibleIndex()
Get the index of the first or last visible item.获取第一个或最后一个可见项的索引。
void ensureIndexIsVisible(int) Scroll so that the specified index is visible within the viewport that this list is in.滚动以使指定索引在该列表所在的视口中可见。
Managing the List's Selection管理列表的选择
Method方法 Purpose目的
void addListSelectionListener(ListSelectionListener) Register to receive notification of selection changes.注册以接收选择更改通知。
void setSelectedIndex(int)
void setSelectedIndices(int[])
void setSelectedValue(Object, boolean)
void setSelectionInterval(int, int)
Set the current selection as indicated. 如图所示设置当前选择。Use setSelectionMode to set what ranges of selections are acceptable. 使用setSelectionMode设置可接受的选择范围。The boolean argument specifies whether the list should attempt to scroll itself so that the selected item is visible.布尔参数指定列表是否应尝试滚动自身,以便所选项目可见。
int getAnchorSelectionIndex()
int getLeadSelectionIndex()
int getSelectedIndex()
int getMinSelectionIndex()
int getMaxSelectionIndex()
int[] getSelectedIndices()
Object getSelectedValue()
Object[] getSelectedValues()
Get information about the current selection as indicated.获取有关当前选择的信息,如图所示。
void setSelectionMode(int)
int getSelectionMode()
Set or get the selection mode. Acceptable values are: SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION, or MULTIPLE_INTERVAL_SELECTION (the default), which are defined in ListSelectionModel.设置或获取选择模式。可接受的值有:SINGLE_SELECTIONSINGLE_INTERVAL_SELECTIONMULTIPLE_INTERVAL_SELECTION(默认值),它们在ListSelectionModel中定义。
void clearSelection()
boolean isSelectionEmpty()
Set or get whether any items are selected.设置或获取是否选择了任何项。
boolean isSelectedIndex(int) Determine whether the specified index is selected.确定是否选择指定的索引。
Managing List Data管理列表数据
Class or Method类或方法 Purpose目的
int getNextMatch(String, int, javax.swing.text.Position.Bias) Given the starting index, search through the list for an item that starts with the specified string and return that index (or -1 if the string is not found). 给定起始索引,在列表中搜索以指定字符串开头的项,并返回该索引(如果未找到字符串,则返回-1)。The third argument, which specifies the search direction, can be either Position.Bias.Forward or Position.Bias.Backward. 第三个参数指定搜索方向,可以是Position.Bias.ForwardPosition.Bias.BackwardFor example, if you have a 6-item list, getNextMatch("Matisse", 5, javax.swing.text.Position.Bias.Forward) searches for the string "Matisse" in the item at index 5, then (if necessary) at index 0, index 1, and so on.例如,如果您有一个6项列表,则getNextMatch("Matisse", 5, javax.swing.text.Position.Bias.Forward)在索引5处的项中搜索字符串“Matisse”(如有必要),然后在索引0、索引1等处搜索。
void setDragEnabled(boolean)
boolean getDragEnabled()
Set or get the property that determines whether automatic drag handling is enabled. 设置或获取确定是否启用自动拖动处理的属性。See Drag and Drop and Data Transfer for more details.有关详细信息,请参阅拖放和数据传输

Examples that Use Lists使用列表的示例

This table shows the examples that use JList and where those examples are described.下表显示了使用JList的示例以及这些示例的描述位置。

Example示例 Where Described描述位置 Notes备注
SplitPaneDemo How to Use Split Panes如何使用拆分窗格 Contains a single-selection, immutable list.包含单个选择,不可变列表。
ListDemo This section本节 Demonstrates how to add and remove items from a list at runtime.演示如何在运行时从列表中添加和删除项。
ListDialog This section, 本节,How to Use BoxLayout如何使用BoxLayout Implements a modal dialog with a single-selection list.使用单个选择列表实现模式对话框。
ListDataEventDemo How to Write a List Data Listener如何编写列表数据侦听器 Demonstrates listening for list data events on a list model.演示在列表模型上侦听列表数据事件。
ListSelectionDemo How to Write a List Selection Listener如何编写列表选择侦听器 Contains a list and a table that share the same selection model. 包含共享相同选择模型的列表和表。You can dynamically choose the selection mode.您可以动态选择选择模式。
SharedModelDemo Using Models Modifies ListSelectionDemo so that the list and table share the same data model.修改ListSelectionDemo,使列表和表共享相同的数据模型。
CustomComboBoxDemo Providing a Custom Renderer提供自定义渲染器 Shows how to provide a custom renderer for a combo box. 显示如何为组合框提供自定义呈现器。Because lists and combo boxes use the same type of renderer, you can use what you learn there an apply it to lists. 因为列表和组合框使用相同类型的渲染器,所以您可以使用在那里学到的知识将其应用于列表。In fact, a list and a combo box can share a renderer.事实上,列表和组合框可以共享一个渲染器。

See the Using JavaFX UI Controls: List View tutorial to learn how to create lists in JavaFX.请参阅使用JavaFXUI控件:列表视图教程,了解如何在JavaFX中创建列表。


Previous page: How to Use Layered Panes
Next page: How to Use Menus