📄 scrollpane.html
字号:
The program doesn't invoke any methods on the <code>JScrollPane</code> object,since the scroll pane handles everything automatically:creating the scroll bars when necessary,redrawing the client when the user moves the scroll knobs,and so on.<p>You might have noticed that the preceding codesets the preferred size of the scroll pane's container.In the Java look and feel, this preferred size happens to be a bit less tall than required for the text area to display the 5 rows that we requestedwhen creating it,so the scroll bar initially displays a vertical scroll bar.If we didn't restrict the size of the scroll pane's container,the scroll pane would be big enoughfor the text area to display the full 5 rows and 30 columnsspecified with the <code>JTextArea</code> constructor.Refer to<a href="#sizing">Sizing a Scroll Pane</a>for information about techniquesfor making a scroll pane the size you want.<p>The rest of this section discusses the following topics:<ul><li> <a href="#operation">How a Scroll Pane Works</a><li> <a href="#scrollbars">Setting the Scroll Bar Policy</a><li> <a href="#decorations">Providing Custom Decorations</a><li> <a href="#scrollable">Implementing a Scrolling-Savvy Client</a><li> <a href="#sizing">Sizing a Scroll Pane</a><li> <a href="#update">Dynamically Changing the Client's Size</a><li> <a href="#api">The Scroll Pane API</a><li> <a href="#eg">Examples that Use Scroll Panes</a></ul><a name="operation"></blockquote><h3>How a Scroll Pane Works</h3></a><blockquote>Here is a snapshot of an applicationthat uses a customized scroll paneto view a large photograph:<p><center><IMG SRC="../../figures/uiswing/components/ScrollDemo.png" WIDTH="348" HEIGHT="324" ALIGN="BOTTOM" ALT="A snapshot of ScrollDemo"></center></p>The scroll pane in this application looks very differentfrom the one in the previous demo program.Rather than displaying text, this scroll pane contains a large image.The scroll pane also has two scroll bars, a row header, a column header,and four corners, three of which have been customized.<blockquote><hr><strong>Try this:</strong> <ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/ScrollDemo.jnlp">Run ScrollDemo</a> (it requires 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 example yourself, consult the <a href="examples/index.html#ScrollDemo">example index</a>.<li> Move the knobs on the scroll bars. Watch the image scroll and the horizontal and vertical rulers scroll along.<li> If you have a mouse with a wheel (which is generally between the mouse buttons) use the mouse wheel to scroll the image vertically.<li> Click the <strong>cm</strong> toggle in the upper left corner of the scroll pane. The units on the row and column headers change to inches (or back to centimeters).<li> Click the arrow buttons on the scroll bars. Also, try clicking on the track above or below the knob on the vertical scroll bar, or to the left or right of the horizontal one.<li> Move the cursor over the image and press the cursor. Continuing to press the cursor, drag to a point outside the image and pause. The visible area of the image moves toward the cursor. This scroll-by-dragging functionality is enabled by the scroll pane and by <code>JComponent</code> API, but implemented by the custom component that displays the image.<li> Resize the window. Notice that the scroll bars disappear when the scroll pane is large enough to display the entire image and reappear again when the scroll pane is too small to show the entire image.</ol><hr></blockquote>The ScrollDemo program establishes the scroll pane's clientwhen creating the scroll pane:<blockquote><pre>//<em>Where the member variables are declared:</em>private ScrollablePicture picture;...//<em>Where the GUI is created:</em>picture = new ScrollablePicture(<em> ... </em>);JScrollPane pictureScrollPane = new JScrollPane(picture);</pre></blockquote>The scroll pane's client is also known as the<em>view</em> or <em>viewport view</em>.You can change the client dynamically by calling the<code>setViewportView</code> method.Note that <code>JScrollPane</code>has no corresponding<code>getViewportView</code> method.If you need to refer to the client object again,you can eithercache it in a variableor invoke <code>getViewport().getViewportView()</code>on the scroll pane.<p>When the user manipulates the scroll bars in a scroll pane,the area of the client that is visible changes accordingly.This picture shows the relationship between the scroll paneand its client and indicates theclasses that the scroll pane commissions to help:<p><center><IMG SRC="../../figures/uiswing/components/scrollarchitecture.gif" WIDTH="531" HEIGHT="334" ALIGN="BOTTOM" ALT="The architecture of a scroll pane"></center></p><p>A scroll pane uses a<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JViewport.html"><code>JViewport</code></a> instance to manage the visible area of the client.The viewport is responsible forcomputing the bounds of the current visible area,based on the positionsof the scroll bars,and displaying it.<p>A scroll pane uses two separate instances of<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JScrollBar.html"><code>JScrollBar</code></a> for the scroll bars. The scroll bars provide theinterface for the user to manipulate the visible area.The following figure shows the three areas of a scroll bar:the knob (sometimes called the <em>thumb</em>), the buttons, and the track.<p><center><IMG SRC="../../figures/uiswing/components/scrollbarparts.png" WIDTH="253" HEIGHT="144" ALIGN="BOTTOM" ALT="The parts of a scroll bar"></center></p><p>When the user moves the knob on the vertical scroll bar up and down,the visible area of the client moves up and down. Similarly, when the usermoves the knob on the horizontal scroll bar to the right andleft, the visible area of the client moves back and forth accordingly.The position of the knob relative to its trackis proportionally equal tothe position of the visible area relative to the client.In the Java look and feel and some others,the size of the knob gives a visual clueas to how much of the client is visible.<p>By clicking a button,the user can scroll by a <em>unit increment</em>.By clicking within the track,the user can scroll by a <em>block increment</em>.If the user has a mouse with a wheel,then the user can scroll vertically using the mouse wheel.The amount that the mouse wheel scrollsis platform dependent.For example, by default on Windows XP,the mouse wheel scrolls three unit increments;the Mouse control panel allows you to specify a different number of unit incrementsor to use a block increment instead.More information about unit and block increments is in<a href="#scrollable">Implementing a Scrolling-Savvy Client</a>.<p>Typical programs don't directly instantiate orcall methods on a viewport or scroll bar.Instead, programs achieve their scrollingbehavior using the <code>JScrollPane</code> APIand the API discussed in<a href="#scrollable">Implementing a Scrolling-Savvy Client</a>.Some scrolling-savvy components such as<code>JList</code>, <code>JTable</code>,and <code>JTree</code> also provide <a href="#otherAPI">additional API</a>to help you affect their scrolling behavior.</blockquote><a name="scrollbars"><h3>Setting the Scroll Bar Policy</h3></a><blockquote>On startup, the scroll pane in the <code>ScrollDemo</code>application has two scroll bars.If you make the window very large,both scroll bars disappear because they are no longer needed.If you then shrink the height of the window withoutchanging its width,the vertical scroll bar reappears.Further experimentation will show thatin this applicationboth scroll bars disappear and reappear as needed.This behavior is controlled by the scroll pane's<em>scroll bar policy</em>,Actually, it's two policies:each scroll bar has its own.<p><code>ScrollDemo</code> doesn't explicitly setthe scroll pane's scroll bar policies —it uses the default.You can set the policies when you create the scroll paneor change them dynamically.<p>Of the constructors provided by <code>JScrollPane</code>,these two let you set the scroll bar policieswhen you create the scroll pane:<blockquote><pre>JScrollPane(Component, int, int)JScrollPane(int, int)</pre></blockquote>The first <code>int</code> specifies the policy for the verticalscroll bar; the second specifies the policy for the horizontal scroll bar.You can also set the policies dynamically with the<code>setHorizontalScrollBarPolicy</code>and<code>setVerticalScrollBarPolicy</code> methods.With both the constructors and the methods, useone of the following constants definedin the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/ScrollPaneConstants.html"><code>ScrollPaneConstants</code></a> interface (which is implemented by <code>JScrollPane</code>):<p><table><tr><th align=left>Policy<th align=left>Description</th></tr><tr><td valign=top><font size=-1><code>VERTICAL_SCROLLBAR_AS_NEEDED</code></font> <br> <font size=-1><code>HORIZONTAL_SCROLLBAR_AS_NEEDED</code></font></td><td valign=top>The default. The scroll bar appears when the viewport is smaller than the client and disappears when the viewport is larger than the client.</td></tr><tr><td valign=top><font size=-1><code>VERTICAL_SCROLLBAR_ALWAYS</code></font> <br> <font size=-1><code>HORIZONTAL_SCROLLBAR_ALWAYS</code></font></td><td valign=top>Always display the scroll bar. The knob disappears if the viewport is large enough to show the whole client.</td></tr><tr><td valign=top><font size=-1><code>VERTICAL_SCROLLBAR_NEVER</code></font> <br> <font size=-1><code>HORIZONTAL_SCROLLBAR_NEVER</code></font></td><td valign=top>Never display the scroll bar. Use this option if you don't want the user to directly control what part of the client is shown, or if you want them to use only non-scroll-bar techniques (such as dragging). </td></tr></table></blockquote><a name="decorations"><h3>Providing Custom Decorations</h3></a><blockquote>The area drawn by a scroll pane consists of up to nine parts:the center, four sides, and four corners.The center is the only component that is alwayspresent in all scroll panes.Besides scroll bars,the sides can containcolumn and row headers.A corner component is visibleonly if both sides that intersect at that cornercontain visible components.<p><center><IMG SRC="../../figures/uiswing/components/scrollpanedecorations.png" WIDTH="494" HEIGHT="310" ALIGN="BOTTOM" ALT="Decorations on a scroll pane"></center></p><p>As shown in the figure, the scroll pane in <code>ScrollDemo</code>has custom row and column headers.Additionally, because all four sides are populated,all four corners are present.The program customizes three of the corners —two just fill their area with the same color as the <code>Rule</code>s,and the other contains a toggle button.The fourth corner, the lower right corner,is the default provided by the scroll pane.Notice that because the row and column headers are always presentin this example,the toggle button is also always present.<p>If a corner contains a controlthat the user needs access to all the time,make sure the sides that intersect at the corner are always present.For example,if this application placed the togglein the lower right corner where the scroll bars intersect,then the toggle would disappear if the userresized the window and even one of the scroll bars disappeared.<p>The scroll pane's row and column headers are providedby a custom <code>JComponent</code> subclass,<a class="SourceLink" target="_blank" href="examples/Rule.java"><code>Rule</code></a>,that draws a ruler in centimeters or inches.Here's the code that creates and sets the scroll pane's rowand column headers:<blockquote><pre><em>//Where the member variables are defined:</em>private Rule columnView;private Rule rowView;...<em>//Where the GUI is initialized:</em>ImageIcon david = createImageIcon("images/youngdad.jpeg");...//Create the row and column headers.columnView = new Rule(Rule.HORIZONTAL, true);rowView = new Rule(Rule.VERTICAL, true);if (david != null) { columnView.setPreferredWidth(david.getIconWidth()); rowView.setPreferredHeight(david.getIconHeight());}...<strong>pictureScrollPane.setColumnHeaderView(columnView);</strong><strong>pictureScrollPane.setRowHeaderView(rowView);</strong></pre></blockquote>You can use any componentfor a scroll pane's row and column headers.The scroll pane puts the row and column headersin <code>JViewPort</code>s of their own.Thus, when scrolling horizontally, the column header follows along,and when scrolling vertically, the row header follows along.<p>As a <code>JComponent</code> subclass,our custom <code>Rule</code> class puts its rendering codein its <code>paintComponent</code> method.The <code>Rule</code> rendering code takes careto draw only within the current clipping bounds,to ensure speedy scrolling.Your custom row and column headers should do the same.<p>You can also use any component for the corners of a scroll pane.<code>ScrollDemo</code> illustrates this by putting a togglebutton in the upper left corner,and custom<a class="SourceLink" target="_blank" href="examples/Corner.java"><code>Corner</code></a>objects in the upper right and lower left corners.Here's the code that createsthe <code>Corner</code> objects and calls <code>setCorner</code> to place them:<blockquote><pre>//Create the corners.JPanel buttonCorner = new JPanel(); //use FlowLayoutisMetric = new JToggleButton("cm", true);isMetric.setFont(new Font("SansSerif", Font.PLAIN, 11));isMetric.setMargin(new Insets(2,2,2,2));isMetric.addItemListener(this);buttonCorner.add(isMetric);...//Set the corners.<strong>pictureScrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, buttonCorner);pictureScrollPane.setCorner(JScrollPane.LOWER_LEFT_CORNER, new Corner());pictureScrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, new Corner());</strong></pre></blockquote>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -