KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > swing > JViewport


1 /*
2  * @(#)JViewport.java 1.114 04/05/18
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package javax.swing;
9
10 import java.awt.*;
11 import java.awt.event.*;
12 import java.awt.image.VolatileImage JavaDoc;
13 import java.awt.peer.ComponentPeer;
14 import java.applet.Applet JavaDoc;
15 import javax.swing.plaf.ViewportUI JavaDoc;
16
17 import javax.swing.event.*;
18 import javax.swing.border.*;
19 import javax.accessibility.*;
20
21
22 import java.io.Serializable JavaDoc;
23
24
25 /**
26  * The "viewport" or "porthole" through which you see the underlying
27  * information. When you scroll, what moves is the viewport. It is like
28  * peering through a camera's viewfinder. Moving the viewfinder upwards
29  * brings new things into view at the top of the picture and loses
30  * things that were at the bottom.
31  * <p>
32  * By default, <code>JViewport</code> is opaque. To change this, use the
33  * <code>setOpaque</code> method.
34  * <p>
35  * <b>NOTE:</b>We have implemented a faster scrolling algorithm that
36  * does not require a buffer to draw in. The algorithm works as follows:
37  * <ol><li>The view and parent view and checked to see if they are
38  * <code>JComponents</code>,
39  * if they aren't, stop and repaint the whole viewport.
40  * <li>If the viewport is obscured by an ancestor, stop and repaint the whole
41  * viewport.
42  * <li>Compute the region that will become visible, if it is as big as
43  * the viewport, stop and repaint the whole view region.
44  * <li>Obtain the ancestor <code>Window</code>'s graphics and
45  * do a <code>copyArea</code> on the scrolled region.
46  * <li>Message the view to repaint the newly visible region.
47  * <li>The next time paint is invoked on the viewport, if the clip region
48  * is smaller than the viewport size a timer is kicked off to repaint the
49  * whole region.
50  * </ol>
51  * In general this approach is much faster. Compared to the backing store
52  * approach this avoids the overhead of maintaining an offscreen buffer and
53  * having to do two <code>copyArea</code>s.
54  * Compared to the non backing store case this
55  * approach will greatly reduce the painted region.
56  * <p>
57  * This approach can cause slower times than the backing store approach
58  * when the viewport is obscured by another window, or partially offscreen.
59  * When another window
60  * obscures the viewport the copyArea will copy garbage and a
61  * paint event will be generated by the system to inform us we need to
62  * paint the newly exposed region. The only way to handle this is to
63  * repaint the whole viewport, which can cause slower performance than the
64  * backing store case. In most applications very rarely will the user be
65  * scrolling while the viewport is obscured by another window or offscreen,
66  * so this optimization is usually worth the performance hit when obscured.
67  * <p>
68  * <strong>Warning:</strong>
69  * Serialized objects of this class will not be compatible with
70  * future Swing releases. The current serialization support is
71  * appropriate for short term storage or RMI between applications running
72  * the same version of Swing. As of 1.4, support for long term storage
73  * of all JavaBeans<sup><font size="-2">TM</font></sup>
74  * has been added to the <code>java.beans</code> package.
75  * Please see {@link java.beans.XMLEncoder}.
76  *
77  * @version 1.114 05/18/04
78  * @author Hans Muller
79  * @author Philip Milne
80  * @see JScrollPane
81  */

82 public class JViewport extends JComponent JavaDoc implements Accessible
83 {
84     /**
85      * @see #getUIClassID
86      * @see #readObject
87      */

88     private static final String JavaDoc uiClassID = "ViewportUI";
89
90     /** Property used to indicate window blitting should not be done.
91      */

92     static final Object JavaDoc EnableWindowBlit = "EnableWindowBlit";
93
94     /**
95      * True when the viewport dimensions have been determined.
96      * The default is false.
97      */

98     protected boolean isViewSizeSet = false;
99
100     /**
101      * The last <code>viewPosition</code> that we've painted, so we know how
102      * much of the backing store image is valid.
103      */

104     protected Point lastPaintPosition = null;
105
106     /**
107      * True when this viewport is maintaining an offscreen image of its
108      * contents, so that some scrolling can take place using fast "bit-blit"
109      * operations instead of by accessing the view object to construct the
110      * display. The default is <code>false</code>.
111      *
112      * @deprecated As of Java 2 platform v1.3
113      * @see #setScrollMode
114      */

115     @Deprecated JavaDoc
116     protected boolean backingStore = false;
117
118     /** The view image used for a backing store. */
119     transient protected Image JavaDoc backingStoreImage = null;
120
121     /**
122      * The <code>scrollUnderway</code> flag is used for components like
123      * <code>JList</code>. When the downarrow key is pressed on a
124      * <code>JList</code> and the selected
125      * cell is the last in the list, the <code>scrollpane</code> autoscrolls.
126      * Here, the old selected cell needs repainting and so we need
127      * a flag to make the viewport do the optimized painting
128      * only when there is an explicit call to
129      * <code>setViewPosition(Point)</code>.
130      * When <code>setBounds</code> is called through other routes,
131      * the flag is off and the view repaints normally. Another approach
132      * would be to remove this from the <code>JViewport</code>
133      * class and have the <code>JList</code> manage this case by using
134      * <code>setBackingStoreEnabled</code>. The default is
135      * <code>false</code>.
136      */

137     protected boolean scrollUnderway = false;
138
139     /*
140      * Listener that is notified each time the view changes size.
141      */

142     private ComponentListener viewListener = null;
143
144     /* Only one <code>ChangeEvent</code> is needed per
145      * <code>JViewport</code> instance since the
146      * event's only (read-only) state is the source property. The source
147      * of events generated here is always "this".
148      */

149     private transient ChangeEvent changeEvent = null;
150
151     /**
152       * Use <code>graphics.copyArea</code> to implement scrolling.
153       * This is the fastest for most applications.
154       *
155       * @see #setScrollMode
156       * @since 1.3
157       */

158     public static final int BLIT_SCROLL_MODE = 1;
159
160     /**
161       * Draws viewport contents into an offscreen image.
162       * This was previously the default mode for <code>JTable</code>.
163       * This mode may offer advantages over "blit mode"
164       * in some cases, but it requires a large chunk of extra RAM.
165       *
166       * @see #setScrollMode
167       * @since 1.3
168       */

169     public static final int BACKINGSTORE_SCROLL_MODE = 2;
170
171     /**
172       * This mode uses the very simple method of redrawing the entire
173       * contents of the scrollpane each time it is scrolled.
174       * This was the default behavior in Swing 1.0 and Swing 1.1.
175       * Either of the other two options will provide better performance
176       * in most cases.
177       *
178       * @see #setScrollMode
179       * @since 1.3
180       */

181     public static final int SIMPLE_SCROLL_MODE = 0;
182
183     /**
184       * @see #setScrollMode
185       * @since 1.3
186       */

187     private int scrollMode = BLIT_SCROLL_MODE;
188
189     //
190
// Window blitting:
191
//
192
// As mentioned in the javadoc when using windowBlit a paint event
193
// will be generated by the system if copyArea copies a non-visible
194
// portion of the view (in other words, it copies garbage). We are
195
// not guaranteed to receive the paint event before other mouse events,
196
// so we can not be sure we haven't already copied garbage a bunch of
197
// times to different parts of the view. For that reason when a blit
198
// happens and the Component is obscured (the check for obscurity
199
// is not supported on all platforms and is checked via ComponentPeer
200
// methods) the ivar repaintAll is set to true. When paint is received
201
// if repaintAll is true (we previously did a blit) it is set to
202
// false, and if the clip region is smaller than the viewport
203
// waitingForRepaint is set to true and a timer is started. When
204
// the timer fires if waitingForRepaint is true, repaint is invoked.
205
// In the mean time, if the view is asked to scroll and waitingForRepaint
206
// is true, a blit will not happen, instead the non-backing store case
207
// of scrolling will happen, which will reset waitingForRepaint.
208
// waitingForRepaint is set to false in paint when the clip rect is
209
// bigger (or equal) to the size of the viewport.
210
// A Timer is used instead of just a repaint as it appeared to offer
211
// better performance.
212

213
214     /**
215      * This is set to true in <code>setViewPosition</code>
216      * if doing a window blit and the viewport is obscured.
217      */

218     private transient boolean repaintAll;
219
220     /**
221      * This is set to true in paint, if <code>repaintAll</code>
222      * is true and the clip rectangle does not match the bounds.
223      * If true, and scrolling happens the
224      * repaint manager is not cleared which then allows for the repaint
225      * previously invoked to succeed.
226      */

227     private transient boolean waitingForRepaint;
228
229     /**
230      * Instead of directly invoking repaint, a <code>Timer</code>
231      * is started and when it fires, repaint is invoked.
232      */

233     private transient Timer JavaDoc repaintTimer;
234
235     /**
236      * Whether or not a valid view has been installed.
237      */

238     private boolean hasHadValidView;
239
240     /** Creates a <code>JViewport</code>. */
241     public JViewport() {
242         super();
243         setLayout(createLayoutManager());
244     setOpaque(true);
245         updateUI();
246     }
247
248
249
250     /**
251      * Returns the L&F object that renders this component.
252      *
253      * @return a <code>ViewportUI</code> object
254      */

255     public ViewportUI JavaDoc getUI() {
256         return (ViewportUI JavaDoc)ui;
257     }
258
259
260     /**
261      * Sets the L&F object that renders this component.
262      *
263      * @param ui the <code>ViewportUI</code> L&F object
264      * @see UIDefaults#getUI
265      * @beaninfo
266      * bound: true
267      * hidden: true
268      * attribute: visualUpdate true
269      * description: The UI object that implements the Component's LookAndFeel.
270      */

271     public void setUI(ViewportUI JavaDoc ui) {
272         super.setUI(ui);
273     }
274
275
276     /**
277      * Resets the UI property to a value from the current look and feel.
278      *
279      * @see JComponent#updateUI
280      */

281     public void updateUI() {
282         setUI((ViewportUI JavaDoc)UIManager.getUI(this));
283     }
284
285
286     /**
287      * Returns a string that specifies the name of the L&F class
288      * that renders this component.
289      *
290      * @return the string "ViewportUI"
291      *
292      * @see JComponent#getUIClassID
293      * @see UIDefaults#getUI
294      */

295     public String JavaDoc getUIClassID() {
296         return uiClassID;
297     }
298
299
300     /**
301      * Sets the <code>JViewport</code>'s one lightweight child,
302      * which can be <code>null</code>.
303      * (Since there is only one child which occupies the entire viewport,
304      * the <code>constraints</code> and <code>index</code>
305      * arguments are ignored.)
306      *
307      * @param child the lightweight <code>child</code> of the viewport
308      * @param constraints the <code>constraints</code> to be respected
309      * @param index the index
310      * @see #setView
311      */

312     protected void addImpl(Component child, Object JavaDoc constraints, int index) {
313       setView(child);
314     }
315
316
317     /**
318      * Removes the <code>Viewport</code>s one lightweight child.
319      *
320      * @see #setView
321      */

322     public void remove(Component child) {
323         child.removeComponentListener(viewListener);
324         super.remove(child);
325     }
326
327
328     /**
329      * Scrolls the view so that <code>Rectangle</code>
330      * within the view becomes visible.
331      * <p>
332      * This attempts to validate the view before scrolling if the
333      * view is currently not valid - <code>isValid</code> returns false.
334      * To avoid excessive validation when the containment hierarchy is
335      * being created this will not validate if one of the ancestors does not
336      * have a peer, or there is no validate root ancestor, or one of the
337      * ancestors is not a <code>Window</code> or <code>Applet</code>.
338      * <p>
339      * Note that this method will not scroll outside of the
340      * valid viewport; for example, if <code>contentRect</code> is larger
341      * than the viewport, scrolling will be confined to the viewport's
342      * bounds.
343      *
344      * @param contentRect the <code>Rectangle</code> to display
345      * @see JComponent#isValidateRoot
346      * @see java.awt.Component#isValid
347      * @see java.awt.Component#getPeer
348      */

349     public void scrollRectToVisible(Rectangle contentRect) {
350         Component view = getView();
351
352         if (view == null) {
353             return;
354         } else {
355         if (!view.isValid()) {
356         // If the view is not valid, validate. scrollRectToVisible
357
// may fail if the view is not valid first, contentRect
358
// could be bigger than invalid size.
359
validateView();
360         }
361             int dx = 0, dy = 0;
362
363             dx = positionAdjustment(getWidth(), contentRect.width, contentRect.x);
364             dy = positionAdjustment(getHeight(), contentRect.height, contentRect.y);
365
366             if (dx != 0 || dy != 0) {
367                 Point viewPosition = getViewPosition();
368         Dimension viewSize = view.getSize();
369         int startX = viewPosition.x;
370         int startY = viewPosition.y;
371         Dimension extent = getExtentSize();
372
373         viewPosition.x -= dx;
374         viewPosition.y -= dy;
375                 // Only constrain the location if the view is valid. If the
376
// the view isn't valid, it typically indicates the view
377
// isn't visible yet and most likely has a bogus size as will
378
// we, and therefore we shouldn't constrain the scrolling
379
if (view.isValid()) {
380                     if (getParent().getComponentOrientation().isLeftToRight()) {
381                         if (viewPosition.x + extent.width > viewSize.width) {
382                             viewPosition.x = Math.max(0, viewSize.width - extent.width);
383                         } else if (viewPosition.x < 0) {
384                             viewPosition.x = 0;
385                         }
386                     } else {
387                         if (extent.width > viewSize.width) {
388                             viewPosition.x = viewSize.width - extent.width;
389                         } else {
390                             viewPosition.x = Math.max(0, Math.min(viewSize.width - extent.width, viewPosition.x));
391             }
392                     }
393                     if (viewPosition.y + extent.height > viewSize.height) {
394                         viewPosition.y = Math.max(0, viewSize.height -
395                                                   extent.height);
396                     }
397                     else if (viewPosition.y < 0) {
398                         viewPosition.y = 0;
399                     }
400                 }
401         if (viewPosition.x != startX || viewPosition.y != startY) {
402             setViewPosition(viewPosition);
403             // NOTE: How JViewport currently works with the
404
// backing store is not foolproof. The sequence of
405
// events when setViewPosition
406
// (scrollRectToVisible) is called is to reset the
407
// views bounds, which causes a repaint on the
408
// visible region and sets an ivar indicating
409
// scrolling (scrollUnderway). When
410
// JViewport.paint is invoked if scrollUnderway is
411
// true, the backing store is blitted. This fails
412
// if between the time setViewPosition is invoked
413
// and paint is received another repaint is queued
414
// indicating part of the view is invalid. There
415
// is no way for JViewport to notice another
416
// repaint has occured and it ends up blitting
417
// what is now a dirty region and the repaint is
418
// never delivered.
419
// It just so happens JTable encounters this
420
// behavior by way of scrollRectToVisible, for
421
// this reason scrollUnderway is set to false
422
// here, which effectively disables the backing
423
// store.
424
scrollUnderway = false;
425         }
426             }
427         }
428     }
429
430     /**
431      * Ascends the <code>Viewport</code>'s parents stopping when
432      * a component is found that returns
433      * <code>true</code> to <code>isValidateRoot</code>.
434      * If all the <code>Component</code>'s parents are visible,
435      * <code>validate</code> will then be invoked on it. The
436      * <code>RepaintManager</code> is then invoked with
437      * <code>removeInvalidComponent</code>. This
438      * is the synchronous version of a <code>revalidate</code>.
439      */

440     private void validateView() {
441         Component validateRoot = null;
442
443     /* Find the first JComponent ancestor of this component whose
444      * isValidateRoot() method returns true.
445      */

446         for(Component c = this; c != null; c = c.getParent()) {
447         if ((c instanceof CellRendererPane JavaDoc) || (c.getPeer() == null)) {
448         return;
449         }
450         if ((c instanceof JComponent JavaDoc) &&
451         (((JComponent JavaDoc)c).isValidateRoot())) {
452         validateRoot = c;
453         break;
454         }
455     }
456
457     // If no validateRoot, nothing to validate from.
458
if (validateRoot == null) {
459         return;
460     }
461
462     // Make sure all ancestors are visible.
463
Component root = null;
464     
465     for(Component c = validateRoot; c != null; c = c.getParent()) {
466             // We don't check isVisible here, otherwise if the component
467
// is contained in something like a JTabbedPane when the
468
// component is made visible again it won't have scrolled
469
// to the correct location.
470
if (c.getPeer() == null) {
471         return;
472         }
473         if ((c instanceof Window) || (c instanceof Applet JavaDoc)) {
474         root = c;
475         break;
476         }
477     }
478
479     // Make sure there is a Window ancestor.
480
if (root == null) {
481         return;
482     }
483
484     // Validate the root.
485
validateRoot.validate();
486
487     // And let the RepaintManager it does not have to validate from
488
// validateRoot anymore.
489
RepaintManager JavaDoc rm = RepaintManager.currentManager(this);
490
491     if (rm != null) {
492         rm.removeInvalidComponent((JComponent JavaDoc)validateRoot);
493     }
494     }
495
496      /* Used by the scrollRectToVisible method to determine the
497       * proper direction and amount to move by. The integer variables are named
498       * width, but this method is applicable to height also. The code assumes that
499       * parentWidth/childWidth are positive and childAt can be negative.
500       */

501     private int positionAdjustment(int parentWidth, int childWidth, int childAt) {
502
503         // +-----+
504
// | --- | No Change
505
// +-----+
506
if (childAt >= 0 && childWidth + childAt <= parentWidth) {
507             return 0;
508         }
509
510         // +-----+
511
// --------- No Change
512
// +-----+
513
if (childAt <= 0 && childWidth + childAt >= parentWidth) {
514             return 0;
515         }
516
517         // +-----+ +-----+
518
// | ---- -> | ----|
519
// +-----+ +-----+
520
if (childAt > 0 && childWidth <= parentWidth) {
521             return -childAt + parentWidth - childWidth;
522         }
523
524         // +-----+ +-----+
525
// | -------- -> |--------
526
// +-----+ +-----+
527
if (childAt >= 0 && childWidth >= parentWidth) {
528             return -childAt;
529         }
530
531         // +-----+ +-----+
532
// ---- | -> |---- |
533
// +-----+ +-----+
534
if (childAt <= 0 && childWidth <= parentWidth) {
535             return -childAt;
536         }
537
538         // +-----+ +-----+
539
//-------- | -> --------|
540
// +-----+ +-----+
541
if (childAt < 0 && childWidth >= parentWidth) {
542             return -childAt + parentWidth - childWidth;
543         }
544
545         return 0;
546     }
547
548
549     /**
550      * The viewport "scrolls" its child (called the "view") by the
551      * normal parent/child clipping (typically the view is moved in
552      * the opposite direction of the scroll). A non-<code>null</code> border,
553      * or non-zero insets, isn't supported, to prevent the geometry
554      * of this component from becoming complex enough to inhibit
555      * subclassing. To create a <code>JViewport</code> with a border,
556      * add it to a <code>JPanel</code> that has a border.
557      * <p>Note: If <code>border</code> is non-<code>null</code>, this
558      * method will throw an exception as borders are not supported on
559      * a <code>JViewPort</code>.
560      *
561      * @param border the <code>Border</code> to set
562      * @exception IllegalArgumentException this method is not implemented
563      */

564     public final void setBorder(Border border) {
565         if (border != null) {
566             throw new IllegalArgumentException JavaDoc("JViewport.setBorder() not supported");
567         }
568     }
569
570
571     /**
572      * Returns the insets (border) dimensions as (0,0,0,0), since borders
573      * are not supported on a <code>JViewport</code>.
574      *
575      * @return a <code>Rectange</code> of zero dimension and zero origin
576      * @see #setBorder
577      */

578     public final Insets getInsets() {
579         return new Insets(0, 0, 0, 0);
580     }
581
582     /**
583      * Returns an <code>Insets</code> object containing this
584      * <code>JViewport</code>s inset values. The passed-in
585      * <code>Insets</code> object will be reinitialized, and
586      * all existing values within this object are overwritten.
587      *
588      * @param insets the <code>Insets</code> object which can be reused
589      * @return this viewports inset values
590      * @see #getInsets
591      * @beaninfo
592      * expert: true
593      */

594     public final Insets getInsets(Insets insets) {
595         insets.left = insets.top = insets.right = insets.bottom = 0;
596         return insets;
597     }
598
599
600     private Graphics getBackingStoreGraphics(Graphics g) {
601         Graphics bsg = backingStoreImage.getGraphics();
602         bsg.setColor(g.getColor());
603         bsg.setFont(g.getFont());
604         bsg.setClip(g.getClipBounds());
605         return bsg;
606     }
607
608
609     private void paintViaBackingStore(Graphics g) {
610         Graphics bsg = getBackingStoreGraphics(g);
611     try {
612         super.paint(bsg);
613         g.drawImage(backingStoreImage, 0, 0, this);
614     } finally {
615         bsg.dispose();
616     }
617     }
618
619     private void paintViaBackingStore(Graphics g, Rectangle oClip) {
620         Graphics bsg = getBackingStoreGraphics(g);
621     try {
622         super.paint(bsg);
623         g.setClip(oClip);
624         g.drawImage(backingStoreImage, 0, 0, this);
625     } finally {
626         bsg.dispose();
627     }
628     }
629
630     /**
631      * The <code>JViewport</code> overrides the default implementation of
632      * this method (in <code>JComponent</code>) to return false.
633      * This ensures
634      * that the drawing machinery will call the <code>Viewport</code>'s
635      * <code>paint</code>
636      * implementation rather than messaging the <code>JViewport</code>'s
637      * children directly.
638      *
639      * @return false
640      */

641     public boolean isOptimizedDrawingEnabled() {
642         return false;
643     }
644
645     /**
646      * Returns true if scroll mode is a BACKINGSTORE_SCROLL_MODE to cause
647      * painting to originate from <code>JViewport</code>, or one of its
648      * ancestors. Otherwise returns false.
649      *
650      * @return true if if scroll mode is a BACKINGSTORE_SCROLL_MODE.
651      * @see JComponent#isPaintingOrigin()
652      */

653     boolean isPaintingOrigin() {
654     if (scrollMode == BACKINGSTORE_SCROLL_MODE) {
655         return true;
656     }
657         return false;
658     }
659
660
661     /**
662      * Only used by the paint method below.
663      */

664     private Point getViewLocation() {
665         Component view = getView();
666         if (view != null) {
667             return view.getLocation();
668         }
669         else {
670             return new Point(0,0);
671         }
672     }
673
674     /**
675      * Depending on whether the <code>backingStore</code> is enabled,
676      * either paint the image through the backing store or paint
677      * just the recently exposed part, using the backing store
678      * to "blit" the remainder.
679      * <blockquote>
680      * The term "blit" is the pronounced version of the PDP-10
681      * BLT (BLock Transfer) instruction, which copied a block of
682      * bits. (In case you were curious.)
683      * </blockquote>
684      *
685      * @param g the <code>Graphics</code> context within which to paint
686      */

687     public void paint(Graphics g)
688     {
689         int width = getWidth();
690         int height = getHeight();
691
692         if ((width <= 0) || (height <= 0)) {
693             return;
694         }
695
696     if (repaintAll) {
697         repaintAll = false;
698         Rectangle clipB = g.getClipBounds();
699         if (clipB.width < getWidth() ||
700         clipB.height < getHeight()) {
701         waitingForRepaint = true;
702         if (repaintTimer == null) {
703             repaintTimer = createRepaintTimer();
704         }
705         repaintTimer.stop();
706         repaintTimer.start();
707         // We really don't need to paint, a future repaint will
708
// take care of it, but if we don't we get an ugly flicker.
709
}
710         else {
711         if (repaintTimer != null) {
712             repaintTimer.stop();
713         }
714         waitingForRepaint = false;
715         }
716     }
717     else if (waitingForRepaint) {
718         // Need a complete repaint before resetting waitingForRepaint
719
Rectangle clipB = g.getClipBounds();
720         if (clipB.width >= getWidth() &&
721         clipB.height >= getHeight()) {
722         waitingForRepaint = false;
723         repaintTimer.stop();
724         }
725     }
726
727         if (!backingStore || isBlitting() || getView() == null) {
728             super.paint(g);
729             lastPaintPosition = getViewLocation();
730             return;
731         }
732
733         // If the view is smaller than the viewport and we are not opaque
734
// (that is, we won't paint our background), we should set the
735
// clip. Otherwise, as the bounds of the view vary, we will
736
// blit garbage into the exposed areas.
737
Rectangle viewBounds = getView().getBounds();
738     if (!isOpaque()) {
739         g.clipRect(0, 0, viewBounds.width, viewBounds.height);
740     }
741
742         if (backingStoreImage == null) {
743             // Backing store is enabled but this is the first call to paint.
744
// Create the backing store, paint it and then copy to g.
745
// The backing store image will be created with the size of
746
// the viewport. We must make sure the clip region is the
747
// same size, otherwise when scrolling the backing image
748
// the region outside of the clipped region will not be painted,
749
// and result in empty areas.
750
backingStoreImage = createImage(width, height);
751         Rectangle clip = g.getClipBounds();
752         if (clip.width != width || clip.height != height) {
753         if (!isOpaque()) {
754             g.setClip(0, 0, Math.min(viewBounds.width, width),
755                   Math.min(viewBounds.height, height));
756         }
757         else {
758             g.setClip(0, 0, width, height);
759         }
760         paintViaBackingStore(g, clip);
761         }
762         else {
763         paintViaBackingStore(g);
764         }
765         }
766         else {
767             if (!scrollUnderway || lastPaintPosition.equals(getViewLocation())) {
768                 // No scrolling happened: repaint required area via backing store.
769
paintViaBackingStore(g);
770             } else {
771                 // The image was scrolled. Manipulate the backing store and flush it to g.
772
Point blitFrom = new Point();
773                 Point blitTo = new Point();
774                 Dimension blitSize = new Dimension();
775                 Rectangle blitPaint = new Rectangle();
776
777                 Point newLocation = getViewLocation();
778                 int dx = newLocation.x - lastPaintPosition.x;
779                 int dy = newLocation.y - lastPaintPosition.y;
780                 boolean canBlit = computeBlit(dx, dy, blitFrom, blitTo, blitSize, blitPaint);
781                 if (!canBlit) {
782                     // The image was either moved diagonally or
783
// moved by more than the image size: paint normally.
784
paintViaBackingStore(g);
785                 } else {
786                     int bdx = blitTo.x - blitFrom.x;
787                     int bdy = blitTo.y - blitFrom.y;
788
789                     // Move the relevant part of the backing store.
790
Rectangle clip = g.getClipBounds();
791             // We don't want to inherit the clip region when copying
792
// bits, if it is inherited it will result in not moving
793
// all of the image resulting in garbage appearing on
794
// the screen.
795
g.setClip(0, 0, width, height);
796                     Graphics bsg = getBackingStoreGraphics(g);
797             try {
798                 bsg.copyArea(blitFrom.x, blitFrom.y, blitSize.width, blitSize.height, bdx, bdy);
799
800             g.setClip(clip.x, clip.y, clip.width, clip.height);
801             // Paint the rest of the view; the part that has just been exposed.
802
Rectangle r = viewBounds.intersection(blitPaint);
803             bsg.setClip(r);
804             super.paint(bsg);
805
806             // Copy whole of the backing store to g.
807
g.drawImage(backingStoreImage, 0, 0, this);
808             } finally {
809                 bsg.dispose();
810             }
811                 }
812             }
813         }
814         lastPaintPosition = getViewLocation();
815         scrollUnderway = false;
816     }
817
818
819     /**
820      * Sets the bounds of this viewport. If the viewport's width
821      * or height has changed, fire a <code>StateChanged</code> event.
822      *
823      * @param x left edge of the origin
824      * @param y top edge of the origin
825      * @param w width in pixels
826      * @param h height in pixels
827      *
828      * @see JComponent#reshape(int, int, int, int)
829      */

830     public void reshape(int x, int y, int w, int h) {
831     boolean sizeChanged = (getWidth() != w) || (getHeight() != h);
832         if (sizeChanged) {
833             backingStoreImage = null;
834         }
835         super.reshape(x, y, w, h);
836     if (sizeChanged) {
837         fireStateChanged();
838     }
839     }
840
841
842     /**
843       * Used to control the method of scrolling the viewport contents.
844       * You may want to change this mode to get maximum performance for your
845       * use case.
846       *
847       * @param mode one of the following values:
848       * <ul>
849       * <li> JViewport.BLIT_SCROLL_MODE
850       * <li> JViewport.BACKINGSTORE_SCROLL_MODE
851       * <li> JViewport.SIMPLE_SCROLL_MODE
852       * </ul>
853       *
854       * @see #BLIT_SCROLL_MODE
855       * @see #BACKINGSTORE_SCROLL_MODE
856       * @see #SIMPLE_SCROLL_MODE
857       *
858       * @beaninfo
859       * bound: false
860       * description: Method of moving contents for incremental scrolls.
861       * enum: BLIT_SCROLL_MODE JViewport.BLIT_SCROLL_MODE
862       * BACKINGSTORE_SCROLL_MODE JViewport.BACKINGSTORE_SCROLL_MODE
863       * SIMPLE_SCROLL_MODE JViewport.SIMPLE_SCROLL_MODE
864       *
865       * @since 1.3
866       */

867     public void setScrollMode(int mode) {
868         scrollMode = mode;
869     if (mode == BACKINGSTORE_SCROLL_MODE) {
870         backingStore = true;
871     } else {
872         backingStore = false;
873     }
874     }
875
876     /**
877       * Returns the current scrolling mode.
878       *
879       * @return the <code>scrollMode</code> property
880       * @see #setScrollMode
881       * @since 1.3
882       */

883     public int getScrollMode() {
884         return scrollMode;
885     }
886
887     /**
888      * Returns <code>true</code> if this viewport is maintaining
889      * an offscreen image of its contents.
890      *
891      * @return <code>true</code> if <code>scrollMode</code> is
892      * <code>BACKINGSTORE_SCROLL_MODE</code>
893      *
894      * @deprecated As of Java 2 platform v1.3, replaced by
895      * <code>getScrollMode()</code>.
896      */

897     @Deprecated JavaDoc
898     public boolean isBackingStoreEnabled() {
899         return scrollMode == BACKINGSTORE_SCROLL_MODE;
900     }
901
902
903     /**
904      * If true if this viewport will maintain an offscreen
905      * image of its contents. The image is used to reduce the cost
906      * of small one dimensional changes to the <code>viewPosition</code>.
907      * Rather than repainting the entire viewport we use
908      * <code>Graphics.copyArea</code> to effect some of the scroll.
909      *
910      * @param enabled if true, maintain an offscreen backing store
911      *
912      * @deprecated As of Java 2 platform v1.3, replaced by
913      * <code>setScrollMode()</code>.
914      */

915     @Deprecated JavaDoc
916     public void setBackingStoreEnabled(boolean enabled) {
917         if (enabled) {
918         setScrollMode(BACKINGSTORE_SCROLL_MODE);
919     } else {
920         setScrollMode(BLIT_SCROLL_MODE);
921     }
922     }
923
924     private final boolean isBlitting() {
925         Component view = getView();
926         return (scrollMode == BLIT_SCROLL_MODE) &&
927            (view instanceof JComponent JavaDoc) && ((JComponent JavaDoc)view).isOpaque();
928     }
929
930
931     /**
932      * Returns the <code>JViewport</code>'s one child or <code>null</code>.
933      *
934      * @return the viewports child, or <code>null</code> if none exists
935      *
936      * @see #setView
937      */

938     public Component getView() {
939         try {
940         return getComponent(0);
941     } catch (ArrayIndexOutOfBoundsException JavaDoc e) {
942         return null;
943     }
944     }
945
946     /**
947      * Sets the <code>JViewport</code>'s one lightweight child
948      * (<code>view</code>), which can be <code>null</code>.
949      *
950      * @param view the viewport's new lightweight child
951      *
952      * @see #getView
953      */

954     public void setView(Component view) {
955
956         /* Remove the viewport's existing children, if any.
957          * Note that removeAll() isn't used here because it
958          * doesn't call remove() (which JViewport overrides).
959          */

960         int n = getComponentCount();
961         for(int i = n - 1; i >= 0; i--) {
962             remove(getComponent(i));
963         }
964
965         isViewSizeSet = false;
966
967         if (view != null) {
968             super.addImpl(view, null, -1);
969             viewListener = createViewListener();
970             view.addComponentListener(viewListener);
971         }
972
973         if (hasHadValidView) {
974             // Only fire a change if a view has been installed.
975
fireStateChanged();
976         }
977         else if (view != null) {
978             hasHadValidView = true;
979         }
980
981     revalidate();
982     repaint();
983     }
984
985
986     /**
987      * If the view's size hasn't been explicitly set, return the
988      * preferred size, otherwise return the view's current size.
989      * If there is no view, return 0,0.
990      *
991      * @return a <code>Dimension</code> object specifying the size of the view
992      */

993     public Dimension getViewSize() {
994         Component view = getView();
995
996         if (view == null) {
997             return new Dimension(0,0);
998         }
999         else if (isViewSizeSet) {
1000            return view.getSize();
1001        }
1002        else {
1003            return view.getPreferredSize();
1004        }
1005    }
1006
1007
1008    /**
1009     * Sets the size of the