.
.
Java Technology Fundamentals Newsletter header
    January 28, 2004    

In this Issue

 

Welcome to the Java Developer Connection Java Technology Fundamentals Newsletter.

This monthly newsletter provides a way for you to learn the basics of the Java programming language, discover new resources, and keep up-to-date on the latest additions to the JDC's New to Java Programming Center.

image Java Programming Language Basics: Image Handling Basics
image Java Bits: JDBC API FAQ
image Making Sense of Java Classes: EditorKit and JEditorPane
image Program Challenge: Drag Image
image Sun's Online Courses
image Sun Tech Days, A Developer Conference!
image For More Information: Read articles, Tech Tips, trails, and tutorials that provide more information on the topics discussed here.

.

Java Programming Language Basics

Image Handling Basics

When doing animation, you will find that the Image class of the java.awt package serves as the base. The class represents an internal structure that stores a bitmapped object. Support is built into the core libraries for working with JPEG, GIF, and even PNG formatted images. For additional image support, see the Java Advanced Imaging (JAI) API.

The core support for working with images is found in just two methods. First, you need to load Image through the getImage() method of Toolkit, and the then you can display that image through the drawImage() method of Graphics.

It sounds simple, but the task is a little more involved behind the scenes than how things might first appear.

First, look at the two getImage() methods:

public Image getImage(String filename)
public Image getImage(URL url)

To load an image in an application, pass the filename or URL to the getImage() method, which returns a reference to an Image object that is loaded later. The method returns immediately, but the image loading doesn't start yet. That's really all there is to loading images in applications.

Image loading in applets is a little different. Instead of using the methods from Toolkit, the Applet class provides its own set of image loading methods:

Image getImage(URL url)
Image getImage(URL baseUrl, String name)

Because applet security policies restrict an untrusted applet from communicating with any host besides the one from which the applet came, use the second version of getImage(). Then, instead of hard coding the base URL into your program the base URL for where you plan on running the applet, you can use the applet's getDocumentBase() or getCodeBase() methods as the base URL.

The two methods, getDocumentBase() and getCodeBase(), report slightly different information about the applet. If you want to load images relative to where the browser loaded the HTML file used to load the applet, use the getDocumentBase() method. If, however, you want to load the images relative to where the browser loaded the applet's class files, then you use getCodeBase().

For instance, while the following two lines might appear to load image files the same, where they look for the designated image file depends upon what the <APPLET> tag looks like in the HTML loader.

Image image1 = getImage(getDocumentBase(), "images/dog.jpg");
Image image2 = getImage(getCodeBase(), "images/dog.jpg");

If you were to specify a CODEBASE attribute for the applet, then the first appears relative to where the HTML file is located, and the second checks where the CODEBASE attribute specified.

Moving beyond loading to drawing brings up the drawImage() method. There are actually six different ways to draw an image. Of these six, you should only use the first two. The optional Color argument in the second version is the background when pixels of an image are transparent.

public boolean drawImage(Image image, int x, int y,
    ImageObserver observer)

public boolean drawImage(Image image, int x, int y, Color
    bgcolor, ImageObserver observer)

public boolean drawImage(Image image, int x, int y, int width,
    int height, Color bgcolor, ImageObserver observer)
.           
public boolean drawImage(Image image, int x, int y, int width,
    int height, ImageObserver observer)
.           
public boolean drawImage(Image image, int dx1, int dy1, int
   dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor,
   ImageObserver observer)

public boolean drawImage(Image image, int dx1, int dy1, int
   dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver
   observer)

The way to draw an image is to pass the Image object returned from getImage() to drawImage() along with the top-left corner of where to draw the image. The ImageObserver argument then adds a bit of complexity to the mix. Image loading isn't triggered until something needs to observe the image. That "thing" is the ImageObserver. Then, as the image is continuously loaded, the observer is periodically notified. However, you don't do any calling of the ImageObserver methods yourself and you don't have to implement the interface yourself. The AWT Component class (and all of its subclasses, including the Swing components) implements the interface for you. As long as you are drawing the image in a subclass of component, like a JFrame, all you have to do is pass "this" as the last argument.

public void paint(Graphics g) {
...
   g.drawImage(image, x, y, this);
...
}

Looking at loading, drawing, and the ImageObserver a little more closely should make the convoluted pieces clearer.

  • Initiate the loading of an image with getImage(). That's the easy part.

  • Draw the image with drawImage(), usually within the paint() method of a Component. Since the image hasn't been loaded yet, the call to drawImage() starts the loading of the image.

  • Internally, loading starts and registers the ImageObserver with the image loading thread.

  • As image data is loaded, the image loading thread periodically notifies the ImageObserver.

  • The default ImageObserver implementation is notified, causing the drawing of the additional Image data.

  • Until the image is fully loaded, the previous two steps repeat. This sounds overly complicated, but you, as the developer, only need to call drawImage(). The remaining work happens behind the scenes. To demonstrate, here's a simple example that just loads an image and draws it.
import java.awt.*;
import javax.swing.*;

public class LoadDraw extends JFrame {

   Image image;

   public LoadDraw(String filename) {
     super(filename);
     setDefaultCloseOperation(EXIT_ON_CLOSE);
     image = getToolkit().getImage(filename);
   }

   public void paint(Graphics g) {
     super.paint(g);
     g.drawImage(image, 25, 25, this);
   }

   public static void main(String args[]) {
     if (args.length > 0) {
       JFrame f = new LoadDraw(args[0]);
       f.setSize(300, 300);
       f.show();
     } else {
       System.err.println(
        "You must specify an image filename to display");
     }
   }
}
.
.

Java Bits

JDBC API FAQ

Learn what JDBC is, how to debug problems with the JDBC API, how to use JDBC to access a desktop database like Microsoft Access over a network, how to retrieve a whole row of data at once, what kinds of documentation are available, and more in this JDBC API FAQ.

» More

.
.

Making Sense of the Java Class

EditorKit and JEditorPane

Swing editor panes are used to edit or display content, such as HTML and RTF files, and so forth. To edit this content in the pane, an EditorKit is used to get the editing resources.

The JEditorPane component uses implementations of the EditorKit to accomplish its behavior. It effectively morphs into the proper kind of text editor for the kind of content it is given. The content type that editor is bound to at any given time is determined by the EditorKit currently installed. If the content is set to a new URL, its type is used to determine the EditorKit that should be used to load the content.

There are several ways to load content into this component.

  • The setText method initializes the component from a string. In this case the current EditorKit is used, and the content type is expected to be of this type.

  • The read method initializes the component from a Reader. Note that if the content type is HTML, relative references (for objects like images) can't be resolved unless the <base> tag is used or the Base property on HTMLDocument is set. In this case the current EditorKit is used, and the content type is expected to be of this type.

  • The setPage method can be used to initialize the component from a URL. In this case, the content type is determined from the URL, and the registered EditorKit for that content type is set.

The JEditorPane class provides constructors that let you initialize an editor pane from a URL. You can also initialize a JEditorPane object then load a page with text from a URL using the setPage method.

  • JEditorPane() -- Creates a new JEditorPane.

  • JEditorPane(String type, String text) -- Creates a JEditorPane that has been initialized to the given text.

  • JEditorPane(URL initialPage) -- Creates a JEditorPane based on a specified URL for input.

To make the links functional, you'd need to create a HyperlinkListener object that is generated when the user clicks a link inside of the contents of the JEditorPane object:

HyperlinkListener listener = new HyperlinkListener() {
  public void hyperlinkUpdate(HyperlinkEvent e)
    if (e.getEventType() == HyperlinkEvent.EventTrype.ACTIVATED) {
     try {
        ep.setPage(e.getURL());
        } catch (IOException ioe) {
           System.err.println("Error loading: " + ioe);
           }
        }
      }
     };

In addition, make sure that the JEditor pane is set to editable:

jep.setEditable(false);

Lastly, register the JEditorPane object with a listener:

ep.addHyperlinkListener(listener);
.
.

Program Challenge

Drag Image

Create a program that loads an image and moves that image around the window as you drag the mouse around within the frame.

For the example, loading happens on mouse click, but you could have a menu or a button to present the JFileChooser.

See a possible solution to the Challenge.

.
.

Sun's Online Courses

Beginning to Program With the Java Programming Language

The Beginning to Program With the Java Programming Language course is designed for students with little or no programming experience who want to learn to program using the Java programming language. This course takes an in-depth look at two of the fundamental concepts of every Java program: Variables and datatypes.

» More

.
.

Sun Tech Days, A Developer Conference!

  • February 17-18, 2004: London, UK
  • March 9-10, 2004: Beijing, China
  • March 16-17, 2004: Mexico City, Mexico

Packed with information on developer tools and technologies, Sun Tech Days brings high-end innovation and solutions. Register and view a current list of cities and dates.

.
.

For More Information

.
.

Downloading the Java 2 Platform

For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the J2SE development kit.

.
.
.

Reader Feedback

  Very worth reading    Worth reading    Not worth reading 

If you have other comments or ideas for future newsletters, please type them here:

 

Have a question about Java programming? Use Java Online Support.

.
.

Subscribe to the following newsletters for the latest information about technologies and products in other Java platforms:

- Core Java Technologies Newsletter. Learn about new products, tools, resources, and events of interest to developers working with core Java technologies.
- Wireless Developer Newsletter. Learn about the latest releases, tools, and resources for developers working on wireless and Java Card technologies and applications.
- Core Java Technologies Tech Tips (formerly JDC Tech Tips) Get expert tips, sample code solutions, and techniques for developing in the Java 2 Platform, Standard Edition (J2SE)
You can subscribe to these and other JDC publications on the JDC Newsletters and Publications page

IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html


Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: dana.nourie@sun.com

Go to the subscriptions page to subscribe or unsubscribe to this newsletter.

ARCHIVES: You'll find the Java Technology Fundamentals Newsletter archives at:
http://developer.java.sun.com/developer/onlineTraining/new2java/supplements/


Copyright 2004 Sun Microsystems, Inc. All rights reserved. 4150 Network Circle, Santa Clara, CA 95054

Trademark Information: http://www.sun.com/suntrademarks/
Java, J2EE, J2SE, J2ME, and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.


Sun 
Microsystems, Inc.
image
image