_chapter 6.htm
来自「Core Java 2(中文名称:JAVA 2 核心技术 卷二:高级特性)这是英」· HTM 代码 · 共 1,429 行 · 第 1/5 页
HTM
1,429 行
39. fontList = new JList(fonts.toArray());
40. fontList.setVisibleRowCount(4);
41. fontList.setSelectionMode
42. (ListSelectionModel.SINGLE_SELECTION);
43. fontList.setCellRenderer(new FontCellRenderer());
44. JScrollPane scrollPane = new JScrollPane(fontList);
45.
46. JPanel p = new JPanel();
47. p.add(scrollPane);
48. fontList.addListSelectionListener(new
49. ListSelectionListener()
50. {
51. public void valueChanged(ListSelectionEvent evt)
52. {
53. Font font = (Font)fontList.getSelectedValue();
54. text.setFont(font);
55. }
56
57. });
58.
59. Container contentPane = getContentPane();
60. contentPane.add(p, BorderLayout.SOUTH);
61. text = new JTextArea(
62. "The quick brown fox jumps over the lazy dog");
63. text.setFont((Font)fonts.get(0));
64. text.setLineWrap(true);
65. text.setWrapStyleWord(true);
66. contentPane.add(text, BorderLayout.CENTER);
67. }
68
69. private JTextArea text;
70. private JList fontList;
71. private static final int WIDTH = 400;
72. private static final int HEIGHT = 300;
73. }
74.
75. /**
76. A cell renderer for Font objects that renders the font name
77. in its own font.
78. */
79. class FontCellRenderer implements ListCellRenderer
80. {
81. public Component getListCellRendererComponent
82. (final JList list, final Object value,
83. final int index, final boolean isSelected,
84. final boolean cellHasFocus)
85. {
86. return new
87. JPanel()
88. {
89. public void paintComponent(Graphics g)
90. {
91. Font font = (Font)value;
92. String text = font.getFamily();
93. FontMetrics fm = g.getFontMetrics(font);
94. g.setColor(isSelected
95. ? list.getSelectionBackground()
96. : list.getBackground());
97. g.fillRect(0, 0, getWidth(), getHeight());
98. g.setColor(isSelected
99. ? list.getSelectionForeground()
100 : list.getForeground());
101. g.setFont(font);
102. g.drawString(text, 0, fm.getAscent());
103. }
104.
105. public Dimension getPreferredSize()
106. {
107. Font font = (Font)value;
108. String text = font.getFamily();
109. Graphics g = getGraphics();
110. FontMetrics fm = g.getFontMetrics(font);
111. return new Dimension(fm.stringWidth(text),
112. fm.getHeight());
113. }
114. };
115. }
116.}
</pre>
<h5 class="docSection3Title" id="ch06lev3sec7"><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>Color getBackground()</tt></p>
<p class="docList">returns the background color for unselected cells.</li>
<li>
<p class="docList"><tt>Color getSelectionBackground()</tt></p>
<p class="docList">returns the background color for selected cells.</li>
<li>
<p class="docList"><tt>void setCellRenderer(ListCellRenderer cellRenderer)</tt></p>
<p class="docList">sets the renderer that is used to paint the cells in the
list.</li>
</ul>
<h5 class="docSection3Title" id="ch06lev3sec8"><tt>javax.swing.ListCellRenderer</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>Component getListCellRendererComponent(JList list,
Object item, int index, boolean isSelected, boolean hasFocus)</tt></p>
<p class="docList">returns a component whose <tt>paint</tt> method will draw
the cell contents. If the list cells do not have fixed size, that component
must also implement <tt>getPreferredSize</tt>.</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>list</tt></td>
<td class="docTableCell" vAlign="top">the list whose cell is being drawn</td>
</tr>
<tr>
<td class="docTableCell" vAlign="top"> </td>
<td class="docTableCell" vAlign="top"><tt>item</tt></td>
<td class="docTableCell" vAlign="top">the item to be drawn </td>
</tr>
<tr>
<td class="docTableCell" vAlign="top"> </td>
<td class="docTableCell" vAlign="top"><tt>index</tt></td>
<td class="docTableCell" vAlign="top">the index where the item is stored
in the model</td>
</tr>
<tr>
<td class="docTableCell" vAlign="top"> </td>
<td class="docTableCell" vAlign="top"><tt>isSelected</tt></td>
<td class="docTableCell" vAlign="top"><tt>true</tt> if the specified cell
was selected</td>
</tr>
<tr>
<td class="docTableCell" vAlign="top"> </td>
<td class="docTableCell" vAlign="top"><tt>hasFocus</tt></td>
<td class="docTableCell" vAlign="top"><tt>true</tt> if the specified cell
has the focus</td>
</tr>
</table>
<p> </li>
</ul>
<h3 class="docSection1Title" id="c6s2">Trees</h3>
<p class="docText">Every computer user who uses a hierarchical file system has
encountered <span class="docEmphasis">tree</span> displays such as the one in
<a class="docLink" href="#ch06fig04">Figure 6-4</a>. Of course, directories and
files form only one of the many examples of treelike organizations. Programmers
are familiar with inheritance trees for classes. There are many tree structures
that arise in everyday life, such as the hierarchy of countries, states, and
cities shown in <a class="docLink" href="#ch06fig05">Figure 6-5</a>.</p>
<center>
<h5 id="ch06fig04" class="docFigureTitle">Figure 6-4. A directory tree</h5>
<p>
<img alt="graphics/06fig04.gif" src="06fig04.gif" border="0" width="198" height="528"><br>
</p>
</center><center>
<h5 id="ch06fig05" class="docFigureTitle">Figure 6-5. A hierarchy of countries, states, and
cities</h5>
<p>
<img alt="graphics/06fig05.gif" src="06fig05.gif" border="0" width="500" height="172"></p>
</center>
<p class="docText">As programmers, we often have to display these tree
structures. Fortunately, the Swing library has a <tt>JTree</tt> class for this
purpose. The <tt>JTree</tt> class (together with its helper classes) takes care
of laying out the tree and of processing user requests for expanding and
collapsing nodes. In this section, you will learn how to put the <tt>JTree</tt>
class to use. As with the other complex Swing components, we must focus on the
common and useful cases and cannot cover every nuance梬e recommend that you
consult <i>Core Java Foundation Classes</i> by Kim Topley [Prentice-Hall 1998]
or <i>Graphic Java 2</i> by David M. Geary [Prentice-Hall 1999] if you want to
achieve an unusual effect.</p>
<p class="docText">Before going any further, let's settle on some terminology
(see <a class="docLink" href="#ch06fig06">Figure 6-6</a>). A tree is composed of
<span class="docEmphasis">nodes.</span> Every node is either a
<span class="docEmphasis">leaf,</span> or it has <span class="docEmphasis">child
nodes.</span> Every node, with the exception of the root node, has exactly one
<span class="docEmphasis">parent.</span> A tree has exactly one root node.
Sometimes you have a collection of trees, each of which has its own root node.
Such a collection is called a <span class="docEmphasis">forest.</span></p>
<center>
<h5 id="ch06fig06" class="docFigureTitle">Figure 6-6. Tree terminology</h5>
<p>
<img alt="graphics/06fig06.gif" src="06fig06.gif" border="0" width="427" height="332"></p>
</center>
<h4 class="docSection2Title" id="ch06lev2sec5">Simple Trees</h4>
<p class="docText">In our first example program, we simply display a tree with a
few nodes (see <a class="docLink" href="#ch06fig08">Figure 6-8</a>). As with
most other Swing components, the <tt>JTree</tt> component follows the
model/view/controller pattern. You provide a model of the hierarchical data, and
the component displays it for you. To construct a <tt>JTree</tt>, you supply the
tree model in the constructor:</p>
<center>
<h5 id="ch06fig08" class="docFigureTitle">Figure 6-8. A simple tree</h5>
<p>
<img alt="graphics/06fig08.gif" src="06fig08.gif" border="0" width="301" height="230"></p>
</center>
<pre>TreeModel model = . . .;
JTree tree = new JTree(model);
</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">There are also constructors that construct trees out of
a collection of elements:</p>
<pre>JTree(Object[] nodes)
JTree(Vector nodes)
JTree(Hashtable nodes) // the values become the nodes
</pre>
<p class="docText">These constructors are not very useful. They merely
build a forest of trees, each with a single node. The third constructor
seems particularly useless since the nodes appear in the essentially
random order given by the hash codes of the keys.</td>
</tr>
</table>
</div>
<p class="docText">How do you obtain a tree model? You can construct your own
model by creating a class that implements the <tt>TreeModel</tt> interface. You
will see later in this chapter how to do that. For now, we'll stick with the <tt>
DefaultTreeModel</tt> that the Swing library supplies.</p>
<p class="docText">To construct a default tree model, you must supply a root
node.</p>
<pre>TreeNode root = . . .;
DefaultTreeModel model = new DefaultTreeModel(root);
</pre>
<p class="docText"><tt>TreeNode</tt> is another interface. You populate the
default tree model with objects of any class that implements the interface. For
now, we will use the concrete node class that Swing supplies, namely <tt>
DefaultMutableTreeNode</tt>. This class implements the <tt>MutableTreeNode</tt>
interface, a subinterface of <tt>TreeNode</tt> (see
<a class="docLink" href="#ch06fig07">Figure 6-7</a>).</p>
<center>
<h5 id="ch06fig07" class="docFigureTitle">Figure 6-7. Tree classes</h5>
<p>
<img alt="graphics/06fig07.gif" src="06fig07.gif" border="0" width="347" height="357"></p>
</center>
<p class="docText">A default mutable tree node holds an object, the
<span class="docEmphasis">user object.</span> The tree renders the user objects
for all nodes. Unless you specify a renderer, the tree simply displays the
string that is the result of the <tt>toString</tt> method.</p>
<p class="docText">In our first example, we use strings as user objects. In
practice, you would usually populate a tree with more expressive user objects.
For example, when displaying a directory tree, it makes sense to use <tt>File</tt>
objects for the nodes.</p>
<p class="docText">You can specify the user object in the constructor, or you
can set it later with the <tt>setUserObject</tt> method.</p>
<pre>DefaultMutableTreeNode node
= new DefaultMutableTreeNode("Texas");
node.setUserObject("California");
</pre>
<p class="docText">Next, you establish the parent/child relationships between
the nodes. Start with the root node, and use the <tt>add</tt> method to add the
children:</p>
<pre>DefaultMutableTreeNode root
= new DefaultMutableTreeNode("World");
DefaultMutableTreeNode country
= new DefaultMutableTreeNode("USA");
root.add(country);
DefaultMutableTreeNode state
= new DefaultMutableTreeNode("California");
country.add(state);
</pre>
<p class="docText"><a class="docLink" href="#ch06fig08">Figure 6-8</a>
illustrates how the tree will look.</p>
<p class="docText">Link up all nodes in this fashion. Then, construct a <tt>
DefaultTreeModel</tt> with the root node. Finally, construct a <tt>JTree</tt>
with the tree model.</p>
<pre>DefaultTreeModel treeModel = new DefaultTreeModel(root);
JTree tree = new JTree(treeModel);
</pre>
<p class="docText">Or, as a shortcut, you can simply pass the root node to the
<tt>JTree</tt> constructor. Then the tree automatically constructs a default
tree model:</p>
<pre>JTree tree = new JTree(root);
</pre>
<p class="docText"><a class="docLink" href="#ch06list04">Example 6-4</a>
contains the complete code.</p>
<h5 id="ch06list04" class="docExampleTitle">Example 6-4 SimpleTree.java</h5>
<pre> 1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4. import javax.swing.tree.*;
5.
6. /**
7. This program shows a simple tree.
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?