⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 list.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 3 页
字号:
<IMG SRC="../../figures/uiswing/components/NameChooserMetal.png" WIDTH="278" HEIGHT="191" ALT="A snapshot of ListDialog, which displays a simple list"><td><IMG SRC="../../figures/uiswing/components/ListDemoMetal.png" WIDTH="256" HEIGHT="163" ALT="A snapshot of ListDemo, which lets you add and remove list items"><tr valign=top><td align=center><b>ListDialog<br>(used by ListDialogRunner)</b><td align=center><b>ListDemo</b></table></p><blockquote><hr><strong>Try this:</strong>&nbsp;<ol><li>Run <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/ListDialogRunner.jnlp">ListDialogRunner</a> and<a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/ListDemo.jnlp">ListDemo</a> (both require release 6)using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java<sup><font size=-2>TM</font></sup> Web Start</a>.    Or, to compile and run the examples yourself,     consult the     <a href="examples/index.html">example index</a>.<li> To bring up the ListDialog,     click the Pick a new name... button     in the window titled Name That Baby.     <br>     The resulting dialog is a ListDialog instance     that's been customized to have the title Name Chooser.<li> In ListDemo,     try adding (hiring) and removing (firing) a few items.</ol><hr></blockquote>This rest of this section discusses the following topics:<p><ul><li> <a href="#init">Initializing a List</a><li> <a href="#selection">Selecting Items in a List</a><li> <a href="#mutable">Adding Items to and Removing Items from a List</a><li> <a href="#renderer">Writing a Custom Cell Renderer</a><li> <a href="#api">The List API</a><li> <a href="#eg">Examples that Use Lists</a></ul><a name="init"></blockquote><h3>Initializing a List</h3></a><blockquote>Here is the code from<a class="SourceLink" target="_blank" href="examples/ListDialog.java"><code>ListDialog.java</code></a>that creates and sets up its list:<blockquote><pre>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));</pre></blockquote>The code passes an array to the list's constructor.The array is filled with stringsthat were passed in from another object.In our example, the strings happen to be boys' names.<p>Other <code>JList</code> constructors let you initializea list from a <code>Vector</code> or from anobject that adheres to the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/ListModel.html"><code>ListModel</code></a> interface.If you initialize a list with an array or vector,the constructor implicitly creates a default list model.The default list model is immutable &#151; 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 modelclass, such as an instance of<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/DefaultListModel.html"><code>DefaultListModel</code></a>.You can set a list's model when you create the listor by calling the <code>setModel</code> method.See<a href="#mutable">Adding Items to and Removing Items from a List</a>for an example.<p>The call to <code>setSelectionMode</code>specifies how many items the user can select,and whether they must be contiguous;the next section tells you more about selection modes.<p>The call to<code>setLayoutOrientation</code>lets the list display its data in multiple columns.The value <code>JList.HORIZONTAL_WRAP</code>specifies that the list should display its items from left to rightbefore wrapping to a new row.Another possible value is <code>JList.VERTICAL_WRAP</code>,which specifies that the data be displayed from top to bottom(as usual) before wrapping to a new column.The following figures show these two wrapping possibilities,together with the default, <code>JList.VERTICAL</code>.<p><table><tr><td><IMG SRC="../../figures/uiswing/components/14ListDialog-hwrap.png" WIDTH="146" HEIGHT="84" ALT="HORIZONTAL_WRAP"><td><IMG SRC="../../figures/uiswing/components/14ListDialog-vwrap.png" WIDTH="142" HEIGHT="84" ALT="VERTICAL_WRAP"><td><IMG SRC="../../figures/uiswing/components/14ListDialog-nowrap.png" WIDTH="102" HEIGHT="84" ALT="VERTICAL"></tr><tr><td><code>HORIZONTAL_WRAP</code></td><td><code>VERTICAL_WRAP</code></td><td><code>VERTICAL</code></td></tr></table><p>In combination with the call to <code>setLayoutOrientation</code>,invoking <code>setVisibleRowCount(-1)</code>makes the list display the maximum number of itemspossible in the available space onscreen.Another common use of <code>setVisibleRowCount</code>is to specify to the lists's scroll panehow many rows the list prefers to display.</blockquote><a name="selection"><h3>Selecting Items in a List</h3></a><blockquote>A list uses an instance of<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/ListSelectionModel.html"><code>ListSelectionModel</code></a> to manage its selection.By default, a list selection model allows any combination of itemsto be selected at a time.You can specify a different selection mode by calling the<code>setSelectionMode</code> method on the list.For example, both <code>ListDialog</code> and <code>ListDemo</code>set the selection mode to <code>SINGLE_SELECTION</code>(a constant defined by <code>ListSelectionModel</code>)so that only one item in the list can be selected.The following table describes the three list selection modes:<p><blockquote><table><tr><th align=left>Mode</th><th align=left>Description</th></tr><tr><td valign=top><code>SINGLE_SELECTION</code><br><IMG SRC="../../figures/uiswing/components/SingleSelection.gif" WIDTH="80" HEIGHT="82" ALT="Single selection means only one item can be selected at once"><br><br></td><td valign=top>Only one item can be selected at a time.    When the user selects an item,    any previously selected item is deselected first.</td></tr><tr><td valign=top><code>SINGLE_INTERVAL_SELECTION</code><br><IMG SRC="../../figures/uiswing/components/SingleIntervalSelection.gif" WIDTH="80" HEIGHT="82" ALT="Single interval selection means multiple, contiguous items can be selected at once"><br><br></td><td valign=top>Multiple, contiguous items can be selected.    When the user begins a new selection range,    any previously selected items are deselected first.</td></tr><tr><td valign=top><code>MULTIPLE_INTERVAL_SELECTION&nbsp;</code><br><IMG SRC="../../figures/uiswing/components/MultipleIntervalSelection.gif" WIDTH="80" HEIGHT="82" ALT="Multiple interval selection means any combination of items can be selected at once"><br><br></td><td valign=top>The default. Any combination of items can be selected.    The user must explicitly deselect items.</td></tr></table></blockquote><p>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<a href="../events/listselectionlistener.html">list selection listener</a>to the list with the <code>addListSelectionListener</code> method.A list selection listener must implement one method: <code>valueChanged</code>.Here's the <code>valueChanged</code> method forthe listener in <code>ListDemo</code>:<blockquote><pre>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);        }    }}</pre></blockquote>Many list selection events can begenerated from a single user action such as a mouse click.The <code>getValueIsAdjusting</code> method returns <code>true</code>if the user is still manipulating the selection.This particular program is interested only in the final resultof the user's action,so the <code>valueChanged</code> methoddoes something only if <code>getValueIsAdjusting</code> returns<code>false</code>.<p>Because the list is in single-selection mode,this code can use <code>getSelectedIndex</code> toget the index of the just-selected item.<code>JList</code> provides other methods for<a href="#selectionapi">setting or getting the selection</a>when the selection mode allows more than one item to be selected.If you want, you can listen for events on thelist's list selection modelrather than on the list itself.<a class="TutorialLink" target="_top" href="../events/examples/index.html#ListSelectionDemo">ListSelectionDemo</a> is an example thatshows how to listen for list selection events on the list selection modeland lets you change the selection mode of a list dynamically.</blockquote><a name="mutable"><h3>Adding Items to and Removing Items from a List</h3></a><blockquote>The ListDemo example that we showed previouslyfeatures a list whose contents can change.You can find the source code for ListDemo in<a class="SourceLink" target="_blank" href="examples/ListDemo.java"><code>ListDemo.java</code></a>.Here's the ListDemo codethat creates a mutable list model object,puts the initial items in it,and uses the list model to create a list:<blockquote><pre>listModel = new DefaultListModel();listModel.addElement("Debbie Scott");listModel.addElement("Scott Hommel");listModel.addElement("Alan Sommerer");list = new JList(listModel);</pre></blockquote>This particular program uses an instanceof <code>DefaultListModel</code>,a class provided by Swing.In spite of the class name, a list does not have a<code>DefaultListModel</code> unless yourprogram explicitly makes it so.If <code>DefaultListModel</code> doesn't suit your needs,you can write a custom list model,which must adhere to the <code>ListModel</code> interface.<p>The following code snippetshows the <code>actionPerformed</code> methodfor the action listener registered onthe <strong>Fire</strong> button.The bold line of code removes the selected item in the list.The remaining lines in the methoddisable the fire button if the list is now empty,and make another selection if it's not.<blockquote><pre>public void actionPerformed(ActionEvent e) {    int index = list.getSelectedIndex();    <strong>listModel.remove(index);</strong>    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);    }}</pre></blockquote><p>Here's the <code>actionPerformed</code> methodfor the action listener shared by the <strong>Hire</strong>button and the text field:<blockquote><pre>public void actionPerformed(ActionEvent e) {    String name = employeeName.getText();    //User didn't 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++;    }    <b>listModel.insertElementAt(employeeName.getText(), index);</b>    //Reset the text field.    employeeName.requestFocusInWindow();    employeeName.setText("");    //Select the new item and make it visible.    list.setSelectedIndex(index);    list.ensureIndexIsVisible(index);}</pre></blockquote>This code uses the list model's<code>insertElementAt</code> methodto insert the new name after the current selectionor, if no selection exists, at the beginning of the list.If you just wish to add to the end of the list,you can use<code>DefaultListModel</code>'s<code>addElement</code> method instead.<p>Whenever items are added to, removed from,or modified in a list,the list model fires list data events.Refer to<a class="TutorialLink" target="_top" href="../events/listdatalistener.html">How to Write a List Data Listener</a> for information about listening for these events.That section containsan example that is similar to <code>ListDemo</code>,but adds buttons that move items up or down in the list.</blockquote><a name="renderer"><h3>Writing a Custom Cell Renderer</h3></a><blockquote>A list uses an object called a cell rendererto display each of its items.The default cell renderer knows how to display strings and icons.If you want to put any other <code>Object</code> in a listor if you want to change the way the default renderer display iconsor strings, you can implement a custom cell renderer.Take these steps to provide a custom cell renderer for a list:<ul><li> Write a class that implements the

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -