Java Technology Fundamentals Newsletter

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/

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 Java Technology Fundamentals Newsletter.
Java Technology Fundamentals
NEWSLETTER
October 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: Filling Shapes
» Making Sense of the Java Classes & Tools: Internationalization -- Understanding Locale in the Java Platform
» Java Bits: Enumerated Types -- Java Tutorial Lesson
» Trail: 2D Graphics
» What's New on java.net: Handling Java Web Application Input, Part 1
» Newsletter for Students
» Sun's Java Technology CD-ROM Courses
» Sun's Java Technology Web Courses
» For More Information

Java Programming Language Basics
 
Filling Shapes


The Java 2D API provides support for arbitrary fill patterns when drawing filled shapes. There is support for both cyclic and acyclic gradient fills as well as matting of images. There is also the ability to fill with solid colors. The Paint interface helps you deal with all three fill styles, where Color, GradientPaint, and TexturePaint implement the interface.

For painting with a solid color, you use the setColor() method inherited from Graphics. For consistency with the other two painting mechanisms you'll soon learn about, when working with Graphics2D, you should use the setPaint() method. For instance, to paint in blue, you would call setPaint(Color.BLUE).

     import java.awt.*;
   import java.awt.geom.*;
   import javax.swing.*;
   
   public class BlueFill extends JPanel {
   
     public void paintComponent(Graphics g) {
       Graphics2D g2d = (Graphics2D)g;
       g2d.setPaint(Color.BLUE);
       Rectangle2D rectangle = 
                     new Rectangle2D.Double(10, 20, 100, 100);
       g2d.fill(rectangle);
     }
   
     public static void main(String args[]) {
       Runnable runner = new Runnable() {
         public void run() {
           JFrame frame = new JFrame("Blue Fill");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.add(new BlueFill());
           frame.setSize(300, 200);
           frame.setVisible(true);
         }
       };
       EventQueue.invokeLater(runner);
     }
   }

BlueFill

Gradient painting involves gradually changing one color to another. Through the GradientPaint class, you do not have to do the conversion yourself. All you have to do is tell the class the starting and ending point and colors. Then, when you call the fill() method of Graphics2D, it gradually changes the color at the starting point to the color at the ending point. If the area asked to fill goes beyond the rectangle formed by the starting and ending points, there is an optional boolean parameter. When this parameter is specified, a true value means the gradient should cycle. If the value is false, then the colors are solid in the two directions that go away from the bounded area -- the default behavior.

The following figure demonstrates the three possible outcomes: no optional parameter, true optional parameter, and false optional parameter. You can specify the endpoints by either using two sets of floating point numbers for endpoints or using two Point2D objects.

GradientFill

The following program generated the three possible gradients shown above. Notice that the first and third fill options are really the same.

   import java.awt.*;
   import java.awt.geom.*;
   import javax.swing.*;
   
   public class GradientFill extends JPanel {
   
     public void paintComponent(Graphics g) {
       Graphics2D g2d = (Graphics2D)g;
       GradientPaint gp = new GradientPaint(
                           25, 45, Color.CYAN, 75, 95, Color.BLUE);
       g2d.setPaint(gp);
       Rectangle2D rectangle = new Rectangle2D.Double(
                                                   0, 20, 100, 100);
       g2d.fill(rectangle);
       gp = new GradientPaint(
                    150, 45, Color.CYAN, 200, 95, Color.BLUE, true);
       g2d.setPaint(gp);
       rectangle = new Rectangle2D.Double(125, 20, 100, 100);
       g2d.fill(rectangle);
       Point2D p2d1 = new Point2D.Float(45, 170);
       Point2D p2d2 = new Point2D.Float(195, 220);
       gp = new GradientPaint(
                         p2d1, Color.CYAN, p2d2, Color.BLUE, false);
       g2d.setPaint(gp);
       Arc2D arc = new Arc2D.Double(
                             20, 145, 200, 100, 45, 300, Arc2D.PIE);
       g2d.fill(arc);
       g.setColor(Color.BLACK);
       g.drawLine(25, 45, 75, 95);
       g.drawLine(150, 45, 200, 95);
       g.drawLine(45, 170, 195, 220);
     }
   
     public static void main(String args[]) {
       Runnable runner = new Runnable() {
         public void run() {
           JFrame frame = new JFrame("Gradient Fill");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.add(new GradientFill());
           frame.setSize(300, 300);
           frame.setVisible(true);
         }
       };
       EventQueue.invokeLater(runner);
     }
   }

