Tech all over the world
Wednesday, March 01, 2006
  Java Technology Fundamentals

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
February 2006
 

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 in this issue of Fundamentals to compile, you need to use the JDK 5.0 software.
http://java.sun.com/j2se/1.5.0/download.jsp

Contents
 
» Java Programming Language Basics: The SpringLayout Manager & Quiz
» Making Sense of the Java Classes & Tools: How to Use BoxLayout - Java Tutorial Resources
» Java Bits: How to Use File Choosers - Java Tutorial
» What's New on Java Studio Creator
» Flash Demos of NetBeans IDE
» Sun's Java Technology CD-ROM Courses
» Award-Winning Sun Java Studio Creator 2 Now Available
» Free Developer Tools
» For More Information

Java Programming Language Basics
 
The SpringLayout Manager


The newest addition to the layout manager front is the SpringLayout manager, added with the Java Platform, Standard Edition, v. 1.4.2. This allows you to attach "springs" to components so that they are laid out relative to other components. For instance, with SpringLayout, you can say that a button appears attached to the right border, no matter what size a user makes the screen.

The SpringLayout manager relies on a SpringLayout.Constraints class for the component constraints. This works similar to the GridBagConstraints class that complements the GridBagLayout manager: each component added to the container can have an attached SpringLayout.Constraints. Therein lies the end to the similarities though.

First off, you usually don’t have to add the component with the constraints. Instead, you can add the component to the container, and then attach the constraints separately. There is nothing stopping you from adding the constraints with the component, but SpringLayout.Constraints is not a simple class. It is a collection of Spring objects, each being a different constraint on the component.

When you use a Spring, you need to add each Spring constraint separately to SpringLayout.Constraints. You "add" constraints to the SpringLayout.Constraints by setting specific constraints on an edge of the component. Using the four SpringLayout constants of EAST, WEST, NORTH, and SOUTH, you call the setContraints(String edge, Spring spring) method of SpringLayout.Constraints, where the String is one of the constants.

For instance, if you wanted to add a component in the top-left of a container, you could set up two springs of constant size, combine them, and add the component to the container with the combined set, as shown here:
   Component left = ...;   SpringLayout layout = new SpringLayout();   JPanel panel = new JPanel(layout);   Spring xPad = Spring.constant(5);   Spring yPad = Spring.constant(25);   SpringLayout.Constraints constraint =                       new SpringLayout.Constraints();   constraint.setConstraint(SpringLayout.WEST, xPad);   constraint.setConstraint(SpringLayout.NORTH, yPad);   contentPane.add(left, constraint); 
That doesn’t look too difficult, but it gets more difficult when you need to add the next component, either to the right of the first or below it. You can’t just say add the component n pixels over. You must actually add the padding to the edge of the earlier component. To find the edge of the earlier component, you ask the layout manager with getConstraint(), passing in the edge you want and the component, as in layout.getConstraint(SpringLayout.EAST, left), to get the location of the right edge of the first component. From that, you can add in the necessary padding and attach it to the edge of the other component, as shown here.
   Component right = ...;   Spring rightSideOfLeft =                layout.getConstraint(SpringLayout.EAST, left);   Spring pad = Spring.constant(20);   Spring leftEdgeOfRight = Spring.sum(rightSideOfLeft, pad);   constraint = new SpringLayout.Constraints();   constraint.setConstraint(SpringLayout.WEST, leftEdgeOfRight);   constraint.setConstraint(SpringLayout.NORTH, yPad);   contentPane.add(right, constraint); 
This works perfectly well, but gets tedious as the number of components increases. Instead, another way that sidesteps the in between steps is to add the components without the constraints, and then add each separately, connecting the components via the putConstraints() method of SpringLayout.
   public void putConstraint(String e1, Component c1, int pad,       String e2, Component c2)   public void putConstraint(String e1, Component c1, Spring s,       String e2, Component c2) 
Here, instead of asking for the edge and adding in the padding yourself, the putConstraint() call combines the tasks for you. To demonstrate, the following snippet adds the same component constraints to the right component as above, but uses putConstraint() instead of using SpringLayout.Constraints directly.
   Component left = ...;   Component right = ...;   SpringLayout layout = new SpringLayout();   JPanel panel = new JPanel(layout);   panel.add(left);   panel.add(right);   layout.putConstraint(SpringLayout.WEST, left, 5,     SpringLayout.WEST, panel);   layout.putConstraint(SpringLayout.NORTH, left, 25,     SpringLayout.NORTH, panal);   layout.putConstraint(SpringLayout.NORTH, right, 25,     SpringLayout.NORTH, panel);   layout.putConstraint(SpringLayout.WEST, right, 20,     SpringLayout.EAST, left); 
