Skip to content Skip to navigation Skip to collection information

OpenStax_CNX

You are here: Home » Content » Object-Oriented Programming (OOP) with Java » Java OOP: Opening an Image File in a PictureExplorer Object

Navigation

Table of Contents

Recently Viewed

This feature requires Javascript to be enabled.
 

Java OOP: Opening an Image File in a PictureExplorer Object

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

Summary: Learn how to open an image file specified by a string in a text field in a PictureExplorer object.

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

This program demonstrates how to specify an image file in a text field, and open the image in a new PictureExplorer object.

Program output at startup

Figure 1 shows the program output at startup.

Figure 1: Program output at startup.
Program output at startup.
Missing image.

Pre-loaded image file name

For convenience, the text field is pre-loaded with the name of an image file that is located in the current directory.

Press Enter to load the image

Pressing the Enter key while the text field has the focus will cause the image to be loaded into a PictureExplorer object, and will cause the PictureExplorer object to be displayed as shown in Figure 2 .

Figure 2: Screen shot after the image is loaded.
Screen shot after the image is loaded.
Missing image.

Control panel is relocated

Note in Figure 2 that the control panel containing the text field has been automatically relocated to a position immediately below the PictureExplorer object.

Another image file in the current directory

Entering the path and name of any jpeg file will cause that file to be loaded into a new PictureExplorer object.

Complete program listing

A complete listing of the program discussed in this lecture is shown in Listing 1 below.

Listing 1: Complete program listing.

/*File Prob11 Copyright 2012 R.G.Baldwin
The purpose of this program is to demonstrate the use of
a JTextField object to specify the name of an image file,
which is then loaded and displayed in a PictureExplorer
object.

The text field is pre-loaded with the name of an image
file that is in the current directory (Prob11a.jpg).

An image file named Prob11b.jpg is also in the current
directory and can be loaded and displayed by entering
the name in the text field.

Any image file on the disk can be loaded and displayed
by entering the path and name of the image file.
*********************************************************/

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.WindowConstants;

public class Prob11{
  public static void main(String[] args){
    new Prob11Runner();
  }//end main method
}//end class Prob11
//======================================================//

class Prob11Runner extends JFrame{
  private Prob11Runner jFrameObj = null;
  private PictureExplorer explorer = null;
  private Picture pix;

  private JPanel fileNamePanel = new JPanel();
  private JTextField inputFileNameField =
                         new JTextField("Prob11a.jpg",20);

  private String fileName = "no file specified";
  //----------------------------------------------------//

  public Prob11Runner(){//constructor
    fileNamePanel.add(new JLabel("File name: "));
    fileNamePanel.add(inputFileNameField);

    //Add the fileNamePanel to the content pane, adjust
    // to the correct size, and set the title.
    getContentPane().add(fileNamePanel);
    pack();
    setTitle("Dick Baldwin");

    //Make the GUI visible, set the focus, and establish
    // a reference to the GUI object.
    setVisible(true);
    inputFileNameField.requestFocus();
    jFrameObj = this;

    //--------------------------------------------------//
    //Register listeners on the user input field.
    //--------------------------------------------------//

    inputFileNameField.addActionListener(
      new ActionListener(){
        public void actionPerformed(ActionEvent e){
          fileName = inputFileNameField.getText();

          pix = new Picture(fileName);
          pix.addMessage("Dick Baldwin",10,20);
          explorer = new PictureExplorer(pix);

          //Set the location for the control GUI
          // immediately below the PictureExplorer object,
          // and set its default close operation.
          setLocation(0,pix.getHeight() + 128);
          jFrameObj.setDefaultCloseOperation(
                           WindowConstants.EXIT_ON_CLOSE);
        }//end action performed
      }//end newActionListener
    );//end addActionListener
    //--------------------------------------------------//
  }//end constructor
  //----------------------------------------------------//
}//end class Prob11Runner

Will explain the code in fragments

As usual, I will break the code down, and explain it in fragments.

The driver class

The driver class is shown in Listing 2 .

There is nothing new in Listing 2 .

Listing 2: The driver class.