Texture painting is similar to gradient painting. However, instead of a starting and ending color, you provide a BufferedImage and area to use as the texture:

TexturePaint(BufferedImage texture, Rectangle2D rect). 

Because the texture is a BufferedImage, you can draw anything you want onto it, from text to image files to any other content. The rectangle specifies the piece of the BufferedImage to use for matting, so you could draw a large figure and crop a small piece out of it. Below, you'll see an image as the texture to use when filling a shape. Because the texture doesn't change between calls to paintComponent(), it is best created outside of paintComponent() so that the image file is fetched only once.

TextureFill

Below is the source used to generate the image above. Feel free to pick any image you choose and set accordingly.

   import java.awt.*;
   import java.awt.geom.*;
   import java.awt.image.*;
   import javax.swing.*;
   
   public class TextureFill extends JPanel {
   
     public TexturePaint getImageTexture(String imageFi
     TexturePaint tp = getImageTexture("logo.gif");le) {
       ImageIcon icon = new ImageIcon(imageFile);
       Image img = icon.getImage();
       int width = img.getWidth(this);
       int height = img.getHeight(this);
       BufferedImage buffImg =
         new BufferedImage(width, height, 
                              BufferedImage.TYPE_INT_ARGB);
       Graphics g = buffImg.getGraphics();
       g.drawImage(img, 0, 0, this);
       Rectangle2D rect = new Rectangle(0, 0, width, height);
       return new TexturePaint(buffImg, rect);
     }
   
     public void paintComponent(Graphics g) {
       Graphics2D g2d = (Graphics2D)g;
       g2d.setPaint(tp);
       Rectangle2D rectangle = 
                          new Rectangle2D.Double(0, 30, 200, 100);
       g2d.fill(rectangle);
       Arc2D arc = 
          new Arc2D.Double(20, 145, 200, 100, 45, 300, Arc2D.PIE);
       g2d.fill(arc);
     }
   
     public static void main(String args[]) {
       Runnable runner = new Runnable() {
         public void run() {
           JFrame frame = new JFrame("Texture Fill");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.add(new TextureFill());
           frame.setSize(300, 300);
           frame.setVisible(true);
         }
       };
       EventQueue.invokeLater(runner);
     }
   }

That is really all there is to "filling" shapes when drawn to the system. Be sure to pick the right one for the specific task you have at hand.




Making Sense of the Java Classes & Tools
 
Internationalization: Understanding Locale in the Java Platform
by John O'Conner


Language and geographic environment are two important influences on our culture. They create the system in which we interpret other people and events in our life. They also affect, even define, proper form for presenting ourselves and our thoughts to others. To communicate effectively with another person, we must consider and use that person's culture, language, and environment.

Similarly, a software system should respect its users' language and geographic region to be effective. Language and region form a locale, which represents the target setting and context for localized software. The Java platform uses java.util.Locale objects to represent locales. This article describes the Locale object and its implications for programs written for the Java platform.

This article is divided into the following sections:

  • Definition
  • Construction
  • Preconstructed Locales
  • Identifying Supported Locales
  • Representing Locale as a String
  • Using Locale
  • Retrieving Locale Information
  • Summary
  • For More Information

Definition

Locales identify a specific language and geographic region. Locale- sensitive objects use java.util.Locale objects to customize how they present and format data to the user. Locales affect user interface language, case mapping, collation (sorting), date and time formats, and number and currency formats. Locales are critical to many culturally and linguistically sensitive data operations.

A java.util.Locale is a lightweight object that contains only a few important members:

  • A language code
  • An optional country or region code
  • An optional variant code

