Home > Articles > Programming > Java

This chapter is from the book


When an image is bigger than the viewport, we tend to scroll the image to see parts that are not visible. To pan or scroll images in a viewport, applications provide different types of user interfaces—for example, scroll bars. Some applications provide mouse-based scrolling. With mouse-based schemes, you normally hold the mouse down and drag the image so that you can view the desired portion of the image. In our design, however, we'll separate the GUI from the controller. The controller will have the logic to scroll on an image canvas, and it will accept input from any type of user interface.

Let's discuss the requirements and design an interface named ScrollController. Figure 7.6 shows how images are panned, or scrolled. The position at which you click the mouse is the anchor point, and as you drag, the current mouse position is the current position of the image. The pan offset is the displacement between the current position and the anchor point. The current image is drawn with this offset from the previous position.

FIGURE 7.6 Panning an image

To hold this displacement, let's specify a property named panOffset. The set and get methods for this property are

  • public void setPanOffset(Point panOffset);

  • public Point getPanOffset();

We need a method that initiates the scrolling. This method should set the anchor point. Let's call this method startScroll():

  • public void startScroll(int x, int y)

We also need a method that stops the scrolling:

  • public void stopScroll()

When the image is scrolled, it is painted at a new position. The paintImage() method we defined in the ImageDisplay interface will not suffice to accomplish this task. So let's specify a method for this purpose, with the displacement in the x and y directions as its inputs:

  • public void scroll(int xOffset, int yOffset);

  • This method paints the current image at an offset of xOffset and yOffset from the previous position in the x and y directions, respectively.

The ScrollController interface, shown in Listing 7.6, contains all the methods defined here.

LISTING 7.6 The ScrollController interface

public interface ScrollController {
  public void setPanOffset(Point panOffset);

  public Point getPanOffset();
  public void startScroll(int x, int y);
  public void scroll(int x, int y);
  public void stopScroll();

Implementing Pan

Now that we have designed an interface to implement scrolling (panning), let's implement a mouse-driven scroll feature. It will have two classes:

  1. Scroll. This class will control scrolling by implementing the ScrollController interface. Scroll will operate on an image canvas, so it needs to hold a reference to an object that implements the ImageManipulator interface.

  2. ScrollGUI. This class will accept user input and pass it on to Scroll Controller. In the case of mouse-driven scrolling, ScrollGUI must receive mouse and mouseMotion events from ImageManipulator.

Figure 7.7 shows a design similar to model-view-controller (MVC) architecture 1 for scrolling. The ScrollGUI object receives the mouse positions through mouse and mouseMotion events. It passes the mouse positions as pan offset to the ScrollController interface, which modifies the current transformation to take the translation into account.

FIGURE 7.7 The data flow for scrolling

We'll follow the same design pattern for all the other manipulation functions. This pattern clearly separates the GUI and the application logic, so you are free to replace ScrollGUI with another class for a different type of GUI.

Two schemes are popular for scrolling images in a viewport:

  1. Using scroll bars

  2. Using mouse-driven interfaces

Because we use the mouse-driven interface in this book, let's look at how a mouse-driven client object must interact with a Scroll object.

The Scroll object must remember two positions: the anchor point and the current position of the image. When the mouse is pressed, the mousePressed() method of a client object must call startScroll(int x, int y) and pass the current coordinates of the mouse as the input parameters. The startScroll() method must save this position as the anchor point. Whenever the mouse is dragged, the mouseDragged() method of the client object must call scroll(int x, int y) and pass the current position of the mouse as input parameters. The scroll() method must compute the displacement between the current position of the mouse and the anchor position. It must then pass this displacement to the ImageManipulator object so that it can paint the image at the current mouse position. When the mouse button is released, the mouseReleased() method of the client object must call stopScroll().

Listing 7.7 shows the code for Scroll.

LISTING 7.7 The Scroll class

package com.vistech.imageviewer;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import java.awt.geom.*;

public class Scroll implements ScrollController {
  protected AffineTransform atx = new AffineTransform();
  protected Point panOffset = new Point(0,0);
  private Point diff = new Point(0,0);
  private Point scrollAnchor = new Point(0,0);
  protected ImageManipulator imageCanvas;

