How To Use Scroll Panes

xiaoxiao2021-03-05  23

How To Use Scroll Panes

A

Jscrollpane

provides a scrollable view of a component. When screen real estate is limited, use a scroll pane to display a component that is large or one whose size can change dynamically. Other containers used to save screen space include

Split Panes and

Tabbed panes.

. The code to create a scroll pane can be minimal For example, here's a picture of a demo program that puts a text area in a scroll pane because the text area's size grows dynamically as text is appended to it:

Here's The Core That Creates The Text Area, Makes It The Scroll Pane's Client, Andds The Scroll Pane to a Container:

// in a container That Uses a BorderLayout:

Textarea = New Jtextarea (5, 30);

...

JscrollPane scrollpane = new jscrollpane (textarea);

...

SetPreferRedsize (New Dimension (450, 110));

...

Add (Scrollpane, BorderLayout.center);

The boldface line of code creates the

JScrollpane, Specifying The Text Area as The Scroll Pane's Client. The Program Doesn't Invoke Any Methods on The

.........................

You might have noticed that the preceding code sets 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 requested when creating it, so the scroll bar initially displays a vertical scroll bar. If we did not restrict the size of the scroll pane's container, the scroll pane would be big enough for the text area to display the full 5 rows and 30 columns specified with THE JTEXTAREA Constructor. Refer to Sizing A Scroll Pane for Information About Techniques for Making A Scroll Pane The Size You Want.The REST OF This Section Discusses The Following Topics:

How a Scroll Pane Works Setting the Scroll Bar Policy Providing Custom Decorations Implementing a Scrolling-Savvy Client Sizing a Scroll Pane Dynamically Changing the Client's Size The Scroll Pane API Examples that Use Scroll Panes

How A Scroll Pane Works

How A Scroll Pane Works

Here Is A Snapshot of An Application That Uses a Customized Scroll Pane To View a Large Photo:

The scroll pane in this application looks very different from 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.

TRY THIS:

Run ScrollDemo using JavaTM Web Start. Or, to compile and run the example yourself, consult the example index. Move the knobs on the scroll bars. Watch the image scroll and the horizontal and vertical rulers scroll along. If you have a mouse with a wheel (which is generally between the mouse buttons) use the mouse wheel to scroll the image vertically. Support for mouse wheel scrolling was added in v 1.4. Click the cm 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). 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 . 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 Jcomponen t API, but implemented by the custom component that displays the image. 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.the ScrollDemo Program Establishes The Scroll Pane's Client When Creating The Scroll Pane:

// WHERE The Member Variables Are Declared:

Private ScrollablePicture Picture;

...

// Where the gui is create

Picture = new scrollablepicture;

JScrollPane PicturescrollPane = New Jscrollpane (Picture);

The Scroll Pane's Client Is Also Known As The

View OR

ViewPort View. You can change the client dynamically by calling the

SetViewPortview Method. Note Thatjscrollpane Has No Corresponding

GetViewPortview Method. if you need to refer to the client Object Again, You Can Either Cache It in a variable or invoke

GetViewPort (). GetViewPortview () on The Scroll Pane.

. 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 pane and its client and indicates the classes that the scroll pane commissions to help:

A scroll pane uses a JViewport instance to manage the visible area of ​​the client. The viewport is responsible for computing the bounds of the current visible area, based on the positions of the scroll bars, and displaying it.

A scroll pane uses two separate instances of JScrollBar for the scroll bars The scroll bars provide the interface for the user to manipulate the visible area The following figure shows the three areas of a scroll bar:.. The knob (sometimes called the thumb), The button, and the track.

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 user moves the knob on the horizontal scroll bar to the right and left, the visible area of ​​the client moves back and forth accordingly. The position of the knob relative to its track is proportionally equal to the 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 clue as to how much of the client is visible.