To demonstrate the use of SpringLayout, the following program connects the pieces explained using putConstraints().
 import java.awt.*; import javax.swing.*;  public class SpringTest {   public static void main(String args[]) {     EventQueue.invokeLater(new Runnable() {       public void run() {         JFrame frame = new JFrame("Spring Form");         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         Container contentPane = frame.getContentPane();          SpringLayout layout = new SpringLayout();         contentPane.setLayout(layout);          Component left = new JLabel("Left");         Component right = new JTextField(15);          contentPane.add(left);         contentPane.add(right);          layout.putConstraint(SpringLayout.WEST,  left, 10,           SpringLayout.WEST,  contentPane);         layout.putConstraint(SpringLayout.NORTH, left, 25,           SpringLayout.NORTH, contentPane);         layout.putConstraint(SpringLayout.NORTH, right, 25,           SpringLayout.NORTH, contentPane);         layout.putConstraint(SpringLayout.WEST, right, 20,           SpringLayout.EAST, left);          frame.setSize(300, 100);         frame.setVisible(true);       }     });   } } 
Compiling and running the program produces the following output:



After resizing the screen, notice how the label and text field stay in the top-left corner of the screen.



Take this online quiz to test what you know about layouts.


Making Sense of the Java Classes & Tools
 
How to Use BoxLayout - Java Tutorial


The Swing packages include a general purpose layout manager named BoxLayout (in the API reference documentation). BoxLayout either stacks its components on top of each other or places them in a row, depending on what you choose. You might think of it as a full-featured version of FlowLayout. Here is a picture of an application that demonstrates using BoxLayout to display a centered column of components:



By creating one or more lightweight containers that use BoxLayout, you can achieve some layouts for which the more complex GridBagLayout is often used. BoxLayout is also useful in some situations where you might consider using GridLayout or BorderLayout. One big difference between BoxLayout and many earlier layout managers is that BoxLayout respects each component's maximum size and X/Y alignment. We'll discuss that later.

The following figure shows a GUI that uses two instances of BoxLayout. In the top part of the GUI, a top-to-bottom box layout places a label above a scroll pane. In the bottom part of the GUI, a left-to-right box layout places two buttons next to each other. A BorderLayout combines the two parts of the GUI and ensures that any excess space is given to the scroll pane.



The following code, taken from ListDialog.java, lays out the GUI. This code is in the constructor for the dialog, which is implemented as a JDialogsubclass. The bold lines of code set up the box layouts and add components to them.
 JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(250, 80)); listScroller.setAlignmentX(LEFT_ALIGNMENT); ... //Lay out the label and scroll pane from top to bottom. JPanel listPane = new JPanel(); listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS)); JLabel label = new JLabel(labelText); ... listPane.add(label); listPane.add(Box.createRigidArea(new Dimension(0,5))); listPane.add(listScroller); listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));  //Lay out the buttons from left to right. JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(cancelButton); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(setButton);  //Put everything together, using the content pane's BorderLayout. Container contentPane = getContentPane(); contentPane.add(listPane, BorderLayout.CENTER); contentPane.add(buttonPane, BorderLayout.PAGE_END); 
Read the rest of this lesson.

Java Bits
 
How to Use File Choosers - Java Tutorial


File choosers provide a GUI for navigating the file system, and then either choosing a file or directory from a list or entering the name of a file or directory. To display a file chooser, you usually use the JFileChooser API to show a modal dialog containing the file chooser. Another way to present a file chooser is to add an instance of JFileChooser (in the API reference documentation) to a container.

Note: If you intend to distribute your program as an unsigned Java Web Start application, then instead of using the JFileChooser API you should use the file services provided by the JNLP API. These services, FileOpenService and FileSaveService, not only provide support for choosing files in a restricted environment, but also take care of actually opening and saving them. An example of using these services is in JWSFileChooserDemo. Documentation for using the JNLP API is in the Java Web Start Developer's Guide (outside of the tutorial).

The rest of this section discusses how to use the JFileChooser API. A JFileChooser object only presents the GUI for choosing files. Your program is responsible for doing something with the chosen file, such as opening or saving it. Refer to I/O (in the Creating a GUI with JFC/Swing trail) for information on how to read and write files.

The JFileChooser API makes it easy to bring up open and save dialogs. The look and feel determine what these standard dialogs look like and how they differ. In the Java look and feel, the save dialog looks the same as the open dialog, except for the title on the dialog's window and the text on the button that approves the operation. Here is a picture of the Java look and feel's standard open dialog:



Here's a snapshot of an application that brings up an open dialog and a save dialog.



Bringing up a standard open dialog requires only two lines of code:
 //Create a file chooser final JFileChooser fc = new JFileChooser(); ... //In response to a button click: int returnVal = fc.showOpenDialog(aComponent); 
The argument to the showOpenDialog method specifies the parent component for the dialog. The parent component affects the position of the dialog and the frame that the dialog depends on. For example, the Java look and feel places the dialog directly over the parent component. If the parent component is in a frame, then the dialog is dependent on that frame, disappearing when the frame is iconified and reappearing when the frame is deiconified.

By default, a file chooser that hasn't been shown before displays all files in the user's home directory. You can specify the file chooser's initial directory using one of JFileChooser's other constructors, or you can set the directory with the setCurrentDirectory method.

The call to showOpenDialog appears in the actionPerformed method of the Open a File... button's action listener:
 public void actionPerformed(ActionEvent e) {     //Handle open button action.     if (e.getSource() == openButton) {         int returnVal = fc.showOpenDialog(FileChooserDemo.this);          if (returnVal == JFileChooser.APPROVE_OPTION) {             File file = fc.getSelectedFile();             //This is where a real application would open the file.             log.append("Opening: " + file.getName() + "." + newline);         } else {             log.append("Open command cancelled by user." + newline);         }    } ... } 
The showXxxDialog methods return an integer that indicates whether the user selected a file. Depending on how you use a file chooser, it's often sufficient to check whether the return value is APPROVE_OPTION and to do nothing for any other value. To get the chosen file (or directory, if you set up the file chooser to allow directory selections), call getSelectedFile on the file chooser. This method returns an instance of File.

The example gets the name of the file and uses it in the log message. You can call other methods on the File object, such as getPath, isDirectory, or exists to get information about the file. You can also call other methods such as delete and rename to change the file in some way. Of course, you might also want to open or save the file using one of the reader or writer classes provided by the Java platform. See I/O (in the Creating a GUI with JFC/Swing trail) for information about using readers and writers to read and write data to the file system.

The example program uses the same instance of JFileChooser to display a standard save dialog. This time the program calls showSaveDialog:
 int returnVal = fc.showSaveDialog(FileChooserDemo.this); 
By using the same file chooser instance to display its open and save dialogs, the program reaps these benefits:
  • The chooser remembers the current directory between uses so the open and save versions automatically share the same current directory.
  • You have to customize only one file chooser, and the customizations apply to both the open and save versions of it.
Finally, the example program has commented-out lines of code that let you change the file selection mode. For example, the following line of code makes the file chooser able to select only directories, and not files:
 fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
Read the the rest of this tutorial.

What's New on Java Studio Creator
 
Watch how the Java Studio Creator IDE can help you develop web applications and portlets in this entertaining, high-level look at the IDE and its capabilities (flash).

Watch the demo.

Flash Demos of NetBeans IDE
 
NetBeans.org now has a number of Flash demos that can save you time and making learning this IDE easy. Learn how to use the Profiler, reuse custom components, create a TopWindowComponent, and more.

Watch the demos.

Sun's Java Technology CD-ROM Courses
 
Web Component Development With Servlet and JSP Technology (CDJ-314)


The Web Component Development With Java Servlet and JavaServer Pages (JSP) Technology course provides students with a way to quickly obtain the skills necessary to build Java Server Pages and their accompanying Java Servlet code rapidly and effectively. Experienced Java programming language developers will benefit from the optional real-world lab exercises that can be downloaded into the workplace.

This course also provides an alternative method of preparing for the Sun Certified Web Component Developer certification examination. The training provided is accurate and up-to-date, providing new insights into not only Java technology but also into how to best apply them in enterprise environments.

As an additional value, students of this web bundle will have access for the duration of this course to the following Quick Reference Guides: HTML, HTTP, the Tomcat Server, the ANT Tool, XML, and UML.

Learn more about this course.

Award-Winning Sun Java Studio Creator 2 Now Available
 
New features, new web site, and lots more for developers! Java Studio Creator makes visual web application and portlet development easy. The developer.com 2006 Java Tool/Add-in of the Year is free to Sun Developer Network members, so get it today.

Free Developer Tools
 
Sun is offering the award-winning Sun Java Studio Enterprise and Sun Java Studio Creator IDEs at no cost to all developers worldwide who join Sun Developer Network (SDN).

Get your free tools.

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



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