_chapter 6.htm
来自「Core Java 2(中文名称:JAVA 2 核心技术 卷二:高级特性)这是英」· HTM 代码 · 共 1,429 行 · 第 1/5 页
HTM
1,429 行
<p class="docList">constructs a list that displays these items.</li>
<li>
<p class="docList"><tt>void setVisibleRowCount(int c)</tt></p>
<p class="docList">sets the preferred number of rows in the list that can be
displayed without a scroll bar.</li>
<li>
<p class="docList"><tt>void setSelectionMode(int mode)</tt></p>
<p class="docList">determines whether single-item or multiple-item selections
are allowed.</p>
<table cellSpacing="0" cellPadding="1" width="93%" border="1">
<colgroup span="3" align="left">
</colgroup>
<tr>
<td class="docTableCell" vAlign="top"><span class="docEmphasis">
Parameters:</span> </td>
<td class="docTableCell" vAlign="top"><tt>mode</tt> </td>
<td class="docTableCell" vAlign="top">one of <tt>SINGLE_SELECTION</tt>,
<tt>SINGLE_INTERVAL_SELECTION</tt>, <tt>MULTIPLE_INTERVAL_SELECTION</tt>
</td>
</tr>
</table>
<p> </li>
<li>
<p class="docList"><tt>void addListSelectionListener(ListSelectionListener
listener)</tt></p>
<p class="docList">adds to the list a listener that's notified each time a
change to the selection occurs.</li>
<li>
<p class="docList"><tt>Object[] getSelectedValues()</tt></p>
<p class="docList">returns the selected values or an empty array if the
selection is empty.</li>
<li>
<p class="docList"><tt>Object getSelectedValue()</tt></p>
<p class="docList">returns the first selected value or <tt>null</tt> if the
selection is empty.</li>
</ul>
<h5 class="docSection3Title" id="ch06lev3sec2"><tt>javax.swing.event.ListSelectionListener</tt></h5>
<p><img alt="graphics/api.gif" src="api.gif" border="0" width="46" height="45"><br>
</p>
<ul>
<li>
<p class="docList"><tt>void valueChanged(ListSelectionEvent e)</tt></p>
<p class="docList">is called whenever the list selection changes.</li>
</ul>
<h4 class="docSection2Title" id="ch06lev2sec2">List Models</h4>
<p class="docText">In the preceding section, you have seen the most common
method for using a list component:</p>
<ul>
<li>
<p class="docList">Specify a fixed set of strings for display in the list,</li>
<li>
<p class="docList">Add a scrollbar,</li>
<li>
<p class="docList">Trap the list selection events.</li>
</ul>
<p class="docText">In the remainder of the section on lists, we will cover more
complex situations that require a bit more finesse:</p>
<ul>
<li>
<p class="docList">Very long lists</li>
<li>
<p class="docList">Lists with changing contents</li>
<li>
<p class="docList">Lists that don't contain strings</li>
</ul>
<p class="docText">In the first example, we constructed a <tt>JList</tt>
component that held a fixed collection of strings. However, the collection of
choices in a list box is not always fixed. How do we add or remove items in the
list box? Somewhat surprisingly, there are no methods in the <tt>JList</tt>
class to achieve this. Instead, you have to understand a little more about the
internal design of the list component. As with text components, the list
component uses the model-view-controller design pattern to separate the visual
appearance (a column of items that are rendered in some way) from the underlying
data (a collection of objects).</p>
<p class="docText">The <tt>JList</tt> class is responsible for the visual
appearance of the data. It actually knows very little about how the data is
stored梐ll it knows is that it can retrieve the data through some object that
implements the <tt>ListModel</tt> interface:</p>
<pre>public interface ListModel
{
public int getSize();
public Object getElementAt(int i);
public void addListDataListener(ListDataListener l);
public void removeListDataListener(ListDataListener l);
}
</pre>
<p class="docText">Through this interface, the <tt>JList</tt> can get a count of
elements and retrieve each one of the elements. Also, the <tt>JList</tt> object
can add itself as a <span class="docEmphasis">list data listener.</span> It then
gets notified if the collection of elements changes, so that it can repaint the
list.</p>
<p class="docText">Why is this generality useful? Why doesn't the <tt>JList</tt>
object simply store a vector of objects?</p>
<p class="docText">Note that the interface doesn't specify how the objects are
stored. In particular, it doesn't force them to be stored at all! The <tt>
getElementAt</tt> method is free to recompute each value whenever it is called.
This is potentially useful if you want to show a very large collection without
having to store the values.</p>
<p class="docText">Here is a somewhat silly example: we let the user choose
among <span class="docEmphasis">all three-letter words</span> in a list box (see
<a class="docLink" href="#ch06fig02">Figure 6-2</a>).</p>
<center>
<h5 id="ch06fig02" class="docFigureTitle">Figure 6-2. Choosing from a very long list of
selections</h5>
<p>
<img alt="graphics/06fig02.gif" src="06fig02.gif" border="0" width="401" height="298"></p>
</center>
<p class="docText">There are 26 26 26 = 17,576 three-letter combinations. Rather
than storing all these combinations, we recompute them as requested when the
user scrolls through them.</p>
<p class="docText">This turns out to be easy to implement. The tedious part,
adding and removing listeners, has been done for us in the <tt>AbstractListModel</tt>
class which we extend. We only need to supply the <tt>getSize</tt> and <tt>
getElementAt</tt> methods:</p>
<pre>class WordListModel extends AbstractListModel
{
public WordListModel(int n) { length = n; }
public int getSize() { return (int)Math.pow(26, length); }
public Object getElementAt(int n)
{
// compute nth string
. . .
}
. . .
}
</pre>
<p class="docText">The computation of the <span class="docEmphasis">n</span>th
string is a bit technical梱ou'll find the details in the code listing in
<a class="docLink" href="#ch06list02">Example 6-2</a>.</p>
<p class="docText">Now that we supplied a model, we can simply build a list that
lets the user scroll through the elements supplied by the model:</p>
<pre>JList wordList = new JList(new WordListModel(3));
wordList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scrollPane = new JScrollPane(wordList);
</pre>
<p class="docText">The point is that the strings are never
<span class="docEmphasis">stored.</span> Only those strings that the user
actually requests to see are generated.</p>
<p class="docText">There is one other setting that we must make. We must tell
the list component that all items have a fixed width and height:</p>
<pre>wordList.setFixedCellWidth(50);
wordList.setFixedCellHeight(15);
</pre>
<p class="docText">Otherwise, the list component would compute each item to
measure its width and height. That would take a long time.</p>
<p class="docText">As a practical matter, such very long lists are rarely
useful. It is extremely cumbersome for a user to scroll through a huge
selection. For that reason, we believe that the list control has been completely
over-engineered. A selection that a user can comfortably manage on the screen is
certainly small enough to be stored directly in the list component. That
arrangement would have saved programmers from the pain of having to deal with
the list model as a separate entity. On the other hand, the <tt>JList</tt> class
is consistent with the <tt>JTree</tt> and <tt>JTable</tt> class where this
generality is useful.</p>
<h5 id="ch06list02" class="docExampleTitle">Example 6-2 LongListTest.java</h5>
<pre> 1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. import javax.swing.event.*;
5.
6.
7. /**
8. This program demonstrates a list that dynamically computes
9. list entries.
10. */
11. public class LongListTest
12. {
13. public static void main(String[] args)
14. {
15. JFrame frame = new LongListFrame();
16. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. frame.show();
18. }
19.}
20.
21. /**
22. This frame contains a long word list and a label that shows a
23. sentence made up from the chosen word.
24. */
25. class LongListFrame extends JFrame
26. {
27. public LongListFrame()
28. {
29. setTitle("LongListTest");
30. setSize(WIDTH, HEIGHT);
31.
32. wordList = new JList(new WordListModel(3));
33. wordList.setSelectionMode
34. (ListSelectionModel.SINGLE_SELECTION);
35.
36. wordList.setFixedCellWidth(50);
37. wordList.setFixedCellHeight(15);
38.
39. JScrollPane scrollPane = new JScrollPane(wordList);
40.
41. JPanel p = new JPanel();
42. p.add(scrollPane);
43. wordList.addListSelectionListener(new
44. ListSelectionListener()
45. {
46. public void valueChanged(ListSelectionEvent evt)
47. {
48. StringBuffer word
49. = (StringBuffer)wordList.getSelectedValue();
50. setSubject(word.toString());
51. }
52.
53. });
54.
55. Container contentPane = getContentPane();
56. contentPane.add(p, BorderLayout.SOUTH);
57. label = new JLabel(prefix + suffix);
58. contentPane.add(label, BorderLayout.CENTER);
59. setSubject("fox");
60. }
61.
62. /**
63. Sets the subject in the label.
64. @param word the new subject that jumps over the lazy dog
65. */
66. public void setSubject(String word)
67. {
68. StringBuffer text = new StringBuffer(prefix);
69. text.append(word);
70. text.append(suffix);
71. label.setText(text.toString());
72. }
73.
74. private static final int WIDTH = 400;
75. private static final int HEIGHT = 300;
76. private JList wordList;
77. private JLabel label;
78. private String prefix = "The quick brown ";
79. private String suffix = " jumps over the lazy dog.";
80.}
81.
82. /**
83. A model that dynamically generates n-letter words.
84. */
85. class WordListModel extends AbstractListModel
86. {
87. /**
88. Constructs the model.
89. @param n the word length
90. */
91. public WordListModel(int n) { length = n; }
92.
93. public int getSize()
94. {
95. return (int)Math.pow(LAST - FIRST + 1, length);
96. }
97.
98. public Object getElementAt(int n)
99. {
100. StringBuffer r = new StringBuffer();;
101. for (int i = 0; i < length; i++)
102. {
103. char c = (char)(FIRST + n % (LAST - FIRST + 1));
104. r.insert(0, c);
105. n = n / (LAST - FIRST + 1);
106. }
107. return r;
108. }
109.
110. private int length;
111. public static final char FIRST = 'a';
112. public static final char LAST = 'z';
113.}
</pre>
<h5 class="docSection3Title" id="ch06lev3sec3"><tt>javax.swing.JList</tt></h5>
<p><img alt="graphics/api.gif" src="api.gif" border="0" width="46" height="45"><br>
</p>
<ul>
<li>
<p class="docList"><tt>JList(ListModel dataModel)</tt></p>
<p class="docList">constructs a list that displays the elements in the
specified model.</li>
<li>
<p class="docList"><tt>void setFixedCellWidth(int width)</tt></p>
<p class="docList">if the width is greater than zero, specifies the width of
every cell in the list. The default value is <tt>-</tt>1, which forces the
size of each cell to be measured.</li>
<li>
<p class="docList"><tt>void setFixedCellHeight(int height)</tt></p>
<p class="docList">if the height is greater than zero, specifies the height of
every cell in the list. The default value is <tt>-</tt>1, which forces the
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?