Home > Articles > Programming > Java

This chapter is from the book

A Tiled-Image Viewer

Using the RenderedImageCanvas class described in the previous section, let's create a viewer that is capable of displaying large images. Let's also add a panel called Tile Grid to show the viewport position and size with respect to the image (see Figure 11.6). We'll also add one more way to pan the image: dragging the rectangle that represents the image to move the image within the viewport. To control the tile size, let's add two text fields for entering tile width and height.

FIGURE 11.6 An image viewer for viewing large images

In addition to the classes mentioned in the JAI planar-image viewer example (see Chapter 10), here are the classes used in this application:

  • TiledImageViewer. This is the main class that launches the application. It is a subclass of JAIImageViewer.

  • RenderedImageCanvas. This class displays the image. It is a subclass of JAIImageCanvas (see the section titled Viewing and Manipulating Large Images earlier in this chapter).

  • RenderGrid. This class implements the Tile Grid panel. It displays the tile grid, as well as the viewport as a rectangle positioned over the tile grid. The position of this rectangle varies when you scroll the image. The position of the image changes when you drag this rectangle.

Now let's look at the code. We have already discussed the RenderedImageCanvas code, so let's look at the RenderGrid class. Even though this class uses no JAI API, we list it here because it draws heavily from the Java 2D graphical and rendering APIs. Listing 11.5 shows the code for RenderGrid.

LISTING 11.5 The RenderGrid class

package com.vistech.jai.render;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import java.awt.geom.*;

public class RenderGrid extends JPanel {
  protected int maxTileIndexX, maxTileIndexY;
  protected int tileWidth, tileHeight;
  protected Point vpPos = new Point(0,0);
  protected Rectangle currentShape;
  protected int panX =0, panY =0;
  protected int width, height;
  protected boolean dragOn = false;
  private Point scrollAnchor = new Point(0,0);
  protected AffineTransform atx = new AffineTransform();
  protected Dimension vpSize;