By clicking a button, the user can scroll by a unit increment. By clicking within the track, the user can scroll by a block increment. 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 scrolls is 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 increments or to use a block increment instead. More information about unit and block increments is in Implementing a scrolling-Savvy Client.Typical programs do not directly instantiate or call methods on a viewport or scroll bar. Instead, programs achieve their scrolling behavior using the JScrollPane API and the API discussed in Implementing A Scrolling-Savvy Client. Some Scrolling-Savvy Components Such As Jlist, JTable, and Jtree Also Provide ADDITIONAL API TO HELP You Affect Their Scrolling Behavior.

Setting The Scroll Bar Policy

On Startup, The Scroll Pane in The Scroll Pane in

ScrollDemo 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 without changing its width, the vertical scroll bar reappears. Further experimentation will show That in this application Both Scroll Bars Disappear and reviews

Scroll Bar Policy, Actually, It's Two Policies: Each Scroll Bar Has ITS OWN.

ScrollDemo Doesn't Explicitly Set The Scroll Pane's Scroll Bar Policies - IT Uses The Default. You Cretenamical The scroll pane or change the.

Of The Constructors Provided by Jscrollpane, There Two Let You Set The Scroll Bar Policies When You Create The Scroll Pane: Jscrollpane (Component, Int, int)

Jscrollpane (int, int)

The first

Int Specifies The Policy for The Vertical Scroll Bar; The Second Specifies The Policy for The Horizontal Scroll Bar. You Can Also Set The Policies Dynamically with The

SETHORIZONTALSCROLLBARPOLICY AND

Single ONE FINE

ScrollPaneConstants

Interface (Which Is Implement by

JScrollPane):

Policy Description VERTICAL_SCROLLBAR_AS_NEEDED HORIZONTAL_SCROLLBAR_AS_NEEDED The default. The scroll bar appears when the viewport is smaller than the client and disappears when the viewport is larger than the client. VERTICAL_SCROLLBAR_ALWAYS HORIZONTAL_SCROLLBAR_ALWAYS Always display the scroll bar. The knob disappears if the viewport is large enough to show the whole client. VERTICAL_SCROLLBAR_NEVER HORIZONTAL_SCROLLBAR_NEVER Never display the scroll bar. use this option if you do not 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).

Providing Custom Decorations

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 always present in all scroll panes Besides scroll bars, the sides can contain column and row. .................

[Pending: Picture Will Be Updated to Reflect That Gray Lines no longer Appear.]

. As shown in the figure, the scroll pane in ScrollDemo 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 Rules, 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 present in this example, the toggle button is also always present.If a corner contains a control that 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 toggle in the lower right corner where the scroll bars Internet Disappered.

The scroll pane's row and column headers are provided by a custom JComponent subclass, Rule, that draws a ruler in centimeters or inches Here's the code that creates and sets the scroll pane's row and column headers.:

// WHERE The Member Variables Are Defined:

Private rule columnview;

PRIVATE RULE RowView;

...

// Where the gui is initialized:

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 ());

}

...

PicturescrollPane.setColumnHeaderView (ColumnView);

Picturescrollpane.setrowheaderview;

You can use any component for a scroll pane's row and column headers. The scroll pane puts the row and column headers inJViewPorts of their own. Thus, when scrolling horizontally, the column header follows along, and when scrolling vertically, the row header follows along .

As a JComponent subclass, our custom Rule class puts its rendering code in its paintComponent method. The Rule rendering code takes care to draw only within the current clipping bounds, to ensure speedy scrolling. Your custom row and column headers should do the same.

You can also use any component for the corners of a scroll pane. ScrollDemo illustrates this by putting a toggle button in the upper left corner, and custom Corner objects in the upper right and lower left corners. Here's the code that creates the Corner objects and Calls setCorner to Place Them:

// CREATE The CORNERS.

JPanel ButtonCorner = new jPanel (); // USE FlowLayout

IsMetric = 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.