When writing or talking about locales, you can use a text abbreviation for a convenient representation. This notation separates each component of a locale with an underscore character:

<language code>[_<country code>[_<variant code>]] 

These three elements provide enough information to other locale- sensitive objects so that they can modify their behavior for a specific linguistic or cultural purpose. For example, a java.text.NumberFormat object created for a German-speaking Swiss locale will format numbers differently than it would for a German- speaking Austrian locale. See Table 1.



Read more

Java Bits
 
Enumerated Types -- Java Tutorial Lesson


An enumerated type is a type whose legal values consist of a fixed set of constants. Common examples include compass directions, which take the values North, South, East, and West; and days of the week, which take the values Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday.

In the Java programming language, you define an enumerated type by using the enum keyword. For example, you would specify a days-of- the-week enumerated type as:

enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, 
            FRIDAY, SATURDAY };

Notice that by convention, the names of an enumerated type's values are spelled in uppercase letters.

You should use enumerated types any time you need to represent a fixed set of constants. That includes natural enumerated types such as the planets in our solar system, the days of the week, and the suits in a deck of cards, as well as sets in which you know all possible values at compile time -- for example, the choices on a menu, rounding modes, command-line flags, and so on.

Java programming language enumerated types are much more powerful than their counterparts in other languages, which are just glorified integers. The enum declaration defines a class (called an enum type). These are the most important properties of enum types:

  • Printed values are informative.
  • They are typesafe.
  • They exist in their own namespace.
  • The set of constants is not required to stay fixed for all time.
  • You can switch on an enumeration constant.
  • They have a static values method that returns an array containing all of the values of the enum type in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enumerated type. (See "The for Statement" in the "Learning the Java Language" trail).)
  • You can provide methods and fields, implement interfaces, and more.
  • They provide implementations of all the Object methods. They are Comparable and Serializable, and the serial form is designed to withstand changes in the enum type.

In the following example, Planet is an enumerated type that represents the planets in the solar system. A Planet has constant mass and radius properties. Each enum constant is declared with values for the mass and radius parameters that are passed to the constructor when it is created. Note that the constructor for an enum type is implicitly private. If you attempt to create a public constructor for an enum type, the compiler displays an error message.

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7),
    PLUTO   (1.27e+22,  1.137e6);

    private final double mass;   //in kilograms
    private final double radius; //in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    public double mass()   { return mass; }
    public double radius() { return radius; }

    //universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    public double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
}

In addition to its properties, Planet has methods that allow you to retrieve the surface gravity and weight of an object on each planet. Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit):

public static void main(String[] args) {
    double earthWeight = Double.parseDouble(args[0]);
    double mass = earthWeight/EARTH.surfaceGravity();
    for (Planet p : Planet.values()) {
        System.out.printf("Your weight on %s is %f%n",
                          p, p.surfaceWeight(mass));
    }
}

Here's the output:

$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413
Your weight on PLUTO is 11.703031

There's one limitation of enum types: Although enum types are classes, you cannot define a hierarchy of enums. In other words, it's not possible for one enum type to extend another enum type.