  public RenderGrid() {
   enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK |

  public Dimension getViewportDimension(){
   return new Dimension(width, height);

  public void setTileIndices(int maxXIndex, int maxYIndex){
   this.maxTileIndexX = maxXIndex;
   this.maxTileIndexY = maxYIndex;

  public void setTileDimension(int width, int height){
   tileWidth = width; tileHeight = height;

  public void setTileWidth(int tw){
   tileWidth = tw; repaint();
  public int getTileWidth(){ return tileWidth;}

  public void setTileHeight(int th){
   tileHeight = th; repaint();
  public int getTileHeight(){ return tileHeight;}
  public void setMaxTileIndexX(int tix){
   maxTileIndexX = tix; repaint();

  public int getMaxTileIndexX(){return maxTileIndexX;}

  public void setMaxTileIndexY(int tiy){
   maxTileIndexY = tiy; repaint();
  public int getMaxTileIndexY(){return maxTileIndexY;}
  public void setTransform(AffineTransform at){atx = at;}
  public void setViewportSize(Dimension size){vpSize = size;}

  public void processMouseEvent(MouseEvent e){
     case MouseEvent.MOUSE_PRESSED:
       setCursor(new Cursor(Cursor.MOVE_CURSOR));
       int x = e.getX();
       int y = e.getY();
       if(currentShape.contains(x,y)) { dragOn = true;}
     case MouseEvent.MOUSE_CLICKED:
     case MouseEvent.MOUSE_RELEASED:
       dragOn = false;

  public void processMouseMotionEvent(MouseEvent e){
     case MouseEvent.MOUSE_DRAGGED:
       if(dragOn) scroll(e.getX(), e.getY());

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

  public void startScroll(int x, int y){
   if(dragOn) return;
   scrollAnchor.x = x- panX;
   scrollAnchor.y = y- panY;

  public void scroll(int x, int y){
   panX = x-scrollAnchor.x;
   panY = y-scrollAnchor.y;
   setPan(new Point(panX, panY));

  public void setPan(Point pos){
   firePropertyChange("viewportPosition",this.vpPos, pos);
   int x = (int)( pos.x * (maxTileIndexX*tileWidth)/(width-20));
   int y = (int)( pos.y * (maxTileIndexY*tileHeight)/(height-20));
   this.vpPos = new Point(x,y);

  public void setViewportPosition(Point vpPos){
   this.vpPos = vpPos; repaint();

  public void paintComponent(Graphics gc) {
   Graphics2D g = (Graphics2D)gc;
   Rectangle bounds = this.getBounds();
   width = bounds.width-20;
   height = bounds.height-20;
   double gridWidth = (width)/(double)maxTileIndexX;
   double gridHeight = (height)/(double)maxTileIndexY;
   g.fillRect(0,0,bounds.width, bounds.height);
   if ((maxTileIndexX == 0)|| (maxTileIndexY == 0)) return;
   double vertStartX = 10.0; double vertStartY = 10.0;
   double vertEndX = 10.0;
   double vertEndY = (double)maxTileIndexY*gridHeight+vertStartY;
   // Horizontal lines
   for(int i= 0; i<maxTileIndexX; i++) {
     g.drawLine((int)vertStartX, (int)vertStartY, (int)vertEndX, (int)vertEndY);
     vertStartX += gridWidth;
     vertEndX  += gridWidth;
   g.drawLine((int)vertStartX, (int)vertStartY,
         (int)vertEndX, (int)vertEndY);
   double horizStartX = 10.0; double horizStartY = 10.0;
   double horizEndX = maxTileIndexX*gridWidth+horizStartX;
   double horizEndY = 10.0;
   // Horizontal lines
   for(int i=0; i<maxTileIndexY; i++) {
     g.drawLine((int)horizStartX, (int)horizStartY,
           (int)horizEndX, (int)horizEndY);
     horizEndY += gridHeight;
     horizStartY  += gridHeight;
   g.drawLine((int)horizStartX, (int)horizStartY,
         (int)horizEndX, (int)horizEndY);
   vertStartX = 10.0; vertStartY = 10.0;
   int vpWid, vpHt;
   if(vpSize == null){ vpWid = (int)gridWidth; vpHt = (int)gridHeight;}
   else {
     vpWid = vpSize.width; vpHt = vpSize.height;

   if(dragOn) {
     currentShape = new Rectangle(-(int)vertStartX+panX,
                   -(int)vertStartY+panY,vpWid, vpHt);
    }else {
     int x = (int)(vertStartX +
         vpPos.x * ((width)/(double)(maxTileIndexX*tileWidth)));
     int y = (int)(vertStartY +
         vpPos.y * ((height)/(double)(maxTileIndexY*tileHeight)));
     currentShape = new Rectangle(x,y,vpWid,vpHt);


The RenderGrid class handles mouse and mouseMotion events internally. When the mouse is pressed, the processMouseEvent() method checks whether the position of the cursor is within the rectangle. If so, it sets the dragOn variable to true. When the mouse is dragged, the processMouseMotion() method moves the rectangle. This method also calls the setPan() method, which fires the propertyChange event for the viewportPosition property.

The use of propertyChange events eliminates the need to call RenderedImage Canvas directly. An interposing object can receive this event and invoke appropriate methods in RenderedImageCanvas. In this case, the interposing object is the Tiled ImageViewer object, which upon receipt of this event, calls the setViewport Position() method of RenderedImageCanvas.

Likewise, when the mouse is dragged over the image, RenderedImageCanvas fires the propertyChange event for its viewportPosition property. Again this event is captured by the TiledImageViewer object, which in turn invokes RenderGrid's setViewportPosition() method. Thus, by using propertyChange events, you can avoid circular dependency between RenderGrid and RenderedImageCanvas. Moreover, both RenderedImageCanvas and RenderGrid can be used as beans and can be visually connected by binding properties (see Appendix B).

The paintComponent() method draws first the grid and then the rectangle representing the viewport. If the value of dragOn is true, which means the user is moving the rectangle, the panX and panY variables are used for moving the rectangle. If it is false, vpPos is used for moving the rectangle. The vpPos variable is set by the setViewportPosition() method, which is called by TiledImageViewer whenever it receives a propertyChange event for the viewportPosition property. The TiledImage Viewer object also sets the tile dimensions, on the basis of which RenderGrid draws the grid. Listing 11.6 shows the code for TiledImageViewer.

LISTING 11.6 The TiledImageViewer class: Part 1 (continued in Listing 11.7)

public class TiledImageViewer extends JAIImageViewer{
  protected RenderedImageCanvas viewer;
  protected RenderGrid renderGrid;
  protected JTextField twidth, theight;
  protected JTextArea memoryMessageBar;

  public void createUI() {
   Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
   int width = (int)(dim.width *3/4.0);
   int height = (int)(dim.height*3/4.0);

   setTitle("Rendering JAI Images");
   viewer = new RenderedImageCanvas();
   Dimension d = getViewerSize(width/(double)height);
   viewer.setPreferredSize(new Dimension(d.width, d.height));

     new PlanarImageLoadedListener() {
       public void imageLoaded(PlanarImageLoadedEvent e) {
        PlanarImage image = e.getImage();
        if(image == null) return;
        SwingUtilities.invokeLater(new ImagePaint(image));

   twidth = new JTextField(5);
   theight = new JTextField(5);
   renderGrid = new RenderGrid();
   renderGrid.setBorder(BorderFactory.createTiledBorder("Tile Grid"));
      //... Gridbag layout code not shown.


  protected void addPropertyChangeEventAdapters(){
     new PropertyChangeListener() {
       public void propertyChange(PropertyChangeEvent e) {
          if(renderGrid != null) updateRenderGrid();
          Point p =(Point)e.getNewValue();
           renderGrid.setMaxTileIndexX(((Integer)e.getNewValue()).            intValue());
           renderGrid.setMaxTileIndexY(((Integer)e.getNewValue()).            intValue());
           int wid = renderGrid.getViewportDimension().width;
           int ht = renderGrid.getViewportDimension().height;
           double scaleX = wid/(double)viewer.getSize().width;
           double scaleY = ht/(double)viewer.getSize().height;
           AffineTransform atx = (AffineTransform)e.getNewValue();

     new PropertyChangeListener() {
       public void propertyChange(PropertyChangeEvent e) {
          double scaleX, scaleY;
          int wid = renderGrid.getViewportDimension().width;
          int ht = renderGrid.getViewportDimension().height;
          scaleX = viewer.getImageWidth()/wid;
          scaleY = viewer.getImageHeight()/ht;
          if(e.getNewValue() instanceof Point){
           Point p =(Point)e.getNewValue();
           viewer.pan(-p.x*scaleX, -p.y*scaleY);


  protected void updateRenderGrid() {
   if(viewer == null) return;
   int tw1 = viewer.getTileWidth();
   int th1 = viewer.getTileHeight();
   int xInd1 = viewer.getMaxTileIndexX();
   int yInd1 = viewer.getMaxTileIndexY();
   renderGrid.setTileIndices(xInd1, yInd1);
   int wid = renderGrid.getViewportDimension().width;
   int ht = renderGrid.getViewportDimension().height;
   double scaleX = viewer.getSize().width/(double)viewer.getImageWidth();
   double scaleY = viewer.getSize().height/(double)viewer.getImageHeight();
   double scaledVpX = wid*scaleX;
   double scaledVpY = ht*scaleY;
   renderGrid.setViewportSize(new Dimension((int)scaledVpX,(int)scaledVpY));

TiledImageViewer is the main application class that launches the application. To run the application, type "java app.TiledImageViewer" or "java app.TiledImageViewer <image path>" on the command line.

The TiledImageViewer class extends JAIImageViewer and overrides the createUI() method. As Figure 11.6 shows, the left-hand panel of the window that represents this application has the Tile Grid pane and two text fields, for setting the tile width and height.

TiledImageViewer acts as an event adapter between RenderGrid and RenderedImageCanvas objects. When the GUI is created, TiledImageViewer registers to receive the propertyChange events from both RenderGrid and RenderedImage Canvas objects. The call to the addPropertyChangeEventAdapters() method in Listing 11.6 shows that this registration is done through anonymous inner classes.

When a user drags the mouse over the image, RenderImageCanvas fires a propertyChange event for the viewportPosition property. When TiledImageViewer receives this event, it calls the setViewportPosition() method in the RenderGrid object. Likewise, when a user moves the rectangle in the Tile Grid pane, the TiledImageViewer object receives the propertyChange event for the viewport Position property. In this case TiledImageViewer calls the pan() method in RenderedImageCanvas. Figure 11.7 shows how TiledImageViewer facilitates communication between RenderGrid and RenderedImageCanvas via propertyChange events.

FIGURE 11.7 The propertyChange event flow

TiledImageViewer acts as an event adapter for other properties as well, including tileWidth, tileHeight, maxTileIndexX, and maxTileIndexY.

Setting the Tile Parameters

You can change the tile layout by entering the tile width and height in the text fields located at the bottom of the left-hand pane. This pane also has a memory status bar that shows the total available and free memory. The memory status is updated whenever the mouse is clicked on the image. Note that the memory readings may not always be accurate. Listing 11.7 shows the code that handles events from the text fields and the code that updates the memory status bar.

LISTING 11.7 The TiledImageViewer class: Part 2 (continued from Listing 11.6)

  public JPanel createTileSetPanel(){
   memoryMessageBar = createMemoryMessageBar();
   //..Gridbag layout code

   return pan;

  protected void addTileParamsEventAdapters(){
     new ActionListener(){
      public void actionPerformed(ActionEvent e) {
        try {
         String str = ((JTextField) e.getSource()).getText();
         int wid = Integer.parseInt(str);
         str = theight.getText();
         int ht = Integer.parseInt(str);
         if(renderGrid != null) updateRenderGrid();
        } catch (Exception e2){}
     } );
     new ActionListener(){
      public void actionPerformed(ActionEvent e) {
        try {
         String str = ((JTextField) e.getSource()).getText();
         int ht = Integer.parseInt(str);
         str = twidth.getText();
         int wid = Integer.parseInt(str);
         if(renderGrid != null) updateRenderGrid();
        } catch (Exception e1){}

     new MouseAdapter() {
      public void mouseReleased(MouseEvent e){

  protected JTextArea createMemoryMessageBar(){
   JTextArea messageBar = new JTextArea();
   return messageBar;

  protected void updateMemoryMessageBar(JTextArea mbar) {
   Runtime rt = Runtime.getRuntime();
   long totalMemory = rt.totalMemory();
   long freemem = rt.freeMemory();
   mbar.setText("Total = "+ totalMemory+ "\n" +
          "Free = " + freemem);

The updateMemoryMessageBar() method calls some utility methods in the java.lang.Runtime class to obtain the amount of total available memory and free memory. It also calls the System.gc() method to run the garbage collector. As we learned in Chapter 10, however, calling this method does not guarantee that the garbage collector will run. The updateMemoryMessageBar() method posts the amount of free memory to the memory message bar.

Painting the Image in a Thread

The TiledImageViewer class also overrides the ImagePaint class, which is shown in Listing 11.8. Running the image-painting routine on a thread is essential for painting large images.

LISTING 11.8 The ImagePaint class

class ImagePaint implements Runnable {
   PlanarImage image;
   boolean firstTime = true;
   public ImagePaint(PlanarImage image){this.image = image;}
   public void run() {
     if(firstTime) {
      try {
       firstTime = false;
       int wid = image.getWidth();
       int height = image.getHeight();
      } catch(Exception e){SwingUtilities.invokeLater(this);}
     else {
      if(!viewer.isImageDrawn()) SwingUtilities.invokeLater(this);

The ImagePaint thread is created by an anonymous class that retrieves the image from the PlanarImageLoaded event object (see the createUI() method in Listing 11.6). In the first pass, the run() method calls RenderedImageCanvas's setImage() method, which calls the repaint() method to start the image painting.

The SwingUtilities.invokeLater() method runs the ImagePaint thread repeatedly until isImageDrawn() returns true. When that happens, the run() method calls updateRenderGrid(), which gets the latest tile settings from the viewer and assigns them to renderGrid. It also updates the memory message bar and changes the hourglass cursor to the default cursor.

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