PicturescrollPane.SetCorner (jscrollpane.upper_left_corner,

ButtonCorner;

PicturescrollPane.setcorner (jscrollpane.lower_left_corner,

New correnergy ());

Picturescrollpane.setcorner (jscrollpane.upper_right_corner,

New correnergy ());

Remember that the size of each corner is determined by the size of the sides intersecting there. For some components you must take care that the specific instance of the component fits in its corner. For example, the program sets the font and margins on the toggle button so that it fits within the space established by the headers. It's not an issue with the Corner class because that class colors its entire bounds, whatever they happen to be, with a solid color.As you can see from the code, constants indicate The Corner Positions. This Figure shows the constant for each position:

The constants are defined in the constants

ScrollPaneConstants

Interface, Which

JScrollPane Implements.

Implementing a scrolling-savvy client

To Customize The Way That A Client Component Interacts with ITS Scroll Panent IMPLEMENT THE

Scrollable

Interface. by import

.

Note: if You can't or don't want to import a scroll client, you can specify the unit and block increments sale the

SetUnitIncrement and

SetBlockIncrement Methods of

Jscrollbar

. For example the unit incrtain for vertical scrolling to 10 pixels:

Scrollpane.getVerticalscrollbar (). setUnitIncrement (10);

Here Again Are The Three Control Areas of A Scroll Bar: The Knob, The Buttons, And The Track.

You Might Have Noticed When Manipulating The Scroll Bars in

ScrollDemo that clicking the buttons scrolls the image to a tick boundary. You might also have noticed that clicking in the track scrolls the picture by a "screenful". More generally, the button scrolls the visible area by a unit increment and the track scrolls the .

The Client for the ScrollDemo Program IS ScrollablePicture. ScrollablePicture Is A Subclass of Jlabel That Provides Implementations of All Five Scrollable Methods:

GetScrollBlockIncrement GetScrollableunititis Crement GetPreferredscrollableviewportsize GetscrollTracksViewPortHeight GetscrollableTracksViewPortWidth

ScrollablePicture IMPLEMENTS

Scrollable 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 methods that you might want to copy for your scrolling-savvy classes.

The scroll pane calls the client's getScrollableUnitIncrement method whenever the user clicks one of the buttons on the scroll bar. This method returns the number of pixels to scroll. An obvious implementation of this method returns the number of pixels between tick marks on the header rulers. ScrollablePicture, However, Does Something Different: It Returns The value Required to Position The Image ON A Tick Mark Boundary. Here's The Implementation:

Public int GetScrollableunitIncrement (Rectangle VisibleRect)

Int Orientation,

INT DIRECTION) {

// Get the current position.

INT currentPosition = 0;

IF (orientation == swingconstants.horizontal) {currentposition = VisibilityRect.x;

} else {

CurrentPosition = VisibilityRect.Y;

}

// Return The Number of Pixels Between CurrentPosition

// and the nearest Tick Mark in The Indicated Direction.

IF (Direction <0) {

Int newPosition = currentposition -

CurrentPosition / MaxUnitIndincrement)

* MaxUnitIncrement;

Return (newPosition == 0)? MAXUNITINCREMENT: NewPosition;

} else {

Return (CurrentPosition / MaxUnitInt) 1)

* MaxUnitIncrement

- CurrentPosition;

}

}

IF The IMAGENDY ON A TICK MARK Boundary, this Method Returns The Number of Pixels Between Ticks. OtherWise, It Returns The Number of Pixels from The Current Location To The Nearest Tick.

Likewise, The Scroll Pane Calls The Client's GetscrollBlockIncrement Method Each Time The User Click ON The Track. Here's ScrollablePicture's Implementation of this Method:

Public int GetScrollableBlockIncrement (Rectangle Visibility,

Int Orientation,

INT DIRECTION) {

IF (orientation == swingconstants.horizontal)

Return VisibilityRect.Width - MaxUnitIncrement;

Else

Return VisibilityRect.height - maxincree;

}

This method returns the height of the visible rectangle minus a tick mark. This behavior is typical. A block increment should be slightly smaller than 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 Context and a Table Might Leave a Row Or Column (Depending On The Scroll Direction).

ScrollablePicture.java has one more bit of code that's not required by the Scrollable interface, but is common in scrollable components: a mouse motion listener that lets the user scroll the picture by dragging from it The boldface code in the following snippet implements scrolling by. Dragging: Public Class ScrollablePicture Extends Jlabel

Implements scrollable,

MouseMotionListener {

...

Public scrollablepicture (...) {

...

SetAutoscrolls (true); // enable synthetic Drag Events

AddMouseMotionListener (this); // Handle Mouse Drags

}

...

Public void mousedraged (mouseevent e) {

// the user is dragging us, so scroll!

Rectangle R = New Rectangle (E.GETX (), E.GETY (), 1, 1);

ScrollRectTovisible (R);

}

...

}

THIS SNIPPET SCROLLS The Picture WHENEVER THE DRAGS from The Picture To a location Outside The Picture and Pauses. The

SetAutoscrolls Method Is Defined by

JComponent for the purpose of associSting - But not implementing - scrolling by Dragging. Setting The AutoScrolls Property To

true makes the component fire synthetic mouse-dragged events even when the mouse is not moving (because it stopped, mid-drag, outside the component). It's up to the component's mouse motion listener to listen for these events and react accordingly.

SIZING A SCROLL PANE

Unless you explicitly set a scroll pane's preferred size, the scroll pane computes it based 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.

If the client is not scrolling-savvy, then the scroll pane sizes itself so that the client displays at its preferred size. For typical unsavvy clients, this makes the scroll pane redundant. That is, the scroll pane has no scroll bars because the client's preferred size is big enough to display the entire client. In this case, if the client does not change size dynamically, you should probably limit the size of the scroll pane by setting its preferred size or the preferred size of its container.If the client is scrolling-savvy, then the scroll pane uses the value returned by the client's getPreferredScrollableViewportSize method to compute the size of its viewport. Implementations of this method generally report a preferred size for scrolling that's smaller than the component's standard preferred size. for example, .

Scrolling-savvy classes, like lists, tables, text components, and trees, often provide one or more methods that let programmers affect the size returned from getPreferredScrollableViewportSize. For example, you can set the number of visible rows in a list or a tree by .

Refer to Methods in Other Classes Related to Scrolling for information about scrolling-related methods provided by classes other than JScrollPane And remember -. If you do not like the value that getPreferredScrollableViewportSize returns, you can always set the preferred size of the scroll pane or ITS Container.

Dynamically Changing The Client's Size

CHANGING THE SIZE OF A SCROLL PANE'S Client Is A Two-Step Process. First, Set The Client's PreferRed Size. Then, Call

Revalidate on the client to let the scroll pane know thing it will below.. Let's look at an example.

. Here's a picture of an application that changes the client's size whenever the user places a circle whose bounds fall outside of the client's current bounds The program also changes the client's size when the user clears the drawing area:

[Pending: this snapshot will bedated] You can Fill Source Code for this Example in

ScrollDemo2.java

, Which is based on an example, provided by Tutorial Reader John Vella. You CAN

Run scrolldemo2 using

Java Web Start

.

Here's The Code That Changes The Drawing Area's Size When Necessary:

IF (Changed) {

// Update Client's PreferRed Size Because

// the area taken up by The Graphics HAS

// Gotten Larger or Smaller (if clear).

Drawingarea.setpreferredsize (/ * the new size * /);

// let the scroll Pane Know to update itself

// And ITS Scroll Bars.

Drawingarea.Revalidate ();

}

Note That When The Client Changes Size, The Scroll Bars Adjust. The Scroll Pane Doesn't Resize, Nor Does The Viewport.

Refer to Splitpanedemo for Another Example in Which The Client Object Changes size.

The Scroll Pane API

The Following Tables List The Commonly Used Scroll-Related Constructors and Methods. Other Methods You Are Most Likely to Invoke ON A

JscrollPane Object Are Those Such As

SetPreferredSize That ITS SuperClasses Provide. See

