The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
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.本节使用这些示例作为后续讨论的基础。
![]() |
![]() |
ListDialog |
ListDemo |
There are three ways to create a list model:创建列表模型有三种方法:
DefaultListModel
.DefaultListModel
。AbstractListModel
and implement the getSize
and getElementAt
methods inherited from the ListModel
interface.AbstractListModel
子类化,并实现从ListModel
接口继承的getSize
和getElementAt
方法。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 |
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
的另一个常见用法是在列表的滚动窗格中指定列表希望显示的行数。
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. ListDialog
和ListDemo
都将选择模式设置为SINGLE_SELECTION
(由ListSelectionModel
定义的常量),以便只能选择列表中的一项。The following table describes the three list selection modes:下表描述了三种列表选择模式:
SINGLE_SELECTION ![]() |
|
SINGLE_INTERVAL_SELECTION ![]() |
|
MULTIPLE_INTERVAL_SELECTION ![]() |
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
. valueChanged
。Here 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
方法返回true
。This 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.是一个示例,演示如何在列表选择模型上侦听列表选择事件,并允许您动态更改列表的选择模式。
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 下面的代码片段显示了在Fire按钮上注册的操作监听器的actionPerformed
method for the action listener registered on the Fire button. 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.DefaultListModel
的addElement
方法。
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
的示例,但添加了在列表中向上或向下移动项目的按钮。
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 默认单元格渲染器知道如何显示字符串和图标,并通过调用Object
s by invoking toString
. toString
显示Object
。If 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:采取以下步骤为列表提供自定义单元格渲染器:
ListCellRenderer
interface.ListCellRenderer
接口的类。setCellRenderer
using the instance as an argument.setCellRenderer
。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 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
对象上调用的其他方法是其超类提供的setPreferredSize
。See 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分为以下几类:
JList(ListModel) JList(Object[]) JList(Vector) JList() |
ListModel ; you should not subsequently modify the passed-in array or Vector .ListModel ;随后不应修改传入的数组或Vector 。 |
void setModel(ListModel) ListModel getModel() |
|
void setListData(Object[]) void setListData(Vector) |
ListModel .ListModel 。 |
void setVisibleRowCount(int) int getVisibleRowCount() |
visibleRowCount property. visibleRowCount 属性。VERTICAL layout orientation, this sets or gets the preferred number of rows to display without requiring scrolling. VERTICAL 布局方向,这设置或获取不需要滚动即可显示的首选行数。HORIZONTAL_WRAP or VERTICAL_WRAP layout orientations, it defines how the cells wrap. HORIZONTAL_WRAP (水平缠绕)或VERTICAL_WRAP (垂直缠绕)布局方向,它定义了单元格的缠绕方式。setLayoutOrientation(int) 。VERTICAL .VERTICAL 。 |
void setLayoutOrientation(int) int getLayoutOrientation() |
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() |
|
void ensureIndexIsVisible(int) |
void addListSelectionListener(ListSelectionListener) |
|
void setSelectedIndex(int) void setSelectedIndices(int[]) void setSelectedValue(Object, boolean) void setSelectionInterval(int, int) |
setSelectionMode to set what ranges of selections are acceptable. setSelectionMode 设置可接受的选择范围。 |
int getAnchorSelectionIndex() int getLeadSelectionIndex() int getSelectedIndex() int getMinSelectionIndex() int getMaxSelectionIndex() int[] getSelectedIndices() Object getSelectedValue() Object[] getSelectedValues() |
|
void setSelectionMode(int) int getSelectionMode() |
SINGLE_SELECTION , SINGLE_INTERVAL_SELECTION , or MULTIPLE_INTERVAL_SELECTION (the default), which are defined in ListSelectionModel .SINGLE_SELECTION 、SINGLE_INTERVAL_SELECTION 或MULTIPLE_INTERVAL_SELECTION (默认值),它们在ListSelectionModel 中定义。 |
void clearSelection() boolean isSelectionEmpty() |
|
boolean isSelectedIndex(int) |
int getNextMatch(String, int, javax.swing.text.Position.Bias) |
Position.Bias.Forward or Position.Bias.Backward . Position.Bias.Forward 或Position.Bias.Backward 。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.getNextMatch("Matisse", 5, javax.swing.text.Position.Bias.Forward) 在索引5处的项中搜索字符串“Matisse”(如有必要),然后在索引0、索引1等处搜索。 |
void setDragEnabled(boolean) boolean getDragEnabled() |
This table shows the examples that use 下表显示了使用JList
and where those examples are described.JList
的示例以及这些示例的描述位置。
SplitPaneDemo |
||
ListDemo |
||
ListDialog |
||
ListDataEventDemo |
||
ListSelectionDemo |
||
SharedModelDemo |
Using Models |
ListSelectionDemo so that the list and table share the same data model.ListSelectionDemo ,使列表和表共享相同的数据模型。 |
CustomComboBoxDemo |
See the Using JavaFX UI Controls: List View tutorial to learn how to create lists in JavaFX.请参阅使用JavaFXUI控件:列表视图教程,了解如何在JavaFX中创建列表。