
Technology Fundamentals
Supplements Index
April 2002
Java Platform Overview |
Getting Started |
Step-by-Step Programming
Learning Paths |
References & Resources |
Certification
Welcome to the Java Developer Connection Java Technology Fundamentals
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 the JDC's New to Java Programming Center.
CONTENTS
1. Java Programming Language Basics
Learning about Layout Managers
2. Making Sense of the Java Class Libraries
The Box and JTabbedPane classes
3. Program Challenge
LayoutChallenge Application
4. Java Bits
5. New to the Programming Center
Supplement Name Change
6. For More Information
Read articles, Tech Tips, trails, and tutorials that provide more information on the topics discussed here.
Java Programming Language Basics
Learning about Layout Managers
Programs written for the Java 2 Platform are meant to be "Write Once, Run Anywhere" (WORA). When creating a user interface that means you must deal with platform-specific issues like font and component size differences.
Written with the Java programming language, these user interfaces can take advantage of a library-level feature called layout managers to position components within the interface. By relying on layout managers to position components, you don't have to calculate absolute positions for components, which might look good on your platform, but could look horrible for another user on a different platform.
When working with a layout manager, you:
- Set the manager for the container that is holding the components
- Add the components to the container
Those components are positioned based upon the rules of the layout manager you've chosen. You just need to learn the rules of the individual layout managers to create your user interfaces.
Several layout managers come standard with the graphical libraries of the Java 2 Standard Edition (J2SE), version 1.4. These are the more commonly used ones:
FlowLayout
GridLayout
BoxLayout
BorderLayout
The FlowLayout manager is the simplest of the bunch. It works like word wrapping in a word processor, fitting as many components as possible on a row. When there is no more room, later components move onto the next row. Each individual component is sized to the size it prefers, and you can justify the set of components on a row to be either left, right, or center justified. The width of the container determines how many components fit on a row.
For example:
String NAMES[] = {
"William", "John", "Sandra",
"Antonin", "Anthony", "David",
"Clarence", "Ruth", "Stephen"};
JFrame flowFrame = new JFrame("FlowLayout");
Container flowPane = flowFrame.getContentPane();
flowPane.setLayout(new FlowLayout(FlowLayout.
RIGHT));
for (int i=0, n=NAMES.length; i<n; i++) {
Button b = new Button(NAMES[i]);
flowPane.add(b);
}
flowFrame.setSize(250, 250);
flowFrame.show();
|
The other alignments are FlowLayout.CENTER (the default) and FlowLayout.LEFT.
The GridLayout manager is another layout manager. It requires you to specify the number of rows and columns to be used. Then, as you add components to the container that uses the GridLayout manager, components are added left-to-right and top-to-bottom.
The GridLayout manager sizes the components equally, filling the entire space provided in its grid of the user interface.
For example:
JFrame gridFrame = new JFrame("GridLayout");
Container gridPane = gridFrame.
getContentPane();
int rows = 3, cols = 3;
gridPane.setLayout(new GridLayout(rows,
cols));
for (int i=0, n=NAMES.length; i<n;
i++) {
Button b = new Button(NAMES[i]);
gridPane.add(b);
}
gridFrame.setSize(250, 250);
gridFrame.show();
|
As long as the number of rows and columns requested in the GridLayout is close to the number of components all is well. Had you only added four components, the screen would be three rows and two columns, with the bottom row empty, though still reserving space.
The BoxLayout manager is like the GridLayout manager with two significant differences: the components are in one row or column, and the components don't have to be the same size. Instead, they can be sized to be their preferred size. In addition to using BoxLayout directly, there is also a Box container that permits you to use the horizontal or vertical BoxLayout.
JFrame vertFrame = new JFrame("Vert
BoxLayout");
Container vertPane = vertFrame.
getContentPane();
vertPane.setLayout(
new BoxLayout(vertPane,
BoxLayout.LINE_AXIS));
for (int i=0, n=NAMES.length;
i<n; i++) {
Button b = new Button(NAMES[i]);
vertPane.add(b);
}
vertFrame.setSize(500, 100);
vertFrame.show();
JFrame horizFrame = new JFrame("Horiz
BoxLayout");
Container horizPane =
horizFrame.getContentPane();
horizPane.setLayout(
new BoxLayout(horizPane,
BoxLayout.PAGE_AXIS));
for (int i=0, n=NAMES.length; i<n;
i++) {
Button b = new Button(NAMES[i]);
horizPane.add(b);
}
horizFrame.setSize(100, 350);
horizFrame.show();
|
The sizing differences aren't noticeable for the column of components PAGE_AXIS. However, with the row of components LINE_AXIS notice that the width of each is just enough to fit the text label. Had the layout manager been a one row GridLayout, each component would be sized the same and you wouldn't necessarily see the label of everyone if the screen was to narrow.
The BorderLayout manager works differently than the rest of the bunch. Instead of adding components directly to the container, you must specify a position within the container. The where to position part of the equation is called the component's constraints. With BorderLayout, these constraints describe which of the five areas of the layout manager to place the component.
Each constraint is defined as a constant of the BorderLayout class: NORTH, SOUTH, EAST, WEST, and CENTER.
A component in the north area of a BorderLayout managed container is positioned at the top of the container. That component is as wide as the container and at its preferred height.
A component in the south area sits at the bottom of the container. It gets sized like a component in the north: As wide as the container and as tall as preferred.
Placing a component in the east area of a BorderLayout managed container causes the component to sit on the right of the container. The width of that component is its preferred width and its height is whatever space is left between the north and south components.
A component in the west area of a BorderLayout managed container sits on the left side of said container. The sizing of that component is the same as one in the east: Preferred width and whatever vertical space is left for height.
The center area takes up the remaining area of the container. That is, any space left after placing components in the north, south, east, and west areas is left for the component in the center area.
Once you decide which layout to use and understand how thecomponents are allocated space, you add the components to the container. Since you must specify constraints for each component, you can't just call the add(Component) method as the earlier examples showed.
Instead, you call add(Component, Object) where the second argument is the constraint for the specific component.
For example:
JFrame borderFrame = new JFrame(
"BorderLayout");
Container borderPane = borderFrame.
getContentPane();
// default for borderPane
// borderPane.setLayout(new
BorderLayout());
borderPane.add(new Button("North"),
BorderLayout.NORTH);
borderPane.add(new Button("South"),
BorderLayout.SOUTH);
borderPane.add(new Button("East"),
BorderLayout.EAST);
borderPane.add(new Button("West"),
BorderLayout.WEST);
borderPane.add(new Button("Center"),
BorderLayout.CENTER);
borderFrame.setSize(250, 250);
borderFrame.show();
|
You do not have to add a component to each area. Instead, you can place a component in the middle, one at the top, and one at the bottom. This leaves the right and left regions empty, so the center component is as wide as the display.
For more complex situations, there are other layout managers like GridBagLayout and SpringLayout. For additional information on these,see the API documentation for the respective class.
Test your knowledge concerning layout managers by taking this quiz.
Making Sense of the Java Class Libraries
The Box and JTabbedPane Classes
Class Box
A Box object is a lightweight container that uses a BoxLayout object as its layout manager. Box provides several class methods that are useful for containers using BoxLayout and even non-Box containers.
A Box object can have either a horizontal or vertical alignment, left to right, or top to bottom, which you can do with static methods upon creation:
Box box;
box = Box.createVerticalBox();
or
Box box;
box = Box.createHorizontalBox();
In addition, the Box class can create several types of invisible components that affect layout, such as glue, struts, and rigid areas.
For instance, if your Box components have a fixed size, use a glue component to control the components' positions. A glue component expands as much as necessary to fill the space between its neighboring components in a box layout.
If you need a fixed amount of space between two components, use a strut. For an invisible component that always takes up the same amount of space, use rigid space.
Some Glue Methods:
createGlue: Creates an invisible "glue" component that can be useful in a Box whose visible components have a maximum width (for a horizontal box) or height (for a vertical box).
createHorizontalGlue: Creates a horizontal glue component. You can think of the glue component as being a gooey substance that expands as much as necessary to fill the space between its neighboring components.
createVerticalGlue: Creates a vertical glue component.
Rigid Space Methods:
createHorizontalStrut(int width): Creates an invisible, fixed-width component. You typically use this method to force a certain amount of space between two components.
createRigidArea(Dimension d): Creates an invisible component that's always the specified size.
createVerticalStrut(int height): Creates an invisible, fixed-height component. In a horizontal box, you might use this method to force the box to be at least the specified height.
Class JTabbedPane
A JTabbedPane is a common Swing user interface component that provides convenient access to multiple panels by clicking on tabs that look much like those used on paper files. Each panel on the tabbed pane has its own set of components.
Tabs can be positioned along the top, bottom, or sides of a JTabbedPane object. Each tab is represented by an index corresponding to the position where it is added. The first tab has an index equal to 0 and the last tab has an index equal to the tab count minus 1.
Create a JTabbedPane object with one of the following three constructors:
JTabbedPane() Creates an empty tabbed pane with a default tab placement of JTabbedPane.TOP and default tab layout policy of JTabbedPane.WRAP_TAB_LAYOUT.
JTabbedPane(int tabPlacement) Creates an empty TabbedPane with the specified tab placement of either: JTabbedPane.TOP, JTabbedPane.BOTTOM, JTabbedPane.LEFT, or JTabbedPane.RIGHT, and a default tab layout policy of JTabbedPane.WRAP_TAB_LAYOUT.
JTabbedPane(int tabPlacement, int tabLayoutPolicy) Creates an empty TabbedPane with the specified tab placement and tab layout policy.
JTabbedPane contains a number of useful methods for adding components, and adding tabs, including tabs with titles or icons:
add(Component component, Object constraints) Adds a component to the tabbed pane.
addTab(String title, Component component) Adds a component represented by a title and no icon.
addTab(String title, Icon icon, Component component, String tip) Adds a component and tip represented by a title and/or icon, either of which can be null.
The following application demonstrates how to create a JTabbedPane object with three tabs. On the first tabbed pane, the Box class and methods are illustrated:
import java.awt.*;
import javax.swing.*;
public class TabbedPaneApp
{
JTabbedPane tabbedPane;
//class constructor
public TabbedPaneApp()
{
tabbedPane = new JTabbedPane(
SwingConstants.TOP);
JFrame frame = new JFrame("TabbedPane");
// Setup the frame to exit when it closes
frame.setDefaultCloseOperation(JFrame.
EXIT_ON_CLOSE);
// Get reference to inner content pane
Container contentPane = frame.
getContentPane();
// Place JTabbedPane in content pane
contentPane.add(tabbedPane,
BorderLayout.CENTER);
// Set frame size
frame.setSize(450, 450);
contentPane.setBackground(Color.white);
// Show frame
frame.show();
// Create vertical box for first tab
Box box = Box.createVerticalBox();
// Create component for top
// Place glue between components
box.add(Box.createVerticalGlue());
box.add(new JButton("Component 1"));
// Create component for middle
box.add(new JTextField("Component 2"));
// Place glue between components
box.add(Box.createVerticalStrut(100));
// Create another component
box.add(new JButton("Component 3"));
// Create another component
box.add(new JButton("Component 4"));
box.add(Box.createVerticalStrut(40));
box.add(new JButton("Component 5"));
// Creates space at the bottom
box.add(Box.createVerticalStrut(40));
// Add box to JTabbedPane
tabbedPane.add(box, "Box Pane");
//Creates two more panes with empty
//panels.
tabbedPane.add(new JPanel(), "Pane 2");
tabbedPane.add(new JPanel(), "Pane 3");
}
public static void main(String args[])
{
TabbedPaneApp tpa = new TabbedPaneApp();
}
}
|
After you compile and run this application, make changes to it:
- Set the tabs so they appear on the left side instead of the top.
- Add a third tab and panel.
- Increase or decrease the struts to change the spacing between components.
- Add additional components to the
Box to see how how this affects the layout.
Program Challenge
For this month's challenge, create a three panel tabbed application. Each panel should have the following characteristics:
- Panel 1
Create a panel that contains a label and a text field. Make the text field as wide as the panel, but limit the height to the text field's preferred height.
- Panel 2
Create a set of components in a single column. Position the first component at the top of the screen. Put the second in the middle, and the third at the bottom. Set each component at its preferred height.
- Panel 3
Create a 3 x 3 grid of components, positioning components only along one of the diagonals. At each position along the diagonal, put two buttons at their preferred size.
Keep in mind that the characteristics described here need to hold true if the frame is resized.
See a possible answer to this solution.
Java Bits
The Purpose of a main Method
When the Java interpreter executes an application through the application's controlling class, it starts by calling the class's main method. The main method then calls the other methods required to run your application. The main method in the Java programming language is similar to the main function in C and C++.
If you try to invoke the Java interpreter on a class that doesn't have a main method, the interpreter refuses to run your program and displays an error message similar to this:
In class NoMain: void main(String args[]) is not defined
The main method can accept a single argument, an array of elements of type String:
public static void main(String[] args){}
This array is the mechanism through which the runtime system passes information to your application.
Note to C and C++ Programmers:
The number and type of arguments passed to the main method in the Java runtime environment differ from the number and type of arguments passed to C and C++'s main function.
New to the Programming Center
Supplement Name Change
The New to Java Programming Center Supplement title has changed to Java Technology Fundamentals.
For More Information
Exploring the AWT Layout Managers
Building an Application: Part 2: Introduction to Inheritance, Panels, and Layouts
Effective Layout Management: Short Course
Class Box
Class JTabbedPane
The main Method
New to Java Programming Center
Building an Application Introduction
Downloading the Java 2 Platform
For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the Java 2, Standard Edition (J2SE) development kit.
IMPORTANT: Please read our Terms of Use and Privacy policies:
Copyright 2002 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA
Have a question about programming? Use Java Online
Support.
- Note -
Sun respects your online time and privacy. The Java Developer Connection
mailing lists are used for internal Sun Microsystems purposes only. You have received this email because you elected to subscribe.
- Feedback -
Comments? Send your feedback on the Java Technology Fundamentals 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
This document is protected by copyright.
JDC Java Technology Fundamentals
April 2002
Sun, Sun Microsystems, Java and J2SE are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.
|