public class Prob11{
  public static void main(String[] args){
    new Prob11Runner();
  }//end main method
}//end class Prob11

Beginning of the Prob11Runner class

The Prob11Runner class begins in Listing 3 .

Listing 3 declares several instance variables that will be used later in the program, initializing some of them.

Note that the class extends JFrame , so an object of the class "is a" JFrame object.

Listing 3: Beginning of the Prob11Runner class.

class Prob11Runner extends JFrame{
  private Prob11Runner jFrameObj = null;
  private PictureExplorer explorer = null;
  private Picture pix;

  private JPanel fileNamePanel = new JPanel();
  private JTextField inputFileNameField =
               new JTextField("Prob11a.jpg",20);

  private String fileName = "no file specified";


Beginning of the constructor

The constructor for the Prob11Runner class begins in Listing 4 .

The code in Listing 4 performs the physical construction of the GUI show in Figure 1 .

The code in Listing 4 saves a reference to the object so that it can be accessed later from within a listener object.

Listing 4: Beginning of the constructor.

  public Prob11Runner(){//constructor
    fileNamePanel.add(new JLabel("File name: "));
    fileNamePanel.add(inputFileNameField);

    //Add the fileNamePanel to the content pane, adjust
    // to the correct size, and set the title.
    getContentPane().add(fileNamePanel);
    pack();
    setTitle("Dick Baldwin");

    //Make the GUI visible, set the focus, and establish
    // a reference to the GUI object.
    setVisible(true);
    inputFileNameField.requestFocus();
    jFrameObj = this;

Register a listener on the text field

Listing 5 shows the beginning of code that instantiates an ActionListener object of an anonymous listener class, and registers the listener object on the text field shown in Figure 1 .

Listing 5: Beginning of anonymous listener class.

    inputFileNameField.addActionListener(
      new ActionListener(){
        public void actionPerformed(ActionEvent e){
          fileName = inputFileNameField.getText();

          pix = new Picture(fileName);
          pix.addMessage("Dick Baldwin",10,20);

          explorer = new PictureExplorer(pix);


Get image and create Picture object

Listing 5 begins by getting the name of the image file from the text field, using that image file to create a new Picture object, and adding a name in the upper-left corner of the picture.

Create new PictureExplorer object

Then Listing 5 instantiates a new PictureExplorer object that encapsulates the Picture object that was created from the image file.

Completion of the anonymous listener class

Listing 6 shows the completion of the anonymous listener class, as well as the end of the constructor, and the end of the class named Prob11Runner .

Listing 6: Completion of the anonymous listener class.

          setLocation(0,pix.getHeight() + 128);
          
          jFrameObj.setDefaultCloseOperation(
                           WindowConstants.EXIT_ON_CLOSE);
        }//end action performed
      }//end newActionListener
    );//end addActionListener
    //--------------------------------------------------//
  }//end constructor
  //----------------------------------------------------//
}//end class Prob11Runner

Relocate the GUI

Listing 6 begins by setting the location of the GUI to a location that is immediately below the PictureExplorer object.

Relocate the GUI (cont'd)

Note that the value of 128 pixels was experimentally determined to be the approximate difference between the height of the PictureExplorer object and the height of the Picture object that it encapsulates.

(This difference may not be correct for different display options on different operating systems.)

Set the default close operation

Listing 6 ends by setting the behavior of the X-button in the GUI to a value that will cause it to terminate the program when the button is clicked.

Run the program

I encourage you to copy the code from Listing 1 and download the image file named Prob11a.jpg . 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.

What's next?

In the next module, you will learn how to extract color data from a selected pixel in a PictureExplorer object, and how to display a color value in a text field. You will also learn how to disable the X-button in the PictureExplorer object, and how to use a reference to the JFrame object that serves as a container for the PictureExplorer object.

Miscellaneous

This section contains a variety of miscellaneous information.

Note:

Housekeeping material
  • Module name: Java OOP: Opening an Image File in a PictureExplorer Object
  • File: Java3122.htm
  • Published: 09/08/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.

-end-

Collection Navigation

Content actions

Download:

Collection as:

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

Module as:

PDF | More downloads ...

Add:

Collection 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

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