  public Scroll() {}

  public Scroll(ImageManipulator imageCanvas) {
   this.imageCanvas = imageCanvas;
  public void setImageManipulator(ImageManipulator imageCanvas){
   this.imageCanvas = imageCanvas;

  public void setPanOffset(Point panOffset){
   this.panOffset = panOffset;

  public Point getPanOffset(){return panOffset; }

  public void translateIncr(double incrx, double incry) {
   atx.translate(incrx, incry);

  public void translate(double diffx, double diffy) {
   double dx = diffx -panOffset.x;
   double dy = diffy -panOffset.y;
   panOffset.x = (int)diffx;
   panOffset.y = (int)diffy;

  public void resetAndTranslate(int dx, int dy) {
   atx.setToTranslation((double)dx, (double)dy);

  public void scroll(int x, int y){
   if((x <0 )|| (y<0)) return;
   try {
     Point2D xy = null;
     xy = atx.inverseTransform((Point2D)(new Point(x,y)), xy);
     double ix = (xy.getX()-scrollAnchor.x);
     double iy = (xy.getY()-scrollAnchor.y);
   }catch(Exception e) {System.out.println(e);}

  public void startScroll(int x, int y){
   atx = imageCanvas.getTransform();
   // Create a new anchor point so that every time mouse button is clicked,
   // the image does not move, but instead the anchor point moves.
   try {
     Point2D xy = null;
     xy = atx.inverseTransform((Point2D)(new Point(x,y)), xy);
     scrollAnchor = new Point((int)(xy.getX()),(int)(xy.getY()));
    }catch(Exception e) {System.out.println(e);}

  public void stopScroll(){ imageCanvas.setCursor(Cursor.getDefaultCursor());}

  public void reset() {
   scrollAnchor = new Point(0,0);
   diff = new Point(0,0);

The Scroll class implements the ScrollController interface. Note that Scroll's constructor takes the ImageManipulator object as an input. This means you can pass any component class that implements the ImageManipulator interface as a parameter to this constructor.

The Scroll object gets the current transformation from the canvas, concatenates it with the transformation generated for the translation, and sets this concatenated transformation as the current transformation of the canvas. Let's look at Scroll's methods.


The startScroll() method first computes the anchor position and assigns it to the variable scrollAnchor. The position passed as an input parameter to startScroll() is in the user coordinate space. These coordinates need to be converted to the image space because the displayed image might have already undergone some transformations. User space is converted to image space through the inverse transformation.

What would happen if this transformation were not done? You would get different results, depending on the transformation(s) already applied to the image. If the image were flipped right to left, it would move in the opposite direction along the x-axis; that is, if you tried to pan the image left to right, it would move right to left. If the image were rotated, it would move in the direction of the rotation when you tried to pan along the x- or y-axis. Inverse transformation solves this problem. The startScroll() method also launches a new cursor to indicate that the image is being panned.

The scroll() method converts the input coordinates to the image space and computes the displacement from the anchor point. This displacement is passed to the translateIncr() method, which performs the actual translation of the image. The stopScroll() method is called when the mouse is released, and it returns the original cursor.

Next we'll look at the translation-related methods in more detail.


Applying translation makes the image move. The translateIncr() method takes translation increments as input parameters. For instance, if an image is moved to position P(x′,y′) from P(x,y), the translation parameters are the displacements from P(x,y) to P(x′,y′). The reason is that the current transformation, which is contained in the atx variable, has already taken into account the translation to P(x,y) from the original position.

As stated earlier, if the translation parameters are the coordinates from the user space (i.e., viewport), the inverse transformation needs to be applied to these coordinates so that they are in atx space.

The translate() method does the same thing as the translateIncr() method, but it takes the absolute translation from the anchor point. This method resets atx and sets the translation to the parameters specified in the inputs. It calls the setToTranslation() method of the AffineTransform class to reset atx and then translates the images to (dx, dy). Note that the input arguments are of type int. The reason is that the coordinates in the user space are integer types, and these coordinates are expected to be passed directly to this method.

User Interface for Scrolling

As stated earlier, panning in our implementation is performed through mouse and mouseMotion events. The ScrollGUI class must capture these events, which means it needs to implement the MouseListener and MouseMotionListener interfaces. Listing 7.8 shows the implementation.

LISTING 7.8 The ScrollGUI class

package com.vistech.imageviewer;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ScrollGUI implements MouseListener,MouseMotionListener{
  protected ScrollController scrollController;
  protected boolean scrollOn = true;
  protected boolean mousePressed = false;

  public ScrollGUI(ScrollController c){scrollController = c;}
  public void setScrollOn(boolean onOff){ scrollOn = onOff;}
  public void init() { setScrollOn(true);}

  public boolean getScrollOn(){ return scrollOn; }
  public void startScroll(){ scrollOn = true;}

  public void reset(){
    if(scrollController != null)scrollController.stopScroll();

  public void mousePressed(MouseEvent e) {
    if(!scrollOn) return;
    if(mousePressed) return;
    mousePressed = true;
     scrollController.startScroll(e.getX(), e.getY());

  public void mouseReleased(MouseEvent e) {
    mousePressed = false;
  public void mouseClicked(MouseEvent e){}
  public void mouseEntered(MouseEvent e){}
  public void mouseExited(MouseEvent e){}

  public void mouseDragged(MouseEvent e){
     if(scrollOn) scrollController.scroll(e.getX(), e.getY());
  public void mouseMoved(MouseEvent e){}

Note that the ScrollGUI constructor takes ScrollController as the input. It communicates with the ImageManipulator object through Scroll (see Figure 7.7).

In order for ScrollGUI to receive mouse and mouseMotion events, a separate object must register ImageManipulator with ScrollGUI. The reason is that both the ImageManipulator and the ScrollController objects are unaware of the ScrollGUI object. This registration needs to be done when ScrollGUI is constructed by an application, as shown here:

ImageManipulator imageCanvas = new ImageCanvas2D();

ScrollController scroll = new Scroll(imageCanvas);
ScrollGUI scrollUI = new ScrollGUI(scroll);


To refresh your memory, Scroll implements the ScrollController interface, and ImageCanvas2D implements the ImageManipulator interface. These objects can be used as ScrollController and ImageManipulator objects, respectively.

Let's construct a typical sequence of method calls with ScrollGUI, Scroll Controller, and ImageManipulator objects:

  1. The application that needs the scroll feature registers ScrollGUI to receive mouse and mouseMotion events with the ImageManipulator object.

  2. The user presses the left mouse button. The ImageManipulator object, which is the mouse event source, fires the mousePressed event to the ScrollGUI object. The mousePressed() method is invoked when any mouse button is clicked. Because the Scroll class uses only the left mouse button, the isLeftMouse Button() method of the SwingUtilities class checks for this condition; that is, it returns true only when the left mouse button is pressed.

  3. The mousePressed() method calls the startScroll() method in the ScrollController object, which saves the position at which the mouse was pressed as the anchor point (in the variable called anchorPoint).

  4. The user drags the mouse while holding the left mouse down. The ImageManipulator object fires the mouseDragged event, which is received by the mouseDragged() method in ScrollGUI. The mouseDragged() method is called repeatedly as the user drags the mouse.

  5. The mouseDragged() method calls the scroll() method in the Scroll Controller object and passes the current mouse coordinates as its parameters.

  6. The ImageManipulator object paints the current image (i.e., displayImage) at the new position.

  7. The user releases the mouse button, prompting the ImageManipulator object to fire a mouseReleased event. This event is received by the mouseReleased() method.

  8. The mouseReleased() method calls stopScroll() to halt scrolling.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020