Sun Java Solaris Communities My SDN Account Join SDN
 
Java Technology Fundamentals Newsletter Index

CardLayout Manager and JTabbedPane, Creating a Sorted JList Component, and More - Java Technology Fundamentals - June 22, 2006



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

Note: For the code in this issue of Fundamentals to compile, you need to use the JDK 5.0 software.

This issue covers:

Java Programming Language Basics
Making Sense of the Java Classes & Tools
Java Bits
Program Challenge
What's New on Java Studio Creator
Tutorials and Tips From NetBeans.org
Sun's Technology Courses
Sun Developer Expert Assistance
Free Developer Tools
For More Information

Java Programming Language Basics
The CardLayout Manager and JTabbedPane

In this article, you'll take a look at the CardLayout layout manager and JTabbedPane component of the Swing component set. The introduction of the JTabbedPane component in the Java 2 Platform, Standard Edition (J2SE) 1.1 practically made the need for CardLayout obsolete, but it's still there and not deprecated, so let's take a look at the CardLayout layout manager.

The CardLayout layout manager is not really a layout manager as most programmers think of one. What it does is let you define any number of "cards" containing, typically, a logically related collection of components. Figure 1 shows a typical card-based configuration window, one that wasn't necessarily implemented using Java technology but could easily be. What CardLayout provides you with is the areas marked History, Saved Forms, and Passwords, including what appears for each selected tab. It doesn't provide the means to swap cards, only to display each one.

The following program demonstrates the use of CardLayout with five cards containing a single button each.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutTest {
  public static void main(String args[]) {
    Runnable runner = new Runnable() {
      public void run() {
        final JFrame frame = new JFrame("Card Layout");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final CardLayout layout = new CardLayout();
        frame.setLayout(layout);
        ActionListener listener = new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            layout.next(frame.getContentPane());
          }
        };
        for (int i=0; i<5; i++) {
          String label = "Card " + i;
          JButton button = new JButton(label);
          frame.add(button, label);
          button.addActionListener(listener);
        }
        frame.setSize(300, 200);
        frame.setVisible(true);
      }
    };
    EventQueue.invokeLater(runner);
  }
}

Notice the add() method used to add cards to a CardLayout. As with the more familiar BorderLayout, you need to use the constraints variety to pass a card name -- in addition to the card itself -- to the layout manager. Later, you can refer to your cards by name instead of by number, for example. Also note that a CardLayout variable was created. Typically, you simply have a new SomeLayoutManager() method call within the brackets of your setLayout() call. But when using CardLayout, you must refer to your CardLayout object after you have created it to change cards. This is why you need the variable to keep a reference to it.

To demonstrate the ability to cycle through the cards, this program was made to listen for action from any of the buttons; the next card is displayed whenever you click on one of the buttons. The next() method tells the application to show the next card under its control for the container. When it reaches the last card and you ask it to show the next() card again, it simply cycles back to the beginning. See Figure 2.

You probably expected to see a full-fledged rendering of the five different cards, as in Figure 1, including the clickable tabs to select any one of the cards. Unfortunately, CardLayout does not do this for you. It is just a layout manager. You must either implement the tabs and card outlines yourself or use the JTabbedPane container. The following program expands on the previous example to demonstrate the usage of JTabbedPane:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TabbedPaneTest {
  public static void main(String args[]) {
    Runnable runner = new Runnable() {
      public void run() {
        JFrame frame = new JFrame("JTabbedPane");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTabbedPane jtp = new JTabbedPane();
        frame.add(jtp, BorderLayout.CENTER);
        for (int i=0; i<5; i++) {
          JButton button = new JButton("Card " + i);
          jtp.add("Btn " + i, button);
        }
        frame.setSize(300, 200);
        frame.setVisible(true);
      }
    };
    EventQueue.invokeLater(runner);
  }
}

Each card is added with the addTab() method, instead of the plain add() method. Also, notice that the event-handling code to move between cards is automatically performed by the JTabbedPane. Because of this added value of JTabbedPane, you'll find yourself almost never using CardLayout. Figure 3 shows the output of the program's new and improved version.

The JTabbedPane has many additional options. For instance, it supports the display of images on the tabs and tool tips when the mouse is rested over a tab with:

  • addTab(String title, Icon icon, Component component)
  • addTab(String title, Icon icon, Component component, String tip)

You can also move the tabs to different sides of the container with setTabbedPlacement() using one of the class constants -- TOP, BOTTOM, LEFT, and RIGHT -- to determine the side to place them on.

One other option says what to do with the tabs when they are too wide for one line. Using setTabLayoutPolicy(), you can have them wrap to multiple levels with the class constant WRAP_TAB_LAYOUT. Or you can have them scroll on one line with SCROLL_TAB_LAYOUT. Figures 4 and 5 show the two different layout policies.



Keep in mind that what goes on each tab is just one component. So if you want to create a tab like that in Figure 1, you'd have to place the components within their own container (JPanel) with its own layout manager before placing them within the tab of the JTabbedPane.

Making Sense of the Java Classes & Tools
Vocal Java
By Jeff Friesen from Java.net  

Several years back, I configured a blind gentleman's Microsoft- Windows-based computer to vocally identify the window under the mouse pointer. As he moved the pointer around the screen, the computer spoke the name of the underlying window. I have never forgotten how beneficial that speaking computer was to that gentleman's life.

My earlier work on configuring a Windows-based computer to speak inspired me to create an equivalent assistive technology for use in Java technology contexts. This technology transparently helps blind users interact with Swing-based graphical user interfaces (GUIs). It also can be used with Abstract Windowing Toolkit- or AWT-based GUIs, provided that those GUIs are made accessible to the technology.

This article introduces my Speaker assistive technology. Because Speaker depends on Sun's Java Speech API -- Sun's preferred choice for supporting various speech technologies on any Java platform -- and FreeTTS -- my preferred Java Speech implementation for making Speaker speak -- the article first reviews those technologies. I developed and tested this article's code with Sun's J2SE 5.0 SDK and FreeTTS 1.2.1. Windows 98 SE was the underlying platform.

Java Speech API Overview

The Java Speech API is a specification that describes a standard set of classes and interfaces for integrating speech technologies into Java software. Sun released version 1.0 (the only version to date) of this specification on October 26, 1998. It is important to keep in mind that Java Speech is only a specification -- no implementation is included.

Java Speech supports two kinds of speech technologies: speech recognition and speech synthesis. Speech recognition converts speech to text. Special input devices called recognizers make speech recognition possible. In contrast, speech synthesis converts text to speech. Special output devices called synthesizers make speech synthesis possible.

The javax.speech package defines the common functionality of recognizers, synthesizers, and other speech engines. The package javax.speech.recognition extends this basic functionality for recognizers. Similarly, javax.speech.synthesis extends this basic functionality for synthesizers.

Read the rest of the article
 

Java Bits
Creating a Sorted JList Component
By John O'Conner  

My personal digital assistant (PDA) provides contact information for friends, family, and coworkers. The PDA allows me to find a person's phone number easily by searching on that person's name. The information is sorted according to standard dictionary-sort order for the contact's name. That is, the name Michele comes before Robert in the list. Without this sort order, I would have difficulty finding names quickly and easily.

Java technology programmers often use the javax.swing.JList component to provide list views of similar data, whether it be a phone contact list or a grocery list. Despite the convenience of this user interface (UI) component, a JList doesn't sort its elements. It displays them in the same order provided by its underlying javax.swing.ListModel interface. Neither the ListModel interface nor the javax.swing.DefaultListModel class provides sorted data. Instead, the default model provides its content in the same order as you enter it. If you enter unsorted data -- for example, the letters B, C, and A -- the model provides it to list components without sorting it to either ascending order -- A, B, C -- or to descending order -- C, B, A. Lists are appropriate UI components for many applications, but an unsorted list has limited usefulness.

This article describes how to produce sorted lists and uses a simple application to demonstrate concepts. You can download all the demo source code using the link at the end of this article. Although I developed the demo source as a NetBeans IDE 5.0 project, the demo's ANT script does not require that you use that IDE to compile or execute the application. The demo application uses the decorator design pattern to provide additional functionality to the ListModel object you already use. This allows you to use and benefit from a sorted model after making only minimal changes to your existing application code base. You really can have your list model and sort it too.

Read the rest of this article
 

Program Challenge

The content of the tab of a JTabbedPane is not limited to just text. Create a program that displays an icon next to the text where the tabs are labeled with some of the colors of the Color class. For each tab, associate a mnemonic of the first character of the color name. For responding when the user selects a new tab, you associate a ChangeListener with the JTabbedPane. Have your program also print out a message when the tab selection changes.

See possible solution:


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

public class TabSelection {
  static Color colors[] = {Color.RED, Color.ORANGE, Color.YELLOW,
    Color.GREEN, Color.BLUE, Color.MAGENTA};
  static String titles[] = {"Red", "Orange", "Yellow", "Green", 
                                            "Blue", "Magenta"};
  static int mnemonic[] = 
                   {KeyEvent.VK_R, KeyEvent.VK_O, KeyEvent.VK_Y, 
                    KeyEvent.VK_G, KeyEvent.VK_B, KeyEvent.VK_M};

  static void add(
            JTabbedPane tabbedPane, String label, int mnemonic) {
    int count = tabbedPane.getTabCount();
    JButton button = new JButton(label);
    button.setBackground(colors[count]);
    tabbedPane.addTab(label, 
                     new DiamondIcon(colors[count]), button, label);
    tabbedPane.setMnemonicAt(count, mnemonic);
  }

  public static void main(final String args[]) {
    Runnable runner = new Runnable() {
      public void run() {
        JFrame frame = new JFrame("Tab Selection");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.setTabLayoutPolicy(
                               JTabbedPane.SCROLL_TAB_LAYOUT);
        for (int i=0, n=titles.length; i<n; i++) {
          add(tabbedPane, titles[i], mnemonic[i]);
        }

        ChangeListener changeListener = new ChangeListener() {
          public void stateChanged(ChangeEvent changeEvent) {
            JTabbedPane sourceTabbedPane = 
                              (JTabbedPane)changeEvent.getSource();
            int index = sourceTabbedPane.getSelectedIndex();
            System.out.println ("Tab changed to: " 
                             + sourceTabbedPane.getTitleAt(index));
          }
        };
        tabbedPane.addChangeListener(changeListener);

        frame.add(tabbedPane, BorderLayout.CENTER);
        frame.setSize(400, 150);
        frame.setVisible(true);
      }
    };
    EventQueue.invokeLater(runner);
  }
}

import javax.swing.*;
import java.awt.*;
public class DiamondIcon implements Icon {
  private Color color;
  private boolean selected;
  private int width;
  private int height;
  private Polygon poly;
  private static final int DEFAULT_WIDTH = 10;
  private static final int DEFAULT_HEIGHT = 10;
  public DiamondIcon(Color color) {
    this (color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT);
  }
  public DiamondIcon(Color color, boolean selected) {
    this (color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT);
  }
  public DiamondIcon (Color color, boolean selected, 
                                 int width, int height) {
    this.color = color;
    this.selected = selected;
    this.width = width;
    this.height = height;
    initPolygon();
  }
  private void initPolygon() {
    poly = new Polygon();
    int halfWidth = width/2;
    int halfHeight = height/2;
    poly.addPoint (0, halfHeight);
    poly.addPoint (halfWidth, 0);
    poly.addPoint (width, halfHeight);
    poly.addPoint (halfWidth, height);
  }
  public int getIconHeight() {
    return height;
  }
  public int getIconWidth() {
    return width;
  }
  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.setColor (color);
    g.translate (x, y);
    if (selected) {
      g.fillPolygon (poly);
    } else {
      g.drawPolygon (poly);
    }
    g.translate (-x, -y);
  }
}

What's New on Java Studio Creator
Blending Images and Text on a Web Page in Sun Java Studio Creator 2
By Tor Norbye  

For application web pages you create in the Sun Java Studio Creator 2 IDE (or the Sun Java Studio Creator 2 IDE, Update 1), you might want to have background images on which you superimpose some text. However, when you run the application, although the background images give the page a nice look, it's often the case that the text on top of the images is hard to read or even lost.

This tech tip shows you some tricks for getting around the problem of text vanishing within a background image. For example, you'll learn how to insert translucent masks between the text and the background so that the text stands out. To get you there, the tip covers the following:

  1. Adding an Image to an Application
  2. Setting a Background Image for a Page
  3. Using a Semi-Translucent Mask to Increase Visibility
  4. Placing and Sizing the Translucent Image in Three-Dimensional Space

Read the article
 

Tutorials and Tips on NetBeans.org

This tutorial is intended as an introduction to using the built-in Concurrent Versions System (CVS) module in NetBeans IDE 5.0. This tutorial assumes no familiarity with the CVS modules from previous IDE releases and will not address differences between the CVS support in version 5.0 and previous versions of the NetBeans IDE. This tutorial assumes that you have access to a CVS repository.

Expected duration: 30 minutes

Introduction

In this tutorial, you will create a new project based on your CVS repository and explore how to use the CVS tools available in NetBeans IDE 5.0.

Prerequisites

This tutorial assumes you have a basic familiarity with the NetBeans IDE 5.0 and that you have access to a CVS repository. We will use this IDE's sources repository as an example.

Software Needed for the Tutorial

Before you begin, install the following software on your computer:

  • NetBeans IDE 5.0
  • Java Standard Development Kit (JDK) version 1.4.2 or 5.0
    (See "For More Information" for download links.)

Notations Used in the Tutorial

<NETBEANS_HOME> -- the NetBeans IDE installation directory <PROJECT_HOME> -- directory that contains the project you create

Tutorial Exercises

  • Exercise 1: Checking out your repository
  • Exercise 2: Understanding the notations
  • Exercise 3: Updating your files
  • Exercise 4: Showing changes
  • Exercise 5: Committing changes
  • Exercise 6: Reverting changes

Read the tutorial and do the exercises

Sun's Technology Courses
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, multitier application. Students use graphical user interface (GUI) design principles and network communications capabilities to code a functional Java technology application that interacts with a networked database server. The significant amount of lab time illustrates the workshop nature of this course.

Format

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

Sign up
 

Sun Developer Expert Assistance

Need help with a programming problem? The Sun Developer Expert Assistance program offers the following:

  • Diagnostic advice
  • Sanity check on coding approach
  • Workarounds to current problems
  • Guidance on best practices
  • Pointers to relevant sample applications and documentation that address the issue

Ask a question about any aspect of the supported products and technologies shown, and an engineer will respond to you by email within 24 hours, either with an answer or a commitment to track down the information.

Supported Products and Technologies

  • NetBeans 5.0
  • J2SE 1.4.2, 5.0
  • Java Studio Creator 2
  • J2EE SDK 5.0 (Sun AS 9)
  • Java Studio Enterprise 7/8
  • Sun Studio 10/11 for Solaris

Learn more

For More Information

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

Reader Feedback

Manage your current newsletter subscriptions:

You can subscribe to these and other publications on the Newsletters and Publications page.

Free Developer Tools
Join Sun Developer Network to get your free 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.

Rate and Review
Tell us what you think of the content of this page.
Excellent   Good   Fair   Poor  
Comments:
Your email address (no reply is possible without an address):
Sun Privacy Policy

Note: We are not able to respond to all submitted comments.