Skip to content Skip to navigation

OpenStax_CNX

You are here: Home » Content » Java OOP: Controlling an Image-Scaling Program with a Slider

Navigation

Recently Viewed

This feature requires Javascript to be enabled.
 

Java OOP: Controlling an Image-Scaling Program with a Slider

Module by: R.G. (Dick) Baldwin. E-mail the author

Summary: Learn how to use a slider to continuously change the size of an image and to draw the scaled image onto a background image.

Preface

This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP) using Java.

The program described in this module requires the use of the Guzdial-Ericson multimedia class library. You will find download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson Multimedia Class Library .

Viewing tip

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.

Figures

Listings

Preview

The primary objective of this module is to illustrate how to use a slider to continuously change the size of an image and to draw the scaled image onto a background image.

Brief program specifications

Write a program named Prob09 that uses the class definition for the class named Prob09 shown in Listing 3 and Ericson's media library along with the image files named Prob09a.jpg (see Figure 1 ) and Prob09b.jpg (see Figure 2 ) to produce the graphic output images shown in Figure 3 .

Figure 1: Prob09a.jpg.
Prob09a.jpg.
Missing image.
Figure 2: Prob09b.jpg.
Prob09b.jpg.
Missing image.
Figure 3: Output images.
Output images.
Missing image.

General background information

The overall structure of this program is very similar to a program that I explained in an earlier module titled Controlling an Edge Detector with a Slider . The only significant difference between the two programs is the code that is executed when the slider fires a ChangeEvent .

I will explain the code that is new and different in this program and refer you back to the earlier module for an explanation of the remainder of the code. You can view the entire program in Listing 3 near the end of the module.

Discussion and sample code

Register a listener object on the slider

The code in Listing 1 registers an anonymous listener object on the slider.

Listing 1: Register a listener object on the slider.

    slider.addChangeListener(
      new ChangeListener(){
        public void stateChanged(ChangeEvent e){

          //Restore the background image of the butterfly.
          graphics = display.getGraphics();
          graphics.drawImage(
                          butterfly.getImage(),0,0,null);

          drawScaledPictureOnPicture(beach,
                                     display,
                                     slider.getValue());
          display.repaint();
        }//end stateChanged
      }//end new ChangeListener
    );//end addChangeListener

Each time the slider fires a ChangeEvent , the method named stateChanged is executed.

Behavior of the stateChanged method

The stateChanged method restores the background image of the butterfly. Then it calls the method named drawScaledPictureOnPicture to draw a scaled version of the beach on top of the background image using the slider value as the scale factor.

The slider value ranges from 0 to 100. This represents a scale factor as a percent of 1.0. In other words, the beach image is never scaled to a size that is larger than the size of the original beach image.

The image of the beach is always aligned with the center of the contentPane of the JFrame .

When the drawScaledPictureOnPicture method returns, the repaint method is called to cause the new image to be rendered on the computer screen.

The method named drawScaledPictureOnPicture

The method named drawScaledPictureOnPicture is shown in its entirety in Listing 2 .

Listing 2: The method named drawScaledPictureOnPicture.

  private void drawScaledPictureOnPicture(
                                      Picture source,
                                      Picture dest,
                                      double scaleFactor){

    transform = new AffineTransform();

    double translateX = dest.getWidth()/2
                    - source.getWidth()*scaleFactor/100/2;
    double translateY = dest.getHeight()/2
                  - source.getHeight()*scaleFactor/100/2;;
    transform.translate(translateX,translateY);
    transform.scale(scaleFactor/100.0,scaleFactor/100.0);
    
    //Get the Graphics2D object used to draw on the
    // destination picture.
    g2 = (Graphics2D)dest.getGraphics();

    //Scale and draw the source image on the destination
    // image.
    g2.drawImage(source.getImage(),transform,null);

  }//end drawScaledPictureOnPicture method

Use an affine transform

This method uses an affine transform to first translate and then scale the source picture and draws the scaled source picture onto the center of the destination picture.

I have published numerous tutorials that explain the use of Affine transforms in Java, including Applying Affine Transforms to Picture Objects . I won't repeat those explanations in this module, but will simply refer you to the earlier tutorials.

Keywords for a Google search

You can find my other tutorials that explain Affine transforms by using Google to search for the following keywords:

null

Run the program

I encourage you to copy the code from Listing 3 . Compile the code and execute it. Experiment with the code, making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do.

Summary

In this module, you learned how to use a slider to continuously change the size of an image and to draw the scaled image onto a background image.

What's next?

In the next module, you will learn how to use a JSlider object along with Affine Transforms to control the rotation of an image.

Miscellaneous

This section contains a variety of miscellaneous information.

Note:

Housekeeping material
  • Module name: Java OOP: Controlling an Image-Scaling Program with a Slider
  • File: Java3118.htm
  • Published: 05/13/12
  • Revised: 09/07/12

Note:

Disclaimers:

Financial : Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF.

I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.

In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it was made and published without my prior knowledge.

Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.

Complete program listing

A complete listing of the program discussed in this module is shown in Listing 3 below.

Listing 3: Complete program listing.

/*File Prob09 Copyright 2008 R.G.Baldwin
Revised 09/13/10

*********************************************************/
import java.awt.geom.AffineTransform;
import java.awt.Graphics2D;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JLabel;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

public class Prob09{
  //DO NOT MODIFY THE CODE IN THIS CLASS DEFINITION.
  public static void main(String[] args){
    new Prob09Runner();
  }//end main method
}//end class Prob09
//End program specifications.
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////

/*------------------------------------------------------//

*********************************************************/
class Prob09Runner extends JFrame{

  private JPanel mainPanel = new JPanel();
  private JPanel titlePanel = new JPanel();
  private JSlider slider = new JSlider(0,100,0);

  private Picture beach = new Picture("Prob09a.jpg");
  private Picture butterfly = new Picture("Prob09b.jpg");

  private int beachWidth = beach.getWidth();
  private int beachHeight = beach.getHeight();

  private Picture display =
            new Picture(beachWidth,beachHeight);

  private Image image = null;
  private Graphics graphics = null;
  private AffineTransform transform = null;
  private Graphics2D g2 = null;

  public Prob09Runner(){//constructor

    System.out.println("Dick Baldwin");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    beach.addMessage("Dick Baldwin",10,20);
    butterfly.addMessage("Dick Baldwin",10,20);

    slider.setMajorTickSpacing(10);
    slider.setMinorTickSpacing(5);
    slider.setPaintTicks(true);
    slider.setPaintLabels(true);

    mainPanel.setLayout(new BorderLayout());
    titlePanel.add(new JLabel(
                          "Percent Size of Beach Image"));
    mainPanel.add(titlePanel,BorderLayout.NORTH);
    mainPanel.add(slider,BorderLayout.CENTER);

    getContentPane().add(mainPanel);
    //pack();
    setSize(beachWidth + 7,97);
    setTitle("Dick Baldwin");
    setLocation(0,beachHeight + 25);
    setVisible(true);

    //Draw and display the background image of the
    // butterfly.
    graphics = display.getGraphics();
    graphics.drawImage(butterfly.getImage(),0,0,null);

    display.show();
    //--------------------------------------------------//
    //Register an anonymous listener object on the slider.
    //Each time the slider fires a ChangeEvent, this event
    // handler restores the background image of the
    // butterfly. Then it draws a scaled version of the
    // beach on top of the background image using the
    // slider value, which ranges from 0 to 100 as the
    // scale factor as a percent of 1.0. The image of the
    // beach is always aligned with the center
    // of the contentPane of the JFrame.
    slider.addChangeListener(
      new ChangeListener(){
        public void stateChanged(ChangeEvent e){

          //Restore the background image of the butterfly.
          graphics = display.getGraphics();
          graphics.drawImage(
                          butterfly.getImage(),0,0,null);

          drawScaledPictureOnPicture(beach,
                                     display,
                                     slider.getValue());
          display.repaint();
        }//end stateChanged
      }//end new ChangeListener
    );//end addChangeListener
    //--------------------------------------------------//
  }//end constructor
  //----------------------------------------------------//

  //Scales and draws the source picture onto the center
  // of the destination picture.
  private void drawScaledPictureOnPicture(
                                      Picture source,
                                      Picture dest,
                                      double scaleFactor){

    transform = new AffineTransform();

    double translateX = dest.getWidth()/2
                    - source.getWidth()*scaleFactor/100/2;
    double translateY = dest.getHeight()/2
                  - source.getHeight()*scaleFactor/100/2;;
    transform.translate(translateX,translateY);
    transform.scale(scaleFactor/100.0,scaleFactor/100.0);
    
    //Get the Graphics2D object used to draw on the
    // destination picture.
    g2 = (Graphics2D)dest.getGraphics();

    //Scale and draw the source image on the destination
    // image.
    g2.drawImage(source.getImage(),transform,null);

  }//end drawScaledPictureOnPicture method
}//end class Prob09Runner

-end-

Content actions

Download module as:

PDF | EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Add module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks