_chapter 6.htm
来自「Core Java 2(中文名称:JAVA 2 核心技术 卷二:高级特性)这是英」· HTM 代码 · 共 1,429 行 · 第 1/5 页
HTM
1,429 行
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Chapter 6</title>
<link rel="stylesheet" type="text/css" href="docsafari.css">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<ul></ul>
<table width="100%" border="1" bgcolor="#EBEBFF">
<tr>
<td width="5%" align="left" valign="middle"><a href="_chapter%205.htm"><img src="Larrow.gif" width="17" height="19" border="0"></a></td>
<td align="center" valign="middle"><a class="docLink" href="Front%20matter.htm">CONTENTS</a></td>
<td width="5%" align="right" valign="middle"><a href="_chapter%207.htm"><img src="Rarrow.gif" width="17" height="19" border="0"></a></td>
</tr>
</table>
<h2 class="docChapterTitle">Chapter 6. Advanced Swing</h2>
<ul>
<li>
<p class="docList"><a class="docLink" href="#c6s1">Lists</a></li>
<li>
<p class="docList"><a class="docLink" href="#c6s2">Trees</a></li>
<li>
<p class="docList"><a class="docLink" href="#c6s3">Tables</a></li>
<li>
<p class="docList"><a class="docLink" href="#c6s4">Styled Text Components</a></li>
<li>
<p class="docList"><a class="docLink" href="#c6s5">Component Organizers</a></li>
</ul>
<p class="docText">In this chapter, we continue our discussion of the Swing user
interface toolkit from Volume 1. Swing is a very rich toolkit, and Volume 1 only
covered basic and commonly used components. That leaves us with three
significantly more complex components for lists, trees, and tables, whose
exploration will occupy the bulk of this chapter. Components for styled text, in
particular HTML, are internally even more complex, and we show you how to put
them to practical use. We finish the chapter by covering component organizers
such as tabbed panes and desktop panes with internal frames.</p>
<h3 class="docSection1Title" id="c6s1">Lists</h3>
<p class="docText">If you want to present a set of choices to a user, and a
radio button or checkbox set consumes too much space, you can use a combo box or
a list. Combo boxes were covered in Volume 1 because they are relatively simple.
The <tt>JList</tt> component has many more features, and its design is similar
to that of the tree and table components. For that reason, it is our starting
point for the discussion of complex Swing components.</p>
<p class="docText">Of course, you can have lists of strings, but you can also
have lists of arbitrary objects, with full control of how they appear. The
internal architecture of the list component that makes this generality possible
is rather elegant. Unfortunately, the designers at Sun felt that they needed to
show off that elegance, rather than hiding it from the programmer who just wants
to use the component. You will find that the list control is somewhat awkward to
use for common cases because you need to manipulate some of the machinery that
makes the general cases possible. We'll walk you through the simple and most
common case, a list box of strings, and then give a more complex example that
shows off the flexibility of the list component.</p>
<h4 class="docSection2Title" id="ch06lev2sec1">The <tt>JList</tt> Component</h4>
<p class="docText">The <tt>JList</tt> component is similar to a set of check
boxes or radio buttons, except that the items are placed inside a single box and
are selected by clicking on the items themselves, not on buttons. If you permit
multiple selection for a list box, the user can select any combination of the
items in the box.</p>
<p class="docText"><a class="docLink" href="#ch06fig01">Figure 6-1</a> shows an
admittedly silly example. The user can select the attributes for the fox, such
as "quick," "brown," "hungry," "wild," and, because we ran out of attributes,
"static," "private," and "final." You can, thus, have the
<span class="docEmphasis">static, final</span> fox jump over the lazy dog.</p>
<center>
<h5 id="ch06fig01" class="docFigureTitle">Figure 6-1. A list box</h5>
<p>
<img alt="graphics/06fig01.gif" src="06fig01.gif" border="0" width="401" height="298"></p>
</center>
<p class="docText">To construct this list component, you first start out with an
array of strings, then pass the array to the <tt>JList</tt> constructor:</p>
<pre>String[] words= { "quick", "brown", "hungry", "wild", ... };
JList wordList = new JList(words);
</pre>
<p class="docText">Alternatively, you can use an anonymous array:</p>
<pre>JList wordList = new JList(new String[]
{"quick", "brown", "hungry", "wild", ... });
</pre>
<p class="docText">List boxes do not scroll automatically. To make a list box
scroll, you must insert it into a scroll pane:</p>
<pre>JScrollPane scrollPane = new JScrollPane(wordList);
</pre>
<p class="docText">Then, you need to add the scroll pane, not the list, into the
surrounding panel.</p>
<p class="docText">We must admit that the separation of the list display and the
scrolling mechanism is elegant in theory, but it is a pain in practice.
Essentially all lists that we ever encountered needed scrolling. It seems cruel
to force programmers to go through hoops in the default case, just so they can
appreciate that elegance.</p>
<p class="docText">By default, the list component displays eight items; use the
<tt>setVisibleRowCount</tt> method to change that value:</p>
<pre>wordList.setVisibleRowCount(10); // display 10 items
</pre>
<p class="docText">By default, a user can select multiple items. This requires
some knowledge of mouse technique: To add more items to a selection, press the
CTRL key while clicking on each item. To select a contiguous range of items,
click on the first one, then hold down the SHIFT key and click on the last one.</p>
<p class="docText">You can also restrict the user to a more limited selection
mode with the <tt>setSelectionMode</tt> method:</p>
<pre>wordList.setSelectionMode
(ListSelectionModel.SINGLE_SELECTION);
// select one item at a time
wordList.setSelectionMode
(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
// select one item or one range of items
</pre>
<p class="docText">You may recall from Volume 1 that the basic user interface
components send out action events when the user activates them. List boxes use a
different notification mechanism. Rather than listening to action events, you
need to listen to list selection events. Add a list selection listener to the
list component, and implement the method</p>
<pre>public void valueChanged(ListSelectionEvent evt)
</pre>
<p class="docText">in the listener.</p>
<p class="docText">When the user selects items, a flurry of list selection
events is generated. For example, suppose the user clicks on a new item. When
the mouse button goes down, there is an event that reports a change in
selection. This is a transitional event梩he call</p>
<pre>event.isAdjusting()
</pre>
<p class="docText">returns <tt>true</tt> if the selection is not yet final.
Then, when the mouse button goes up, there is another event, this time with <tt>
isAdjusting</tt> returning <tt>false</tt>. If you are not interested in the
transitional events, then you can wait for the event for which <tt>isAdjusting</tt>
is <tt>false</tt>. However, if you want to give the user instant feedback as
soon as the mouse button is clicked, then you need to process all events.</p>
<p class="docText">Once you are notified that an event has happened, you will
want to find out what items are currently selected. The <tt>getSelectedValues</tt>
method returns an <span class="docEmphasis">array</span>
<span class="docEmphasis">of objects</span> containing all selected items.</p>
<p class="docText">You need to cast <span class="docEmphasis">each</span> array
element to a string.</p>
<pre>Object[] values = list.getSelectedValues();
for (int i = 0; i < values.length; i++)
<span class="docEmphasis">do something with</span> (String)values[i];
</pre>
<div class="docNote">
<p class="docNoteTitle">CAUTION</p>
<table cellSpacing="0" cellPadding="1" width="90%" border="0">
<tr>
<td vAlign="top" width="60">
<img alt="graphics/caution.gif" src="caution.gif" align="left" border="0" width="54" height="51"><br>
</td>
<td vAlign="top">
<p class="docText">You cannot cast the return value of <tt>
getSelectedValues</tt> from an <tt>Object[]</tt> array to a <tt>String[]</tt>
array. The return value was not created as an array of strings, but as an
array of objects, each of which happens to be a string. If you want to
process the return value as an array of strings, you can use the following
code:</p>
<pre>int length = values.length;
String[] words = new String[length];
System.arrayCopy(values, 0, words, 0, length);
</pre>
</td>
</tr>
</table>
</div>
<p class="docText">If your list does not allow multiple selections, you can call
the convenience method <tt>getSelectedValue</tt>. It returns the first selected
value (which you know to be the only value if multiple selections are
disallowed).</p>
<pre>String selection = (String)source.getSelectedValue();
</pre>
<div class="docNote">
<p class="docNoteTitle">NOTE</p>
<table cellSpacing="0" cellPadding="1" width="90%" border="0">
<tr>
<td vAlign="top" width="60">
<img alt="graphics/note.gif" src="note.gif" align="left" border="0" width="54" height="53"><br>
</td>
<td vAlign="top">
<p class="docText">List components do not react to double clicks from a
mouse. As envisioned by the designers of Swing, you use a list to select
an item, and then you need to click a button to make something happen.
However, some user interfaces allow a user to double-click on a list to
indicate selection of a list item and acceptance of an action. We don't
think this is a good user interface style because it is difficult for
users to discover that they are supposed to double-click. But if you do
want to implement this behavior, you have to add a mouse listener to the
list box, then trap the mouse event as follows:</p>
<pre>public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() == 2)
{
JList source = (JList)evt.getSource();
Object[] selection = source.getSelectedValues();
doAction(selection);
}
}
</pre>
</td>
</tr>
</table>
</div>
<p class="docText"><a class="docLink" href="#ch06list01">Example 6-1</a> is the
listing of the program that demonstrates a list box filled with strings. Notice
how the <tt>valueChanged</tt> method builds up the message string from the
selected items.</p>
<h5 id="ch06list01" class="docExampleTitle">Example 6-1 ListTest.java</h5>
<pre> 1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. import javax.swing.event.*;
5.
6. /**
7. This program demonstrates a simple fixed list of strings.
8. */
9. public class ListTest
10. {
11. public static void main(String[] args)
12. {
13. JFrame frame = new ListFrame();
14. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15. frame.show();
16. }
17. }
18.
19. /**
20. This frame contains a word list and a label that shows a
21. sentence made up from the chosen words. Note that you can
22. select multiple words with Ctrl+click and Shift+click.
23. */
24. class ListFrame extends JFrame
25. {
26. public ListFrame()
27. {
28. setTitle("ListTest");
29. setSize(WIDTH, HEIGHT);
30.
31. String[] words =
32. {
33. "quick","brown","hungry","wild","silent",
34. "huge","private","abstract","static","final"
35. };
36.
37. wordList = new JList(words);
38. JScrollPane scrollPane = new JScrollPane(wordList);
39.
40. JPanel p = new JPanel();
41. p.add(scrollPane);
42. wordList.addListSelectionListener(new
43. ListSelectionListener()
44. {
45. public void valueChanged(ListSelectionEvent event)
46. {
47. Object[] values = wordList.getSelectedValues();
48.
49. StringBuffer text = new StringBuffer(prefix);
50. for (int i = 0; i < values.length; i++)
51. {
52. String word = (String)values[i];
53. text.append(word);
54. text.append(" ");
55. }
56. text.append(suffix);
57.
58. label.setText(text.toString());
59. }
60. });
61.
62. Container contentPane = getContentPane();
63. contentPane.add(p, BorderLayout.SOUTH);
64. label = new JLabel(prefix + suffix);
65. contentPane.add(label, BorderLayout.CENTER);
66. }
67.
68. private static final int WIDTH = 400;
69. private static final int HEIGHT = 300;
70. private JList wordList;
71. private JLabel label;
72. private String prefix = "The ";
73. private String suffix = "fox jumps over the lazy dog.";
74. }
</pre>
<h5 class="docSection3Title" id="ch06lev3sec1"><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(Object[] items)</tt></p>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?