.
.
developers.sun.com java.sun.com
.
    September 27, 2004    

In this Issue

 

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

- Java Programming Language Basics: Drag and Drop
- Java Bits: Java Speech API
- Making Sense of the Java Class: BigDecimal Class
- Sun's Online Courses: Getting Started With the Sun Java Desktop
- Online Chats: New Language Features in J2SE 5.0 and Project Looking Glass
- Sun Tech Days, A Developer Conference!
- For More Information: Read articles, Tech Tips, trails, and tutorials that provide
more information on the topics discussed here.


You can receive future issues of this newsletter in HTML or text: https://softwarereg.sun.com/registration/developer/en_US/subscriptions

For more Java technology content, visit these sites:

java.sun.com - The latest Java platform releases, tutorials, and newsletters.

java.net - A web forum for collaborating and building solutions together.

java.com - The marketplace for Java technology, applications and services.

.

Java Programming Language Basics

Drag and Drop

In the last newsletter, you learned about MIME types and transferring data through the system clipboard. This month, you'll explore transferring data with drag and drop. Click the mouse over content you wish to move and drag the mouse with its associated content to its new home.

With release 1.4, many Swing components offer Drag and Drop support directly with minimal work. All you have to do is call setDragEnabled on the component with an argument of true, and for the appropriate components, the default behavior will be available. For instance, in the following example, you can drag the JTextField contents and drop them into a button's label.

import java.awt.*;
import javax.swing.*;

public class DndExample {
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        JFrame frame = new JFrame("Dnd Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();
        JTextField textField = new JTextField("Select This");
        textField.setDragEnabled(true);
        contentPane.add(textField, BorderLayout.NORTH);
        JButton button = new JButton("Drop Here");
        button.setTransferHandler(new TransferHandler("text"));
        contentPane.add(button, BorderLayout.SOUTH);
        frame.setSize(200, 100);
        frame.setVisible(true);
      }
    });
  }
}

The button side of the example needs a little coaxing in what to do with the drop operation. Its setTransferHandler method allows you to specify a TransferHandler which will handle the drop operation. In this simple case, all you have to do is specify which JavaBeans property acts as the destination. So, to put the text from the JTextField (or any draggable text component) into the label of the button, you specify the text property of JButton:

button.setTransferHandler(new TransferHandler("text"));

This built in behavior isn't limited to text though. For instance, the JColorChooser component comes with built-in support for dragging java.awt.Color objects. Select the color, drag the mouse from the preview area at bottom of control, and drop it into somewhere waiting for a Color. In the following example, this is demonstrated with a JButton background as the target area.

import java.awt.*;
import javax.swing.*;

public class ColorDndExample {
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        JFrame frame = new JFrame("Dnd Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();
        JColorChooser chooser = new JColorChooser();
        chooser.setDragEnabled(true);
        contentPane.add(chooser, BorderLayout.CENTER);
        JButton button = new JButton("Drop Here");
        button.setTransferHandler(new TransferHandler("background"));
        contentPane.add(button, BorderLayout.SOUTH);
        frame.setSize(300, 300);
        frame.setVisible(true);
      }
    });
  }
}

That background is specified by setting the TransferHandler for the button:

button.setTransferHandler(new TransferHandler("background"));

The Swing components that offer built in drag support include all the text components but JPasswordField (JTextField, JFormattedTextField, JTextArea, JTextPane, and JEditorPane), JColorChooser, JFileChooser, JList, JTable, and JTree. Drop support comes with all the text components, including JPasswordField, along with the JColorChooser.

If you want to add drag support to your own components, you have to add code to detect the initiating activity and export the draggable data. To demonstrate, you'll notice that JLabel doesn't come with built-in drag support. Support is easy to add by initiating the drag operation when the mouse is pressed over the component.

 JLabel label = ...
   label.setTransferHandler(new TransferHandler("text"));

   MouseListener listener = new MouseAdapter() {
     public void mousePressed(MouseEvent e) {
       JComponent c = (JComponent)e.getSource();
       TransferHandler handler = c.getTransferHandler();
       handler.exportAsDrag(c, e, TransferHandler.COPY);
     }
   };
   label.addMouseListener(listener);

This code first says that the property to associate with the drag and drop operations is the text property of the label. As with JButton, for dropping, setText will be called with the dragged content. On the drag side, the data that will be exported is the result of getText. When you've detected you want to initiate a drag operation, you have to tell the TransferHandler to exportAsDrag. You never directly get the content yourself here. Instead, the handler knows what content to use based upon the property passed into the constructor.

The following program demonstrates all these pieces together. It supports dragging from the text field to the label or in the reverse direction from the label to the text field.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LabelDndExample {
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        JFrame frame = new JFrame("Label Dnd Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();
        JTextField textField = new JTextField("Drop Here");
        textField.setDragEnabled(true);
        contentPane.add(textField, BorderLayout.NORTH);
        JLabel label = new JLabel("Drag Here");
        label.setTransferHandler(new TransferHandler("text"));
        MouseListener listener = new MouseAdapter() {
          public void mousePressed(MouseEvent e) {
            JComponent c = (JComponent)e.getSource();
            TransferHandler handler = c.getTransferHandler();
            handler.exportAsDrag(c, e, TransferHandler.COPY);
          }
        };
        label.addMouseListener(listener);
        contentPane.add(label, BorderLayout.SOUTH);
        frame.setSize(200, 100);
        frame.setVisible(true);
      }
    });
  }
}

There is much more that can be done with the Drag and Drop support available with the Java platform. To learn more, follow the trail in the Sun Java Tutorial.

.
.

Java Bits 2

Java Speech API

The Java Speech API allows you to incorporate speech technology into user interfaces for your applets and applications. Offering a cross-platform interface, the API supports command and control recognizers, dictation systems, and speech synthesizers. Through the use of a simple rule-based grammar, your applications can be voice controlled in no time.

While the API is pure Java technology, you do need a library specific to the runtime platform of your users.

Explore the API and play with the library at the Java Media home for the Java Speech API.

.
.

Making Sense of the Java Classes

BigDecimal Class

If you're in the finance arena and just can't deal with any chance of round off error, consider using the BigDecimal class found in the java.math package. For numbers larger then can be represented by a double or float, the BigDecimal class never rounds off, offering infinite precision.

The first thing you need to know when working with BigInteger is that you can't use the standard math operators like plus (+) or minus (-). Any time you need to do something as simple as adding numbers together, you must call a method of the class.

This brings up the second point of using the class. Created instances are immutable. In other words, once created, you can't change it. So, methods like add or divide return new BigDecimal objects, instead of updating existing ones.

When using BigDecimal, you specify a scale, meaning the number of digits after the decimal point, and all numerical computations return that many significant digits. When rounding must occur, you must specify a rounding constant so the system can determine how you want the system to truncate the last digit.

BigDecimal Rounding Constants:

ROUND_CEILING           Round up towards positive infinity
ROUND_DOWN             Round towards zero
ROUND_FLOOR             Round towards negative infinity
ROUND_HALF_DOWN     Round towards nearest neighbor, or zero if equal
ROUND_HALF_EVEN       Round towards nearest neighbor, or even if equal
ROUND_HALF_UP          Round towards nearest neighbor, or away from zero if equal
ROUND_UNNECESSARY  Value can be represented without rounding
ROUND_UP                  Round away from zero

You can specify the scale for a BigDecimal in one of three ways. When you call the BigDecimal constructor with a String, the number of digits after the decimal place determines the scale. When you call the constructor passing in a BigInteger, you also pass in a scale. And, you can always change it later with setScale.

To demonstrate, the following program calculates how much money you'll have after a year, investing $10,000 in an account with an annual rate of return at 2.25%.

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;

public class BigDecSample {
  public static void main(String args[]) {
    BigDecimal rate = 
      new BigDecimal(".022500");
    BigDecimal months = 
      new BigDecimal("12");
    BigDecimal monthlyRate = 
      rate.divide(months, BigDecimal.ROUND_HALF_DOWN);
    NumberFormat pf = 
      NumberFormat.getPercentInstance(Locale.US);
    pf.setMinimumFractionDigits(4);
    System.out.println("Annual rate : " 
      + pf.format(rate.doubleValue()));
    System.out.println("Monthly rate: " 
      + pf.format(monthlyRate.doubleValue()));
    BigDecimal balance = 
      new BigDecimal("10000.0000");
    NumberFormat nf = 
      NumberFormat.getCurrencyInstance();
    for (int i=0; i<12; i++) {
      BigDecimal interest = 
        balance.multiply(monthlyRate);
      balance = balance.add(interest);
      System.out.println("Balance : " 
        + nf.format(balance.doubleValue()));
    }
  }
}

And then running the program generates the following output:

Annual rate : 2.2500%
Monthly rate: 0.1875%
Balance : $10,018.75
Balance : $10,037.54
Balance : $10,056.36
Balance : $10,075.21
Balance : $10,094.10
Balance : $10,113.03
Balance : $10,131.99
Balance : $10,150.99
Balance : $10,170.02
Balance : $10,189.09
Balance : $10,208.19
Balance : $10,227.33

Meaning that you'll get $227.33 back in interest, not $225 as you might expect, since earned interest is compounded, giving you interest on your interest.

.
.

Sun's J2SE Web Courses

Getting Started With the Sun Java Desktop

The Getting Started With the Sun Java Desktop course is a tutorial that enables students to efficiently use the Sun Java Desktop and its components. The course aims to help users to transition from other desktop environments to the Sun Java Desktop. The course describes the features of the Sun Java Desktop and compares the components of the desktop with those of the Microsoft Windows desktop.

More

.
.

Online Chats

New Language Features in J2SE 5.0
Guests: Scott Seligman, Joe Darcy, and Peter von der Ah.
October 12. 11:00 A.M. PDT/6:00 P.M. UTC

Project Looking Glass
Guests: Hideya Kawahara, Paul Byrne, and Deron Johnson
October 26. 11:00 A.M. PDT/6:00 P.M. UTC

.
.

Sun Tech Days, A Developer Conference!

October 7-8, 2004: Seoul, South Korea

November 4-5, 2004: Manila, Philippines

November TBD, 2004: New York, USA

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.

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

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

PRIVACY STATEMENT:
Sun respects your online time and privacy. You have received this based on your e-mail 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


Copyright 2004 Sun Microsystems, Inc. All rights reserved. Sun Microsystems, Inc. 10 Network Circle, MPK10-209 Menlo Park, CA 94025 US

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


SUBSCRIBE/UNSUBSCRIBE
- To subscribe, go to the subscriptions page, choose the newsletters you want to subscribe to and click Update
- To unsubscribe, go to the subscriptions page, uncheck the appropriate check box, and click Update


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