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

📄 scrollpane.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 4 页
字号:
<p>Remember that the size of each corner is determined bythe size of the sides intersecting there.For some componentsyou must take care that the specific instanceof the component fits in its corner.For example, the program sets the font and marginson the toggle button so thatit fits within the space established by the headers.It's not an issue with the <code>Corner</code> classbecause that class colors its entire bounds,whatever they happen to be, with a solid color.<p>As you can see from the code, constants indicate the corner positions.This figure shows the constant for each position:<p><center><IMG SRC="../../figures/uiswing/components/6corverns.gif" WIDTH="508" HEIGHT="132" ALIGN="BOTTOM" ALT="Corner constants"></center></p>The constants are defined in 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 <code>JScrollPane</code> implements.</blockquote><a name="scrollable"><h3>Implementing a Scrolling-Savvy Client</h3></a><blockquote>To customize the way that a client component interactswith its scroll pane,you can make the component implement the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/Scrollable.html"><code>Scrollable</code></a> interface.By implementing <code>Scrollable</code>,a client can specify boththe size of the viewport used to view itand the amount to scroll for clicks on the different controls on a scroll bar.<blockquote><hr><strong>Note:</strong>&nbsp;If you can't or don't want to implement a scrollable client,you can specify the unit and block incrementsusing the<code>setUnitIncrement</code>and<code>setBlockIncrement</code>methods of<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JScrollBar.html"><code>JScrollBar</code></a>.For example, the following code sets the unit increment for vertical scrolling to 10 pixels:<blockquote><pre>scrollPane.getVerticalScrollBar().setUnitIncrement(10);</pre></blockquote><hr></blockquote><p>Here again are the three control areas of a scroll bar:the knob, 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>You might have noticed when manipulating the scroll barsin <code>ScrollDemo</code> that clicking the buttonsscrolls the image to a tick boundary.You might alsohave noticed that clicking in the track scrolls thepicture by a "screenful". More generally, the buttonscrolls the visible area by a unit increment and the trackscrolls the visible area by a block increment.The behavior you see in the example is not the scroll pane's defaultbehavior, but is specified by the clientin its implementation of the <code>Scrollable</code> interface.<p>The client for the <code>ScrollDemo</code> program is<a class="SourceLink" target="_blank" href="examples/ScrollablePicture.java"><code>ScrollablePicture</code></a>.<code>ScrollablePicture</code> is a subclass of <code>JLabel</code>that provides implementations of all five <code>Scrollable</code> methods:<ul><li> <code>getScrollableBlockIncrement</code><li> <code>getScrollableUnitIncrement</code><li> <code>getPreferredScrollableViewportSize</code><li> <code>getScrollableTracksViewportHeight</code><li> <code>getScrollableTracksViewportWidth</code></ul><code>ScrollablePicture</code> implements the <code>Scrollable</code>interface primarily to affect the unit and block increments.However, it must provide implementations for all five methods.Thus, it provides reasonable defaults for the other three methodsthat you might want to copy for your scrolling-savvy classes.<p>The scroll pane calls the client's<code>getScrollableUnitIncrement</code>method whenever the user clicksone of the buttons on the scroll bar.This method returns the number of pixels to scroll.An obvious implementation of this method returns thenumber of pixels between tick marks on the header rulers.<code>ScrollablePicture</code>, however, does something different:It returns the value required to position the image ona tick mark boundary. Here's the implementation:<blockquote><pre>public int getScrollableUnitIncrement(Rectangle visibleRect,                                      int orientation,                                      int direction) {    //Get the current position.    int currentPosition = 0;    if (orientation == SwingConstants.HORIZONTAL) {        currentPosition = visibleRect.x;    } else {        currentPosition = visibleRect.y;    }    //Return the number of pixels between currentPosition    //and the nearest tick mark in the indicated direction.    if (direction < 0) {        int newPosition = currentPosition -                         (currentPosition / maxUnitIncrement)                          * maxUnitIncrement;        return (newPosition == 0) ? maxUnitIncrement : newPosition;    } else {        return ((currentPosition / maxUnitIncrement) + 1)                 * maxUnitIncrement                 - currentPosition;    }}</pre></blockquote>If the image is already on a tick mark boundary, this method returnsthe number of pixels between ticks. Otherwise, it returns the numberof pixels from the current location to the nearest tick.<p>Likewise,the scroll pane calls the client's <code>getScrollableBlockIncrement</code>method each time the user clicks on the track.Here's<code>ScrollablePicture</code>'s implementation of this method:<blockquote><pre>public int getScrollableBlockIncrement(Rectangle visibleRect,                                       int orientation,                                       int direction) {    if (orientation == SwingConstants.HORIZONTAL)        return visibleRect.width - maxUnitIncrement;    else        return visibleRect.height - maxUnitIncrement;}</pre></blockquote>This method returns the height of the visible rectangle minus a tick mark.This behavior is typical. A block increment should be slightly smallerthan the viewport to leave a little of the previous visible area for context.For example, a text area might leave one or two lines of text for contextand a table might leave a row or column (depending on the scroll direction).<p><code>ScrollablePicture.java</code> has one more bit of code that's not required by the <code>Scrollable</code> interface,but is common in scrollable components:a mouse motion listenerthat lets the user scrollthe picture by dragging from it.The boldface code in the following snippetimplements scrolling by dragging:<blockquote><pre>public class ScrollablePicture extends JLabel                               implements Scrollable,                                          <b>MouseMotionListener</b> {    ...    public ScrollablePicture(...) {        ...        <b>setAutoscrolls(true);</b> //enable synthetic drag events        <b>addMouseMotionListener(this);</b> //handle mouse drags    }    ...    <b>public void mouseDragged(MouseEvent e) {</b>        //The user is dragging us, so scroll!        <b>Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);        scrollRectToVisible(r);    }</b>...}</pre></blockquote>This snippet scrolls the picturewhenever the user drags from the picture to a locationoutside the picture and pauses.The <code>setAutoscrolls</code> methodis defined by <code>JComponent</code>for the purpose of assisting &#151;but not implementing &#151; scrolling by dragging.Setting the autoscrolls property to <code>true</code>makes the component fire synthetic mouse-dragged eventseven when the mouse isn't moving(because it stopped, mid-drag, outside the component).It's up to the component's mouse motion listenerto listen for these events and react accordingly.</blockquote><a name="sizing"><h3>Sizing a Scroll Pane</h3></a><blockquote>Unless you explicitly set a scroll pane's preferred size,the scroll pane computes itbased on the preferred size of its nine components(the viewport, and, if present, the two scroll bars,the row and column headers, and the four corners).The largest factor,and the one most programmers care about,is the size of the viewport used to display the client.<p>If the client is not scrolling-savvy,then the scroll pane sizes itself so thatthe client displays at its preferred size.For typical unsavvy clients,this makes the scroll pane redundant.That is, the scroll pane has no scroll barsbecause the client's preferred sizeis big enough to display the entire client.In this case,if the client doesn't change size dynamically,you should probably limit the size of thescroll pane by setting its preferred sizeor the preferred size of its container.<p>If the client is scrolling-savvy,then the scroll pane uses the value returned by the client's<code>getPreferredScrollableViewportSize</code>method to compute the size of its viewport.Implementations of this methodgenerally report a preferred size for scrollingthat's smaller than the component's standard preferred size.For example, by default, the value returned by<code>JList</code>'s implementation of<code>getPreferredScrollableViewportSize</code>is just big enough to display eight rows.<p>Scrolling-savvy classes, like<a href="list.html">lists</a>,<a href="table.html">tables</a>,<a href="text.html">text components</a>, and<a href="tree.html">trees</a>,often provide one or more methodsthat let programmers affect the size returned from<code>getPreferredScrollableViewportSize</code>.For example,you can set the number of visible rows in a listor a tree by calling the<code>setVisibleRowCount</code> method.The list or tree takes care of figuring out thesize needed to display that number of rows.<p>Refer to <a href="#otherAPI">Methods in Other Classes Related to Scrolling</a>for information about scrolling-related methodsprovided by classes other than <code>JScrollPane</code>.And remember &#151;if you don't like the value that<code>getPreferredScrollableViewportSize</code> returns,you can always set the preferred size of the scroll paneor its container.</blockquote><a name="update"><h3>Dynamically Changing the Client's Size</h3></a><blockquote>Changing the size of a scroll pane's clientis a two-step process.First, set the client's preferred size. Then,call <code>revalidate</code> on the client tolet the scroll pane know that it should update itselfand its scroll bars.Let's look at an example.<p>Here's a picture of an applicationthat changes the client's size whenever the user placesa circle whose bounds fall outside of the client's current bounds.The program also changes the client's size when the user clearsthe drawing area:<p><center><IMG SRC="../../figures/uiswing/components/ScrollDemo2.png" WIDTH="262" HEIGHT="266" ALIGN="BOTTOM" ALT="A snapshot of ScrollDemo2"></center></p><p align=center>You can find the full source code for this example in<a class="SourceLink" target="_blank" href="examples/ScrollDemo2.java"><code>ScrollDemo2.java</code></a>,which is based on an example provided by tutorial reader John Vella.You can <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/ScrollDemo2.jnlp"><b>run ScrollDemo2</b></a> (it requires release 6) using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.    <p>Here's the code that changes the drawing area'ssize when necessary:<blockquote><pre>if (changed) {    //Update client's preferred size because    //the area taken up by the graphics has    //gotten larger or smaller (if cleared).    drawingArea.setPreferredSize(<em>/* the new size */</em>);    //Let the scroll pane know to update itself    //and its scroll bars.    drawingArea.revalidate();}</pre></blockquote>Note that when the client changes size,the scroll bars adjust.The scroll pane doesn't resize, nor does the viewport.<p>Refer to<a href="examples/index.html#SplitPaneDemo"><code>SplitPaneDemo</code></a> for another example in whichthe client object changes size.</blockquote><h3><a name="api">The Scroll Pane API</a></h3><blockquote>The following tables list the commonly usedscroll-related constructors and methods.Other methods you are most likely to invoke ona <code>JScrollPane</code> object are thosesuch as <code>setPreferredSize</code>that its superclasses provide.See<a href="jcomponent.html#api">The JComponent API</a>for tables of commonly used inherited methods.<p>The API for using scroll panes falls into these categories:<ul><li><a href="#setup">Setting Up the Scroll Pane</a><li><a href="#decorationsAPI">Decorating the Scroll Pane</a><li><a href="#scrollableAPI">Implementing a Scrolling-Savvy Client</a><li><a href="#otherAPI">Methods in Other Classes Related to Scrolling</a></ul><p><table border=1><caption><a name="setup">Setting Up the Scroll Pane</a><br>(<code>JScrollPane</code> constructors and methods)</caption><tr><th align=left>Method or Constructor</th><th align=left>Purpose</th></tr>  <tr>    <td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JScrollPane.html#JScrollPane()">JScrollPane()</a>    <br><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JScrollPane.html#JScrollPane(java.awt.Component)">JScrollPane(Component)</a>    <br><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JScrollPane.html#JScrollPane(int, int)">JScrollPane(int, int)</a>    <br><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JScrollPane.html#JScrollPane(java.awt.Component, int, int)">JScrollPane(Component, int, int)</a>    </td>    <td>Create a scroll pane.        The <code>Component</code> parameter, when present, sets        the scroll pane's client.        The two <code>int</code> parameters, when present, set the        vertical and horizontal scroll bar policies (respectively).    </td>  </tr>  <tr>    <td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JScrollPane.html#setViewportView(java.awt.Component)"><code>void setViewportView(Component)</a>    </td>    <td>Set the scroll pane's client.    </td>  </tr>  <tr>    <td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JScrollPane.html#setVerticalScrollBarPolicy(int)">void setVerticalScrollBarPolicy(int)</a>    <br><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JScrollPane.html#getVerticalScrollBarPolicy()">int getVerticalScrollBarPolicy()</a>    </td>    <td>Set or get the vertical scroll policy.        <code>ScrollPaneConstants</code> defines three values

⌨️ 快捷键说明

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