You are receiving this e-mail {e-mail address} 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/
  Welcome to the Java Technology Fundamentals Newsletter.
Java Technology Fundamentals
NEWSLETTER
August 2005
 

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 Sun Developer Network's New to Java Center.

You can receive future issues of this newsletter in HTML or text:
http://developer.java.sun.com/subscription/

Note: For the code to compile in this issue of Fundamentals, you need to use the JDK 5.0 software.
http://java.sun.com/j2se/1.5.0/download.jsp

Contents
 
» Java Programming Language Basics: Transferring Data With XML
» Making Sense of the Java Classes & Tools: Using the System Class
» Java Bits: Chapter 1: Introduction to the Java Sound API
» Learning Java 2D, Part 1
» What's New on java.net: Interaction Happens: Thinking Graphically
» Live Virtual Course: Java Programming Language Workshop (VC-SL-285)
» Sun's Java Technology CD-ROM Courses: Java Programming Language (CDJ-275)
» Sun's Java Technology Web Courses: J2SE Internals and Troubleshooting (WJO-3250)
» Sun Java Technology Top Five Courses Promotion
» Books for Learning: NetBeans IDE Field Guide

» For More Information

Java Programming Language Basics
 
Transferring Data With XML


Everyone is using XML these days to share information over the Internet. It provides a platform-independent way to transfer data between computers and to specify configuration data for a system. Unlike HTML, which uses tags to describe the format of a web page, XML tags identify the data they contain. For instance, the following document, phonebook.xml, might describe someone's phone book:
<PHONEBOOK>
<PERSON>
  <NAME>George Bush</NAME>
  <EMAIL>president@example.com</EMAIL>
  <TELEPHONE>202-555-1212</TELEPHONE>
  <WEB>www.whitehouse.gov</WEB>
</PERSON>
<PERSON>
  <NAME>Joseph Cardinal Ratzinger</NAME>
  <EMAIL>pope@example.com</EMAIL>
  <TELEPHONE>39 (6) 55.55.12.12</TELEPHONE>
  <WEB>www.vatican.va</WEB>
</PERSON>
<PERSON>
  <NAME>Tony Blair</NAME>
  <EMAIL>pm@example.co.uk</EMAIL>
  <TELEPHONE>44-207-555-1212</TELEPHONE>
  <WEB>www.number-10.gov.uk</WEB>
</PERSON>
<PERSON>
  <NAME>Meg Whitman</NAME>
  <EMAIL>ebay@example.com</EMAIL>
  <TELEPHONE>408-555-1212</TELEPHONE>
  <WEB>www.ebay.com</WEB>
</PERSON>
</PHONEBOOK>
Here, the outermost tag of PHONEBOOK indicates we have a telephone book. Inside the phone book, you'll find a set of PERSON elements. And for each person, you'll find a name, email address, telephone number, and web site address.

Once you have an XML document, what can you do with it? That's where Java technology and the Java Platform, Standard Edition (Java SE, formerly known as J2SE) libraries come into play. Inside the standard libraries, you'll find support for transforming XML documents through XSLT and parsing XML documents through SAX or DOM.

XSLT stands for Extensible Style Language for Transformation. By creating a second document that describes the transformations you wish done, you can take the first document's content and create a third. The Java technology libraries come with an XSLT processor to do the transformation. Essentially, the same program can be used to make lots of different transformations. The only thing that needs to change is the XSL file that describes the transformations.

For instance, if you wanted to take the XML phone-book file and create an HTML table out of it, the transformation below would pull the name, email address, and web address out of the XML file, sort the results, and send the results to the console.

The following document, directory.xsl, describes just such a transformation. For each PERSON tag within a PHONEBOOK tag, grab the data from the NAME, TELEPHONE, and EMAIL tag.
  <?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="
 http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">

<html>
<head>
<title>Directory</title>
</head>
<body>

<table border="1">

<tr>
  <th>Name</th>
  <th>Telephone</th>
  <th>Email</th>
</tr>

<xsl:for-each select="PHONEBOOK/PERSON">
  <xsl:sort/>
  <tr>
    <td><xsl:value-of select="NAME"/></td>
    <td><xsl:value-of select="TELEPHONE"/></td>
    <td><xsl:value-of select="EMAIL"/></td>
  </tr>
</xsl:for-each>

</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Following is the program that does the transformation:
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;

public class Transform {

  public static void main(String args[]) {

    if (args.length != 2) {
      System.err.println("Usage: java Transform xmlfile stylesheet");
      System.exit(-1);
    }

    try {
      StreamSource source = new StreamSource(args[0]);
      StreamSource stylesource = new StreamSource(args[1]);

      TransformerFactory factory = TransformerFactory.newInstance();
      Transformer transformer = factory.newTransformer(stylesource);

      StreamResult result = new StreamResult(System.out);
      transformer.transform(source, result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
And here is the result:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; 
 charset=UTF-8">
<title>Directory</title>
</head>
<body>
<table border="1">
<tr>
<th>Name</th><th>Telephone</th><th>Email</th>
</tr>
<tr>
<td>George Bush</td><td>202-555-1212</td><td>president@example.com</td>
</tr>
<tr>
<td>Joseph Cardinal Ratzinger</td><td>39 (6) 55.55.12.12</td>
<td>pope@example.com</td>
</tr>
<tr>
<td>Tony Blair</td><td>44-207-555-1212</td><td>pm@example.co.uk</td>
</tr>
<tr>
<td>Meg Whitman</td><td>408-555-1212</td><td>ebay@example.com</td>
</tr>
</table>
</body>
</html>
If you want to do more with the XML document besides just transform it, that's where SAX and DOM come into play. With SAX, or Simple API for XML, you make one pass through the document and react to events, like when a tag begins or ends. With DOM, or Document Object Model, the entire XML document is read into memory and essentially stored in a treelike data model.

The SAX parser uses a callback mechanism that calls methods of the supplied DefaultHandler when a tag begins or ends. For instance, in the following program, whenever a NAME tag is found, the value is printed.
import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class NameLister {

  public static void main(String args[]) {


    if (args.length != 1) {
      System.err.println("Usage: java NameLister xmlfile");
      System.exit(-1);
    }

    try {

      SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser saxParser = factory.newSAXParser();

      DefaultHandler handler = new DefaultHandler() {
        boolean name = false;
        public void startElement(String uri, String localName,
                                 String qName, Attributes attributes)
            throws SAXException {
          if (qName.equalsIgnoreCase("NAME")) {
            name = true;
          }
        }
        public void characters(char ch[], int start, int length)
            throws SAXException {
          if (name) {
            System.out.println("Name: " 
                                + new String(ch, start, length));
            name = false;
          }
        }
      };

      saxParser.parse(args[0], handler);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Running the program with the command line
java NameLister phonebook.xml
will produce the following results:
  Name: George Bush
  Name: Joseph Cardinal Ratzinger
  Name: Tony Blair
  Name: Meg Whitman
The basic framework of starting off with DOM is the same. When working with DOM, though, instead of using the SAXParserFactory from the javax.xml.parsers factory, you get a DocumentBuilder from the DocumentBuilderFactory. After parsing the input file, you have a tree that you can do whatever you like with, including adding new nodes, rearranging existing nodes, and saving the results in a new XML file.

You can do much more with XML than is shown here. For more information, see http://java.sun.com/xml/.

Making Sense of the Java Classes & Tools
 
Using the System Class


Unlike with most other classes, you don't instantiate the System class to use it. To be more precise, you cannot instantiate the System class: It's a final class, and all of its constructors are private.

All of System's variables and methods are class variables and class methods -- they are declared static. For a complete discussion about class variables and class methods and how they differ from instance variables and instance methods, refer to Understanding Instance and Class Members (in the Essential Java Classes trail) in the Objects, Classes, and Interfaces lesson. See for More Information below.

To use a class variable, you use it directly from the name of the class using Java's dot (.) notation. For example, to reference the System's class variable out, you append the variable name to the class name separated by a period, like this:

System.out
You call class methods in a similar fashion. For example, to call System's getProperty method, you append the method name to the end of the class name, separated by a period:
System.getProperty(argument);
The following small Java technology program uses the System class twice, first to retrieve the current user's name and then to display it:
class UserNameTest {
    public static void main(String[] args) {
        String name;
        name = System.getProperty("user.name");
        System.out.println(name);
    }
}
You'll notice that the program never instantiates a System object. It just references the getProperty method and the out variable directly from the class.

The code sample uses System's getProperty method to search the properties database for the property called user.name. System Properties later in this lesson talks more about system properties and the getProperty method.

The code sample also uses System.out, a PrintStream that implements the standard output stream. The println method prints its argument to the standard output stream. The next page of this lesson discusses the standard output stream and the other two standard I/O streams provided by the System class.

Read more

Java Bits
 
Chapter 1: Introduction to the Java Sound API


The Java Sound API is a low-level API for effecting and controlling the input and output of sound media, including both audio and Musical Instrument Digital Interface (MIDI) data. The Java Sound API provides explicit control over the capabilities normally required for sound input and output, in a framework that promotes extensibility and flexibility.

Who Is the Java Sound API For?

Because sound is so fundamental, the Java Sound API fulfills the needs of a wide range of application developers. Potential application areas include the following:
  • Communication frameworks, such as conferencing and telephony
  • End-user content delivery systems, such as media players and music using streamed content
  • Interactive application programs, such as games and web sites that use dynamic content
  • Content creation and editing
  • Tools, toolkits, and utilities
How Does the Java Sound API Relate to Other Interfaces?

The Java Sound API provides the lowest level of sound support on the Java platform. It provides application programs with a great amount of control over sound operations, and it is extensible. For example, the Java Sound API supplies mechanisms for installing, accessing, and manipulating system resources such as audio mixers, MIDI synthesizers, other audio or MIDI devices, file readers and writers, and sound format converters. The Java Sound API does not include sophisticated sound editors or graphical tools, but it provides capabilities on which to build such programs. It emphasizes low- level control beyond what the end user commonly expects.

Other Java platform APIs have sound-related elements. The Java Media Framework (JMF) is a higher-level API that is currently available as a Standard Extension to the Java platform. JMF specifies a unified architecture, messaging protocol, and programming interface for capturing and playing back time-based media. JMF provides a simpler solution for basic media-player application programs, and it enables synchronization between different media types, such as audio and video.

On the other hand, programs that focus on sound can benefit from the Java Sound API, especially if they require more advanced features, such as the ability to carefully control buffered audio playback or directly manipulate a MIDI synthesizer. Other Java APIs with sound aspects include Java 3D and APIs for telephony and speech. An implementation of any of these APIs might use an implementation of the Java Sound API internally, but it is not required to do so.

Packages

The Java Sound API includes support for both digital audio and MIDI data. These two major modules of functionality are provided in separate packages:
  • javax.sound.sampled -- This package specifies interfaces for capture, mixing, and playback of digital (sampled) audio.
  • javax.sound.midi -- This package provides interfaces for MIDI synthesis, sequencing, and event transport.
Two other packages permit service providers (as opposed to application developers) to create custom software components that extend the capabilities of an implementation of the Java Sound API:

Read more

Learning Java 2D, Part 1 by Robert Eckstein
 

The Java 2D is not a new API, but you can use it to create some stunningly high-quality graphics with Java technology. The Java 2D API is easy to use and includes features such as image processing, alpha-based compositing, antialiasing, geometric transformations, international text rendering, and even support for advanced printing.

In order to understand the basics of the Java 2D environment, however, you must first understand the concept of rendering. Rendering is the process whereby the Java 2D graphics engine (represented by the java.awt.Graphics2D class) will take graphics primitive classes such as shapes, text, and images, and "draw" them to an output device, such as a screen or a printer. The power of the Java 2D libraries lies in the wide variety of customizations that are available in the Graphics2D class to perform renderings.

This article discusses some of the basics of the Java 2D API, including lines and shapes, as well as the rendering pipeline. The second part of this article will go into more detail on shapes, including constructive geometry and paths, as well as discussing fonts and text. Finally, the third part will deal with using the Java 2D libraries to manipulate and display images.

User Space vs. Device Space

Let's start by defining the difference between user space and device space. In most computer graphics environments, each pixel is numbered. If you draw a square at, say (20, 20), then the top left corner of the square will begin at approximately the 20th pixel from the left edge, or axis, of the drawing space and at the 20th pixel from the top axis of the drawing space. Coordinates that are offset from axes are called Cartesian coordinates. The location of Java 2D objects are also specified using Cartesian coordinates. The beginning of the space occurs in the upper left side of a hypothetical rectangle that increases to the right and downward.

Java 2D, however, defines coordinates in units (72 units to an inch), and rendering occurs in a hypothetical plane called the user space.

Note that we use the term "units" and not "pixels." The latter term implies that the output device is a computer screen. When an object is drawn to the output device, such as a screen or printer, the results may have to be scaled to ensure that the object is the same size. After all, a shape that appears as four inches wide on the screen should also appear four inches wide when it is printed on a piece of paper. A computer monitor typically uses 72 pixels per inch, so each Java 2D unit is conveniently equivalent to a pixel. However, a computer printer may use 300, 600, or even 1200 or more dots per inch. In this case, the Java 2D graphics engine has to scale its user space to a new device space when the object is "drawn" to the printer output device.

Graphics, Lines, and Shapes

The easiest Java 2D primitives to learn are lines and shapes, so let's start there. Let's assume that we are writing the code for the inner rendering routine of a custom Swing component. With the older AWT classes, you would use the methods of the java.awt.Graphics class to draw the lines and shapes you wanted on a screen.
public paint(Graphics g) {

    g.drawLine(10,10,40,40);
    g.drawRect(20, 20, 100, 100);
    g.fillRect(120, 120, 200, 200);

}
This graphics capability was very limited. Fonts were limited; shapes could be drawn with only one pixel thickness; and image support was rudimentary. With the added graphics capabilities of the Java 2D API, on the other hand, graphics are much more robust.

Read more

What's New on java.net
 
Interaction Happens: Thinking Graphically by Jonathan Simon


Making a polished user interface (UI) is hard work. Interaction design takes experience and time, which are usually inconceivable luxuries. And that's before we mention the technical limitations in Swing, which we are all too familiar with. On top of that, programming and interaction design are often at direct odds with each other. Making a polished, functioning UI can take much more code (and much more complicated code) than making a less-polished alternative. Similarly, developing with graphics toolkits and widgets often forces the implementation to use a less-than-perfect solution from an interaction perspective. The combined effect of these forces is a difficult playing field, where we try to solve these problems and develop a product.

This article takes a holistic view at the problem space. We'll take a look at three different UI design issues from an interaction perspective. Following that, we'll look at some interaction design solutions to these problems that I've used and seen others use on countless projects. Finally, we'll implement them in Swing, exploring the technical details of implementing these designs. The goal is to understand, through practical examples, that there is a single problem space from interaction design to code. Along the way, you'll also see some code examples of Swing techniques you may not have used before but might find interesting (think transparent painting and rounded borders).

Example 1: Address Detail Panel

A common way to display detailed information is to create a panel with one label per field and to display the field alongside it. Figure 1 shows an example of one of these panels for address details of someone named What A. Guy.

Normal Address
Figure 1. Standard details panel displaying an address

Although it's easy to create a one-to-one mapping between the address fields and this panel, this design has a number of interaction issues:
  • Difficult alignment: In this example, the field names are all right-aligned, but their lengths vary. Some field names have more space between the end of the field name and the beginning of the value, making it difficult to correlate the field name and the value. Some interaction designers prefer to right-align the field name and left-align the value, but then your detail panels start to look an awful lot like ASCII Christmas trees. You can improve the alignment significantly by standardizing the field name length (say, between five and ten characters) but it's still going to be awkward.
  • Waste of space: As explained above, the field names are different lengths, and you have to make the field labels wide enough to accommodate the widest field name. Some of the fields will undoubtedly be shorter. So in addition to making the alignment difficult, it's a waste of screen real estate. Save the pixels!
  • Nondynamic: These displays don't usually adjust themselves for the information they are displaying. For example, if there is no middle initial, the value will simply be blank. But like looking through a database table, the blank fields are always there -- you'll always have the field label there, and the space is still taken up. And if you try to make it dynamic, the screen is very noticeably changing all the time. On the upside, these panels are pretty easy to build. You can even generate them automatically from a data object using reflection or a field mapping. This is a great example of where interaction design goals differ from coding simplicity. Even though they might be difficult from an interaction perspective, they do have some redeeming features. But we're here to focus on interaction and work toward the code, so let's see if we can do a little better.

    Read the rest of this article

  • Live Virtual Course
     
    Java Programming Language Workshop (VC-SL-285)


    The Java Programming Language Workshop course provides students with practical experience in designing a vertical solution for a distributed, multi-tier application. Students use graphical user interface (GUI) design principles and network-communications capabilities to code a functional Java application that interacts with a networked database server. The significant amount of lab time emphasizes the workshop nature of this course.

    FORMAT: This course is presented using Sun's web-based Live Virtual Classroom (LVC). The LVC is a dynamic and fully interactive online learning environment that features live teaching, collaboration, and instructor-assisted activities.

    COURSE FEATURES AND SERVICES:
    • Live audio by expert instructor
    • Lab reviews, simulations, demonstrations, or lab exercises
    • Printable Study Guide


    Sign up

    Sun's Java Technology CD-ROM Courses
     
    Java Programming Language (CDJ-275)


    The Java Programming Language course provides students with a self- paced CD-ROM course that can help experienced programmers learn how to write, compile, and run Java technology applications. This course provides fundamental knowledge about the Java programming language and its runtime environment, object-oriented programming with the Java programming language, creating programs with graphical user interface (GUI) components, handling exceptions, using threads, creating applets, and learning how input/output and networking work in the Java programming language.

    This course uses a new learning tool, called the ObjectTool, which was specifically created to help you more readily understand the Java technology programming language syntax and semantics. This tool also provides support for learning object concepts, such as encapsulation, inheritance, and polymorphism.

    Learn more about this course

    Sun's Java Technology Web Courses
     
    J2SE Internals and Troubleshooting (WJO-3250)


    The J2SE Internals and Troubleshooting course provides technical information on the internal functioning and operation of Java 2 Platform, Standard Edition (J2SE platform). The course addresses debugging, gathering of crash-related data, the nature of the just- in-time (JIT) compiler, garbage collection, JNI, threads, and handling signals in native code.

    Web-based courses purchased on this web site may be used only in the US. If you reside outside the US, please select a country to inquire about products delivered in your country.

    Learn more

    Sun Java Technology Top Five Courses Promotion
     
     


    There has never been a better time to take Java technology training from Sun. For a limited time, when you register for one of our five most popular Java technology training courses, you will be eligible to receive one of our five most requested giveaway items.

    Qualifying Java Technology Courses
    • Developing Applications for the J2EE Platform (FJ-310)
    • Java Programming Language (SL-275)
    • Web Component Development With Servlet and JSP Technologies (SL-314)
    • Architecting and Designing J2EE Applications (SL-425)
    • Object-Oriented Analysis and Design Using UML (OO-226)
    Read more about this offer:

    Books for Learning
     
    NetBeans IDE Field Guide


    NetBeans IDE Field Guide is the only comprehensive NetBeans 4.1 introductory guide and task reference -- it's the fast-answers NetBeans "cookbook" for every experienced Java developer. NetBeans insider Patrick Keegan shows you how to use NetBeans 4.1 to build any Java application -- even advanced J2EE software, web services, and mobile applications.

    If you're new to NetBeans, this book will help you quickly leverage its power throughout the entire edit-compile-test-debug cycle. If you've worked with older versions, you'll learn how to make the most of its dramatic improvements. Whatever you're building with Java technology, NetBeans IDE Field Guide will help you build it faster, better, and more efficiently.

    See Chapter 5, Debugging Applications

    Buy the book

    For More Information
     
    The terms "Java Virtual Machine" and "JVM" mean a virtual machine for the Java platform.


    Downloading the Java Platform, Standard Edition (Java SE, formerly known as J2SE)
     


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

    Download Java SE Platform

    Bookmark the Specifications

    New to Java Center


    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 Java Technology Fundamentals Newsletter to: fundamentals_newsletter@sun.com

    Find archived issues of the following Java technology developer newsletters or manage your current newsletter subscriptions: https://softwarereg.sun.com/registration/developer/en_US/subscriptions

    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.
    • Mobility Developer Newsletter. Learn about the latest releases, tools, and resources for developers working on wireless and Java Card technologies and applications.
    • Enterprise Java Technologies Newsletter. Learn about the latest in enterprise Java technology: releases, products, tools, resources, events, news, and views.
    • Core Java Technologies Tech Tips (formerly JDC Tech Tips). Get expert tips, sample code solutions, and techniques for developing in the Java Platform, Standard Edition (Java SE)
    You can subscribe to these and other JDC publications on the JDC Newsletters and Publications page

    PRIVACY STATEMENT

    Sun respects your online time and privacy. You have received this based on your email preferences. If you would prefer not to receive this information, please follow the steps at the bottom of this message to unsubscribe.

    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

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

    To update your Sun subscription preferences or unsubscribe to Sun news services, click here or use this link https://softwarereg.sun.com/registration/developer/en_US/subscriptions



    FEEDBACK

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

    Sun Microsystems, Inc. 10 Network Circle, MPK10-209 Menlo Park, CA 94025 US