Finally, the java.util package contains two special-purpose Set and Map implementations that support enum types: EnumSet (discussed in Set Implementations (in the "Learning the Java Language" trail) and EnumMap (discussed in "Map Implementations" in the "Learning the Java Language" trail).



Read more

Trail: 2D Graphics
 
by Deborah Adair, Jennifer Ball, and Monica Pawlan


This trail introduces you to the Java 2D API and shows you how to display and print 2D graphics in your Java technology programs. The Java 2D API enables you to easily do the following:

  • Draw lines of any thickness
  • Fill shapes with gradients and textures
  • Move, rotate, scale, and shear text and graphics
  • Composite overlapping text and graphics

For example, you could use the Java 2D API to display complex charts and graphs that use various line and fill styles to distinguish sets of data, like those shown in the following figure:

2D-1

The Java 2D API also enables you to store and to manipulate image data -- for example, you can easily perform image-filter operations, such as blur and sharpen, as shown in the following figure:

2D-2

This trail covers the most common uses of the Java 2D APIs and briefly describes some of the more advanced features.

The Java 2D APIs are closely integrated with the Abstract Windowing Toolkit (AWT). If you are not familiar with AWT, you might find it useful to review the AWT documentation, which you can download.

Overview of the Java 2D API introduces the key Java 2D concepts and describes the Java 2D rendering model.

Displaying Graphics with Graphics2D teaches you how to set up the Graphics2D rendering context to use fancy stroke and fill styles, perform transformations, clip the drawing region, composite overlapping graphics, and specify rendering preferences.

Working with Text and Fonts shows you how to use a Font object to create a font with desired attributes, and to derive a new font by changing the attributes, determine the names of the fonts that are available on your system, and position text within a component.

Manipulating and Displaying Images explains how to implement double buffering and how to perform image-filter operations with BufferedImage objects.

Printing teaches you how to render 2D graphics to a printer and how to print complex documents.

Solving Common 2D Graphics Problems gives the solutions to some problems you might encounter when writing 2D applets and applications.

Read more

What's New on java.net
 
Handling Java Web Application Input, Part 1
by Stephen Enright


Inadequate data validation is the most common cause of security exploits suffered by web applications today. A staggering fact is the high number of applications exploited through weak validation. This is due to the simplicity of such an attack. No longer do attackers have to spend vast amounts of time researching ways to circumvent the security infrastructure of an application. An attacker can use freely available tools to scan for vulnerable web sites. Using these findings, an attacker can use a web browser to ghost straight through firewall rule sets on port 80, altering an application's intended behavior. This is true, never more so than today.

A multitude of technologies and frameworks are available. Engineers are under increasing pressure to complete work on time and hence place a heavy reliance on such tools. However, such technology may not adequately deal with user input to meet all cases and as a result may introduce unintentional security vulnerabilities. Therefore, it is of paramount importance that secure coding practices are in place to close any possible doorway that permits such nefarious attacks to take place.

The purpose of this series of articles is to explain common security vulnerabilities associated with application input. This series emphasizes the importance of handling application input correctly. Although the topics covered are nothing new, they are critical to ensuring an application's security.

This series is aimed at practitioners interested in planning, designing, implementing, and maintaining software systems that are unaware of such issues. In this article, part one in the series, we will look at some validation best practices, along with SQL injection attacks. In later articles, we will look at other common attacks; in particular, part two will deal with cross-site scripting attacks and error-handling techniques.



Read the rest of this article

Newsletter for Students
 
Get your FREE Student Connection subscription today!


Get your FREE Student Connection subscription today! Sun's new Student Connection e-zine delivers the hottest tech tools, the coolest coding tips, and one-click access to a premier collection of student developer resources and training opportunities. All you have to do is become a member of Sun Developer Network and the e-zine is yours!



Sign up

Sun's Java Technology CD-ROM Courses
 
Distributed Programming With Java Technology (CDJ-320)


The Distributed Programming With Java Technology course provides students with a self-paced CD-ROM course that can help experienced programmers build the necessary skills to design and program distributed computing solutions. It provides Java platform programmers and network application programmers with the essential information for building distributed computing solutions using the following application program interfaces (APIs):

  • Java Database Connectivity (JDBC)
  • Java Remote Method Invocation (RMI)
  • Java Interface Definition Language (IDL)
  • Java Naming and Directory Interface (JNDI)
Learn more about this course

Sun's Java Technology Web Courses
 
ePractice Certification Exam for the Sun Certified Programmer for the Java 2 Platform, Standard Edition 5.0 (WGS-PREX-J055C))


The ePractice Certification Exam for the Sun Certified Programmer for the Java 2 Platform, Standard Edition 5.0 provides students with preparation for Sun certification by acquainting them with the format of the exam and its questions, providing instant feedback regarding skill levels and gaps, and suggesting specific Sun Educational Services training to fill those gaps. The exam includes sample test questions, the correct answers including explanations, and suggestions for future study.



Learn more

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