The JComponent API for Tables of Commonly Used Inherited Methods.

The Api for Using Scroll Pains Falls Into these Categories:

Setting Up The Scroll Pane Decorating The Scroll Pane Implementing A Scrolling-Savvy Client Methods in Other Classes Related To ScrollingSetting Up The Scroll Pane

(

JscrollPane Constructionors and Methods)

Method or Constructor Purpose JScrollPane () JScrollPane (Component) JScrollPane (int, int) JScrollPane (Component, int, int) Create a scroll pane. The Component parameter, when present, sets the scroll pane's client. The two int parameters, when present ..., set the vertical and horizontal scroll bar policies (respectively) void setViewportView (Component) Set the scroll pane's client void setVerticalScrollBarPolicy (int) int getVerticalScrollBarPolicy () Set or get the vertical scroll policy ScrollPaneConstants defines three values ​​for specifying this policy: . VERTICAL_SCROLLBAR_AS_NEEDED (the default), VERTICAL_SCROLLBAR_ALWAYS, and VERTICAL_SCROLLBAR_NEVER void setHorizontalScrollBarPolicy (int) int getHorizontalScrollBarPolicy () Set or get the horizontal scroll policy ScrollPaneConstants defines three values ​​for specifying this policy:.. HORIZONTAL_SCROLLBAR_AS_NEEDED (the default), HORIZONTAL_SCROLLBAR_ALWAYS, and HORIZONTAL_SCROLLBAR_NEVER void setViewportBorder (Border) Border GetViewPo rtBorder () Set or get the border around the viewport. void setWheelScrollingEnabled (boolean) boolean isWheelScrollingEnabled () Set or get whether scrolling occurs in response to the mouse wheel. Mouse-wheel scrolling is enabled by default. Introduced in 1.4.

Decorating the scroll pane

(

JscrollPane Methods)

Method Purpose void setColumnHeaderView (Component) void setRowHeaderView (Component) Set the column or row header for the scroll pane. Void setCorner (String, Component) Component getCorner (String) Set or get the corner specified. The int parameter specifies which corner and must be one of the following constants defined in ScrollPaneConstants:. UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER, LOWER_LEFT_CORNER, LOWER_RIGHT_CORNER, LOWER_LEADING_CORNER, LOWER_TRAILING_CORNER, UPPER_LEADING_CORNER, and UPPER_TRAILING_CORNER The last four constants (LEADING / TRAILING) were introduced in 1.3, but are not usable as late as 1.4 .2 due to bug 4467063.implementing a scrolling-savvy client

Method Purpose int getScrollableUnitIncrement (Rectangle, int, int) int getScrollableBlockIncrement (Rectangle, int, int) (required by the Scrollable interface) Get the unit or block increment in pixels. The Rectangle parameter is the bounds of the currently visible rectangle. The first int parameter is either SwingConstants.HORIZONTAL or SwingConstants.VERTICAL depending on what scroll bar the user clicked on. The second int parameter indicates which direction to scroll. A value less than 0 indicates up or left. A value greater than 0 indicates down or right . Dimension getPreferredScrollableViewportSize () (required by the Scrollable interface) Get the preferred size of the viewport. This allows the client to influence the size of the viewport in which it is displayed. If the viewport size is unimportant, implement this method to return getPreferredSize Boolean getscrollabletracksviewportwidth () Boolean getscrollabletracksviewportheight () (Required by the scroll interface) Get WHETH er the scroll pane should force the client to be the same width or height as the viewport. A return value of true from either of these methods effectively disallows horizontal or vertical scrolling (respectively). void setAutoscrolls (boolean) (in JComponent) Set whether synthetic mouse dragged events should be generated when the user drags the mouse outside of the component and stops;. these events are necessary for scrolling by dragging by default, the value is false, but many scrollable components such as JTable and custom components set the value To True.Methods in Other classes related to scrolling

转载请注明原文地址:https://www.9cbs.com/read-32338.html

New Post(0)