Tech all over the world
Saturday, April 15, 2006
  Core Java Technologies Tech Tips, April 15, 2006 (Indexed Property Changes, Java 2D API Enhancements)
You are receiving this e-mail because you elected to receive e-mail from Sun Microsystems, Inc. To update your communications preferences, please see the link at the bottom of this message. We respect your privacy and post our privacy policy prominently on our Web site http://sun.com/privacy/

Please do not reply to the mailed version of the newsletter, this alias is not monitored. Feedback options are listed in the footer for both content and delivery issues.
  Welcome to the Core Java Technologies Tech Tips.
Core Java Technologies
TECHNICAL TIPS
April 15, 2006
View this issue as simple text
In This Issue
 
Welcome to the Core Java Technologies Tech Tips for April 15, 2006. Here you'll get tips on using core Java technologies and APIs, such as those in Java 2 Platform, Standard Edition (J2SE).

This issue covers:

» Reporting Indexed Property Changes in Beans
» Java 2D API Enhancements in J2SE 5.0

These tips were developed using Java 2 Platform, Standard Edition Development Kit 5.0 (JDK 5.0). You can download JDK 5.0 at http://java.sun.com/j2se/1.5.0/download.jsp.

This issue of the Core Java Technologies Tech Tips is written by John Zukowski, president of JZ Ventures, Inc. (http://www.jzventures.com).

See the Subscribe/Unsubscribe note at the end of this newsletter to subscribe to Tech Tips that focus on technologies and products in other Java platforms.

REPORTING INDEXED PROPERTY CHANGES IN BEANS
 

In J2SE 5.0, a number of features were added to the JavaBeans component API. One of these was support for IndexedPropertyChangeEvent. The JavaBeans component API provided a way to report changes to a regular property of a JavaBeans component (also called a JavaBean or just a "bean"). The support for IndexedPropertyChangeEvent added the ability to report additional information about changes to an indexed property of a bean.

Most people are familiar with JavaBean component properties. Simply add set and get methods to your class and you have a read-write property defined by whatever the name is after set and get. In other words, if your class has methods named setName() and getName(), your class has a JavaBean component property named name.

There are two types of component properties: regular and indexed. Indexed properties are distinguished from regular properties in that they have multiple values, where each value is accessed by an index. The set and get methods for a regular property such as name would look like this:

Regular property:
  • public void setName(String name)
  • public String getName()
If name is an indexed property, the methods look like this:

Indexed property:
  • public void setName(int index, String name)
  • public String getName(int index)
  • public void setName(String[] names)
  • public String[] getName()
Beans can be designed to notify you of their property changes. You can register a PropertyChangeListener object with the bean through the addPropertyChangeListener() method. The listener is then notified of changes through PropertyChangeEvent objects or IndexedPropertyChangeEvent objects. A property that generates a PropertyChangeEvent when its value changes is called a bound property.

The PropertyChangeListener class has one method:
    public void propertyChange(PropertyChangeEvent pce) 
If the argument to propertyChange() is of type PropertyChangeEvent, how do you get notified with an IndexedPropertyChangeEvent? The answer derives from the fact that the IndexedPropertyChangeEvent class is a subclass of PropertyChangeEvent. So, inside your propertyChange() you need an instanceof check to see what type of argument you get:

    public void propertyChange(PropertyChangeEvent pce) {      String name = pce.getPropertyName();      if (pce instanceof IndexedPropertyChangeEvent) {        IndexedPropertyChangeEvent ipce =          (IndexedPropertyChangeEvent) pce;        int index = ipce.getIndex();        System.out.println("Property: " + name + "; index: "         + index);      } else {        System.out.println("Property: " + name);      }      System.out.println("; value: " + pce.getNewValue());    } 
Before viewing an example program that uses IndexedPropertyChangeEvent, let's focus on how to report a change to a bound indexed property. The following code reports the update of the name indexed property shown previously:

    private PropertyChangeSupport changeSupport;     public ClassConstructor() {      changeSupport = new PropertyChangeSupport(this);    }     public void setName(int index, String name) {      String oldName = this.name;      this.name = name;      changeSupport.fireIndexedPropertyChange("name", index,        oldName, name);    } 
The PropertyChangeSupport class is a support class found in the java.beans package (the package for the JavaBeans component API). The fireIndexedPropertyChange() method reports a change to the bound indexed property (in this case, name) to any listeners that were registered through the addPropertyChangeListener() method.

Here's what the full example looks like:
    import java.beans.*;    import java.util.*;        public class IndexedSampleBean {          private PropertyChangeSupport changeSupport;          private Map<Integer, String> names;          private String title;          public IndexedSampleBean() {        changeSupport = new PropertyChangeSupport(this);        names = new HashMap<Integer, String>();      }          public void setTitle(String title) {        String oldTitle = this.title;        this.title = title;        changeSupport.firePropertyChange("title", oldTitle, title);      }          public String getTitle() {        return title;      }          public void setName(int index, String name) {          String oldName = names.get(index);          names.put(index, name);          changeSupport.fireIndexedPropertyChange("name", index,                    oldName, name);      }          public String getName(int index) {        return names.get(index);      }          public void addPropertyChangeListener(       PropertyChangeListener l) {          changeSupport.addPropertyChangeListener(l);      }       public void removePropertyChangeListener(       PropertyChangeListener l) {          changeSupport.removePropertyChangeListener(l);      }          public static void main(String[] args) throws Exception {        IndexedSampleBean bean = new IndexedSampleBean();        PropertyChangeListener listener =           new PropertyChangeListener() {            public void propertyChange(PropertyChangeEvent pce) {              String name = pce.getPropertyName();              if (pce instanceof IndexedPropertyChangeEvent) {                IndexedPropertyChangeEvent ipce =                  (IndexedPropertyChangeEvent) pce;                int index = ipce.getIndex();                System.out.print("Property: " + name +                  "; index: " + index);              } else {                System.out.print("Property: " + name);              }              System.out.println("; value: " + pce.getNewValue());            }        };        bean.addPropertyChangeListener(listener);        bean.setName(1, "John");        bean.setName(2, "Ed");        bean.setName(3, "Mary");        bean.setName(4, "Joan");        bean.setTitle("Captain");        System.out.println("Name at 3 is: " + bean.getName(3));        System.out.println("Title is: " + bean.getTitle());      }    } 
The class defines an indexed property named name and sets the name at four positions. In addition, a regular bound property named title is also present and set. The listener is notified for each call to set the name or title and then print the property name, index (if appropriate), and value. The class then gets the name at one specific position and prints it, before printing the single title.

Running the program produces the following results:
  >java IndexedSample      Property: name index: 1 value: John     Property: name index: 2 value: Ed     Property: name index: 3 value: Mary     Property: name index: 4 value: Joan     Property: title; value: Captain     Name at 3 is: Mary     Title is: Captain 
For more information about the support for IndexedPropertyChangeEvent in the JavaBeans component API, see API Enhancements to the JavaBeans Component API in J2SE 5.0. Also see the JavaBeans Trail in the Java Tutorial.

Back to Top

JAVA 2D API ENHANCEMENTS IN J2SE 5.0
 

Each new release of the standard edition of the Java platform brings both big and small improvements. Most people hear about all the big new features such as Generics or the new concurrency utilities package. What people don't always hear about are the small new features. These features are rarely mentioned because they are useful to a smaller audience than some of the bigger features. This tip describes several of these small enhancements to the Java 2D API added in J2SE 5.0. What actually happens when you use the new features often depends on your operating environment and your hardware. In some cases, using these features might provide very little (if any) benefit.

Bicubic Interpolation

One Java 2D API enhancement has to do with image scaling -- it also affects rotation and other affine transformations. The RenderingHints class has two constants that deal with different interpolation options: VALUE_INTERPOLATION_BILINEAR and VALUE_INTERPOLATION_BICUBIC. Setting the KEY_INTERPOLATION hint to one of the two options tells the underlying system what rules to follow when scaling an image. Prior to J2SE 5.0, the two hint values produced the same result. Because RenderingHints are simply hints, they could be ignored. In fact, the bicubic setting was always ignored, and instead, bilinear interpolation was used.

If you are unfamiliar with the two interpolation options, it helps to understand what happens when scaling up an image. For instance, where do all those new pixels in the scaled up image come from? With bilinear scaling, the pixels come from the 2x2 rectangle of pixels from the source image that are closest to the scaled pixel. The rectangle of pixels are blended using a linear function in both X and Y. With bicubic scaling, they come from the 4x4 area that surrounds the scaled pixel. The rectangle of pixels are blended using a cubic function in both X and Y. Because of the increased area and algorithmic complexity, bicubic scaling tends to create a better looking scaled image, but at the cost of performance.

In J2SE 5.0, the bicubic setting is honored. You can see this by running the following test program. When you run the program, specify an image file. The program sets the RenderingHints with the two constants, VALUE_INTERPOLATION_BILINEAR and VALUE_INTERPOLATION_BICUBIC, and reports interpolation algorithm differences (if any). First run the program with JDK 1.4 and then with JDK 5.0. You'll see that interpolation algorithm differences are reported only with the newer JDK.
    import java.awt.*;    import java.awt.image.*;    import java.io.*;    import javax.swing.*;    import javax.imageio.*;          public class Bicubic {      public static void main(String args[]) throws IOException {        if (args.length == 0) {          System.err.println(            "Provide image name on command line");          System.exit(-1);        }        Image image = ImageIO.read(new File(args[0]));        int w = image.getWidth(null);        int h = image.getHeight(null);        BufferedImage bilinear = new BufferedImage(2*w, 2*h,          BufferedImage.TYPE_INT_RGB);        BufferedImage bicubic = new BufferedImage(2*w, 2*h,          BufferedImage.TYPE_INT_RGB);               Graphics2D bg = bilinear.createGraphics();        bg.setRenderingHint(RenderingHints.KEY_INTERPOLATION,          RenderingHints.VALUE_INTERPOLATION_BILINEAR);        bg.scale(2, 2);        bg.drawImage(image, 0, 0, null);        bg.dispose();               bg = bicubic.createGraphics();        bg.setRenderingHint(RenderingHints.KEY_INTERPOLATION,         RenderingHints.VALUE_INTERPOLATION_BICUBIC);       bg.scale(2, 2);       bg.drawImage(image, 0, 0, null);       bg.dispose();              for(int i=0; i<2*w; i++)         for(int j=0; j<2*h; j++)           if (bilinear.getRGB(i, j) != bicubic.getRGB(i, j))             System.out.println("Interpolation algo differ");     }    }  
For the JDK 1.4 environment, there is no output from running the program:
    > java Bicubic image.jpg      [No Output] 
For the JDK 1.5 environment, every pixel that differs is reported.
    > java Bicubic image.jpg      Interpolation algo differ      Interpolation algo differ      Interpolation algo differ      Interpolation algo differ      Interpolation algo differ      .... repeated many times 
OpenGL Acceleration

The February 8, 2005 Tech Tip Introduction to JOGL described the Java programming language binding for the OpenGL 3D graphics API. In J2SE 5.0, there are some OpenGL options available to accelerate the core functionality of the 2D API. The options are "under the covers" -- they don't require the user to know how to program in OpenGL. By default, the acceleration option is disabled. To enable the option, set the sun.java2d.opengl system property to true. If you want verbose output sent about the OpenGL-based pipeline, use a value of True (uppercase T) instead of t. To see the results, use the Java 2D demo code that comes with the JDK.
    java -Dsun.java2d.opengl=True -jar Java2Demo.jar 
You can find out more about the OpenGL-based pipeline in Behind the Graphics2D: The OpenGL-based Pipeline.

Creating Fonts

Prior to J2SE 5.0, the Font class allowed you to create TrueType fonts from an InputStream through the createFont() method:
    public static Font createFont(int fontFormat,           InputStream fontStream) 
where fontFormat is Font.TRUETYPE_FONT. J2SE 5.0 makes two changes to this support. First, you can create Adobe Type 1 fonts. Second, you can create a font directly from a File object with the new createFont() method signature:
    public static Font createFont(int fontFormat,            File fontFile) 
If you simply want the fonts installed, that is, you don't want to create them with either method, you can copy the font files to the $JREHOME/lib/fonts directory. They will be automatically picked up by the runtime environment when installed in that directory.

Image Acceleration

The last set of new Java 2D features to explore relates to image acceleration. These features depend on underlying support in your system. If your system doesn't support these features, they are simply ignored.

The first image acceleration feature is buffered image caching. Video memory supports the caching of managed images. In general, programs that use the kind of images that can be managed tend to perform better that those that use unmanaged images. Prior to J2SE 5.0, only images created with the createImage() method of Component or with the createCompatibleImage() method of GraphicsConfiguration were managed by the Java 2D implementation. Now all images created with one of the BufferedImage constructors are managed by the Java 2D implementation.

Another new image acceleration feature is the ability to control the hardware acceleration of images. Note however that in J2SE 5.0, the methods used to control the hardware acceleration of images are not fully operational. See Methods for Controlling Hardware Acceleration of Images for more details.

The availability of this support depends on the platform and the type of image content. Also, on Microsoft Windows platforms, to see results, you sometimes need to set the sun.java2d.translaccel system property to true. See the description of translaccel in System Properties for Microsoft Windows Platforms for more information about the flag.

When creating Java programs, you can tell the underlying system that you want to optimize certain image operations. You do this by prioritizing how the system stores particular images in accelerated memory if possible. The key phrase here is "if possible." Prior to J2SE 5.0, you could request VolatileImage objects to be stored in accelerated memory. With J2SE 5.0, you can also request that regular Image objects be placed there. And you can create transparent VolatileImage objects. Previously, you could only create opaque ones.

The getCapabilities() method is now defined in both Image and VolatileImage -- not only in VolatileImage. This method can be used to discover if an image currently is accelerated. You can also specify the acceleration priority with the setAccelerationPriority() method, or identify its priority setting with the getAccelerationPriority() method. When its acceleration priority is zero, attempts to accelerate the specific image are disabled. The priority setting is just a hint though, and the JDK implementation can honor (or not honor) it as it sees fit.

To create transparent VolatileImage objects, use one of the two new createCompatibleVolatileImage() methods:
  • createCompatibleVolatileImage(     int width, int height, int transparency)
  • createCompatibleVolatileImage(     int width, int height, ImageCapabilities caps,      int transparency)
Summary

As the Java platform continues to grow, watch for all those little features that don't get as much attention as the bigger ones. Little things, such as Common Unix Printer System (CUPS) printer support for Solaris and Linux, get added with little fanfare. If you happen to have a CUPS printer, the new feature is important. Be sure to read the release notes to see if a new feature is something you've been waiting for. See also the description of new features and enhancements for J2SE 5.0.

Back to Top

Rate and Review
Tell us what you think of the content of this page.
Excellent   Good   Fair   Poor  
Comments:
If you would like a reply to your comment, please submit your email address:
Note: We may not respond to all submitted comments.
Comments? Send your feedback on the Tech Tips: http://developers.sun.com/contact/feedback.jsp?category=newslet

If you have your own Tech Tip that you would like to share with others, you're encouraged to post it in an appropriate Sun Developer Network forum.

Subscribe to the following newsletters for the latest information about technologies and products in other Java platforms:
  • Enterprise Java Technologies Tech Tips. Get tips on using enterprise Java technologies and APIs, such as those in the Java 2 Platform, Enterprise Edition (J2EE).
  • Wireless Developer Tech Tips. Get tips on using wireless Java technologies and APIs, such as those in the Java 2 Platform, Micro Edition (J2ME).
You can subscribe to these and other Java technology developer newsletters or manage your current newsletter subscriptions on the Sun Developer Network Subscriptions page

ARCHIVES: You'll find the Core Java Technologies Tech Tips archives at:
http://java.sun.com/developer/JDCTechTips/index.html

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

© 2006 Sun Microsystems, Inc. All Rights Reserved. For information on Sun's trademarks see: http://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. 10 Network Circle, MPK10-209 Menlo Park, CA 94025 US



Please unsubscribe me from this newsletter.


 
Comments: Post a Comment



<< Home
News, Articles, events from all over the world

My Photo
Name:
Location: India

Born on shraavana shudha chauthi of dundubhi naama samvaswara, Im kiran alias kini alias kiri bought up by loving parents. Being from agricultural family I have learnt plowing, carting but never learnt climbing trees. Now away from home I have lost touch with the agricultural skills.

ARCHIVES
January 2006 / February 2006 / March 2006 / April 2006 / May 2006 / June 2006 / July 2006 / August 2006 / September 2006 / October 2006 / November 2006 / December 2006 / April 2007 / May 2007 / June 2007 / July 2007 / August 2007 / September 2007 / October 2007 / November 2007 / December 2007 / January 2008 / February 2008 / March 2008 / April 2008 / May 2008 / June 2008 / July 2008 / August 2008 / September 2008 / October 2008 / November 2008 / December 2008 / January 2009 / February 2009 / March 2009 / April 2009 /


Powered by Blogger