Chapter 15. Swing

HOW do you write a program in the Java programming language with a graphical user interface? The short answer is the Swing toolkit! This chapter gives you a brief overview of the graphical capabilities of the core Java platform with a special focus on Swing.

This chapter does not show how to implement these features. For a “how-to” on using the Swing toolkit, see Creating a GUI with JFC/Swing.[1]

A Brief Introduction to the Swing Package

This section gives you a brief introduction to the capabilities of the Java SE platform that pertain to developing programs with graphical user interfaces (GUIs). Next, it shows you a demo (sample code provided) that showcases many of these features.

The next section, Swing Features (page 470), discusses these capabilities in more detail.

What Is Swing?

To create a Java program with a graphical user interface (GUI), you’ll want to learn about Swing.

The Swing toolkit includes a rich set of components for building GUIs and adding interactivity to Java applications. Swing includes all the components you would expect from a modern toolkit: table controls, list controls, tree controls, buttons, and labels.

Swing is far from a simple component toolkit, however. It includes rich undo support, a highly customizable text package, integrated internationalization and accessibility support. To truly leverage the cross-platform capabilities of the Java platform, Swing supports numerous look and feels, including the ability to create your own look and feel. The ability to create a custom look and feel is made easier with Synth, a look and feel specifically designed to be customized. Swing wouldn’t be a component toolkit without the basic user interface primitives such as drag and drop, event handling, customizable painting, and window management.

Swing is part of the Java Foundation Classes (JFC). The JFC also include other features important to a GUI program, such as the ability to add rich graphics functionality and the ability to create a program that can work in different languages and by users with different input devices.

Swing GUI Components

The Swing toolkit includes a rich array of components: from basic components, such as buttons and checkboxes, to rich and complex components, such as tables and text. Even deceptively simple components, such as text fields, offer sophisticated functionality, such as formatted text input or password field behavior. There are file browsers and dialogs to suit most needs, and if not, customization is possible. If none of Swing’s provided components are exactly what you need, you can leverage the basic Swing component functionality to create your own.

Java 2D API

To make your application stand out; convey information visually; or add figures, images, or animation to your GUI, you’ll want to use the Java 2D API. Because Swing is built on the 2D package, it’s trivial to make use of 2D within Swing components. Adding images, drop shadows, compositing—it’s easy with Java 2D.

Pluggable Look-and-Feel Support

Any program that uses Swing components has a choice of look and feel. The JFC classes shipped by Sun and Apple provide a look and feel that matches that of the platform. The Synth package allows you to create your own look and feel. The GTK+ look and feel makes hundreds of existing look and feels available to Swing programs.

A program can specify the look and feel of the platform it is running on, or it can specify to always use the Java look and feel, and without recompiling, it will just work. Or, you can ignore the issue and let the UI manager sort it out.

Data Transfer

Data transfer, via cut, copy, paste, and drag and drop, is essential to almost any application. Support for data transfer is built into Swing and works between Swing components within an application, between Java applications, and between Java and native applications.

Internationalization

This feature allows developers to build applications that can interact with users worldwide in their own languages and cultural conventions. Applications can be created that accept input in languages that use thousands of different characters, such as Japanese, Chinese, or Korean.

Swing’s layout managers make it easy to honor a particular orientation required by the UI. For example, the UI will appear right to left in a locale where the text flows right to left. This support is automatic: You need only code the UI once and then it will work for left to right and right to left, as well as honor the appropriate size of components that change as you localize the text.

Accessibility API

People with disabilities use special software—assistive technologies—that mediates the user experience for them. Such software needs to obtain a wealth of information about the running application in order to represent it in alternate media: for a screen reader to read the screen with synthetic speech or render it via a Braille display, for a screen magnifier to track the caret and keyboard focus, for on-screen keyboards to present dynamic keyboards of the menu choices and toolbar items and dialog controls, and for voice control systems to know what the user can control with his or her voice. The accessibility API enables these assistive technologies to get the information they need and to programmatically manipulate the elements that make up the graphical user interface.

Undo Framework API

Swing’s undo framework allows developers to provide support for undo and redo. Undo support is built in to Swing’s text component. For other components, Swing supports an unlimited number of actions to undo and redo, and is easily adapted to an application. For example, you could easily enable undo to add and remove elements from a table.

Flexible Deployment Support

If you want your program to run within a browser window, you can create it as an applet and run it using Java Plug-in, which supports a variety of browsers, such as Internet Explorer, Firefox, and Safari. If you want to create a program that can be launched from a browser, you can do this with Java Web Start. Of course, your application can also run outside of browser as a standard desktop application.

For more information on deploying an application, see Chapters 17 and 18.

This chapter provides an overview of Swing capabilities, beginning with a demo that showcases many of these features. When you are ready to begin coding, the “Creating a GUI with JFC/Swing” online tutorial provides the programming techniques to take advantage of these features.

Let’s examine a demo that shows many of these features.

A Swing Demo

Run the PasswordStore demo[2] for an illustration of some of Swing’s rich feature set. PasswordStore allows the user to manage login information for various hosts. It also generates passwords, evaluates the effectiveness of a password, and allows you to store notes about a particular host or assign an icon to represent the host.

The following highlights some of the specific features of the PasswordStore application.[3]

Host Info

At program launch, the list of hosts is displayed in a Swing list component. Using the View menu, the view can be toggled between the table and the list.

In both views, the Host/Account Filter text field can be used to dynamically restrict the entries to those where the host or account name contains the typed string.

List View

The Swing list component can be customized to include visual data. As shown in Figure 15.1, an optional miniature icon to the left of the host name represents the host. The graphic to the right uses color and proportional fill to reflect the strength of the password (red = poor, yellow = fair, green = good). The bar changes dynamically as the user enters/modifies the password in the text field below. The user has typed the text “oo” in the filter text field, which matches two entries: Heirloom Seeds and Pacific Zoo Shop.

Host Info (List View) and Filter text field.

Figure 15.1. Host Info (List View) and Filter text field.

Table View

The Swing table component (Figure 15.2) allows the user to rearrange the columns by dragging the column header. Also, a column can be sorted by clicking the column header. If the column you click on isn’t highlighted as the primary sorted column, it will become the primary sorted column in ascending order. Clicking on the primary sorted column toggles the sort order. For example, if column 1 isn’t selected, clicking on it will make it the selected column and the data is sorted in ascending order. Clicking column 1 again will sort the data in descending order. Clicking on column 2 will make column 2 the primary column in ascending order.

Host Info (Table View).

Figure 15.2. Host Info (Table View).

Details/Notes Tabbed Pane

The tabbed pane below the host info allows the user to choose between the Details panel and the Notes text pane, keeping the overall footprint of the window smaller and less overwhelming.

Details Panel

The icon area on the left can be assigned an image by either dragging an image (jpg, png, gif, or tif) to the area or by clicking the image well and bringing up a file browser.

The text fields—used to enter or modify the host name, login, and password—support cut/copy, paste, drag, drop, undo, and redo.

As the user enters or modifies the password, the 2D bar chart dynamically displays the distribution of the password. If the list view is currently displayed, the corresponding colored bar in the list also changes dynamically.

Notes Text Pane

This is the text component where the user can save notes about the selected host. If the text pane contains a URI, Swing’s text component provides the ability to click on the URI and a browser window automatically opens to that location.

Wizzy 2D Graphics

PasswordStore uses customized graphics in several ways to enhance the UI: In the list view, images are used to represent each host; a colored bar, the Strength Visualizer, represents the effectiveness of a password; and a dynamic bar chart, the Password Visualizer, displays the distribution of a password. When you add an image, whether by dragging and dropping it into the image well (in the Details panel) or by clicking the well and bringing up the file browser, a mini-icon is automatically generated for the list view (Figure 15.3).

2D graphics used.

Figure 15.3. 2D graphics used.

Note

This demo is meant to be illustrative only and not meant to be used for real analysis of passwords.

Multiple Look and Feels

This provides the ability to switch between three look and feels using the View menu: Java (called Metal), Motif/CDE, and the native look and feel: Windows on Microsoft Windows, Aqua on Mac OS X, and so on.

Undo and Redo

Undo and redo works on text, as you would expect, but it also works on actions. For example, you can generate a password using the Account > Generate Password menu, and if you don’t like the new password you can undo it using Edit > Undo or the control-Z shortcut. Similarly, you can redo the undo using Edit > Redo or the control-Y shortcut.

The PasswordStore demo has a reasonable level of complexity for a small Swing application and shows a sampling of Swing’s capabilities. The source code[4] is available for download, but it is outside the scope of this chapter to discuss the implementation in detail. For more information on the architecture and implementation of this application, see Scott Violet’s Excellent Blog[5] on java.net.

Note

If PasswordStore were a production application, it would most likely encrypt the password database; however, due to legal restrictions on distributing information of that nature, it is not included here.

Swing Features

PasswordStore shows some of the rich functionality of a particular Swing application. This lesson discusses the general features available to applications using the Java SE platform and, in particular, the Swing toolkit.

A Visual Guide to Swing Components

This section shows Swing components in both Java and Windows look and feel.

Basic Controls (Table 15.1)

Simple components that are used primarily to get input from the user; they may also show simple state.

Table 15.1. Basic Controls

Name

Java Look and Feel

Windows Look and Feel

JButton

Basic Controls
Basic Controls

JCheckBox

Basic Controls
Basic Controls

JComboBox

Basic Controls
Basic Controls

JList

Basic Controls
Basic Controls

JMenu

Basic Controls
Basic Controls

JRadioButton

Basic Controls
Basic Controls

JSlider

Basic Controls
Basic Controls

JSpinner

Basic Controls
Basic Controls

JPasswordField

Basic Controls
Basic Controls

Interactive Displays of Highly Formatted Information (Table 15.2)

These components display highly formatted information that (if you choose) can be modified by the user.

Table 15.2. Interactive Displays of Highly Formatted Information

Java Look and Feel

Windows Look and Feel

JColorChooser

Interactive Displays of Highly Formatted Information
Interactive Displays of Highly Formatted Information

JEditorPane and JTextPane

Interactive Displays of Highly Formatted Information
Interactive Displays of Highly Formatted Information

JFileChooser

Interactive Displays of Highly Formatted Information
Interactive Displays of Highly Formatted Information

JTable

Interactive Displays of Highly Formatted Information
Interactive Displays of Highly Formatted Information

JTextArea

Interactive Displays of Highly Formatted Information
Interactive Displays of Highly Formatted Information

JTree

Interactive Displays of Highly Formatted Information
Interactive Displays of Highly Formatted Information

Uneditable Information Displays (Table 15.3)

These components exist solely to give the user information.

Table 15.3. Uneditable Information Displays

Name

Java Look and Feel

Windows Look and Feel

JLabel

Uneditable Information Displays
Uneditable Information Displays

JProgressBar

Uneditable Information Displays
Uneditable Information Displays

JSeparator

Uneditable Information Displays
Uneditable Information Displays

JToolTip

Uneditable Information Displays
Uneditable Information Displays

Top-Level Containers (Table 15.4)

At least one of these components must be present in any Swing application.

Table 15.4. Top-Level Containers

Name

Java Look and Feel

Windows Look and Feel

JApplet

Top-Level Containers
Top-Level Containers

JDialog

Top-Level Containers
Top-Level Containers

JFrame

Top-Level Containers
Top-Level Containers

General-Purpose Containers (Table 15.5)

These general-purpose containers are used in most Swing applications.

Table 15.5. General-Purpose Containers

Java Look and Feel

Windows Look and Feel

JPanel

General-Purpose Containers
General-Purpose Containers

JScrollPane

General-Purpose Containers
General-Purpose Containers

JSplitPane

General-Purpose Containers
General-Purpose Containers

JTabbedPane

General-Purpose Containers
General-Purpose Containers

JToolBar

General-Purpose Containers
General-Purpose Containers

Special-Purpose Containers (Table 15.6)

These special-purpose containers play specific roles in the UI.

Table 15.6. Special-Purpose Containers

Java Look and Feel

Windows Look and Feel

JInternalFrame

Special-Purpose Containers
Special-Purpose Containers

JLayeredPane

Special-Purpose Containers
Special-Purpose Containers

JRootPane

Special-Purpose Containers
Special-Purpose Containers

Pluggable Look and Feel

The Swing toolkit allows you to decide how to configure the particular look and feel of your application. If you don’t specify a look and feel, the Swing UI manager figures out which one to use. The options for setting a look and feel include:

  1. Leave it up to the Swing UI manager. If a particular look and feel is not specified by the program, Swing’s UI manager checks whether the user has specified a preference. If that preference hasn’t been specified or isn’t available, the default look and feel is used. The default look and feel is determined by the supplier of the JRE. For the JRE that Sun provides, the Java look and feel (called Metal) is used. The Java look and feel works on all platforms.

  2. Use the look and feel of the native platform. If the application is running on a Microsoft Windows XP machine, the Windows look and feel is used. On Mac OS platforms, the Aqua look and feel is used. On UNIX platforms, such as Solaris or Linux, either the GTK+ look and feel or the CDE/Motif look and feel is used, depending on the user’s desktop choice.

  3. Specify a particular look and feel. Swing ships with four look and feels: Java (also called Metal), Microsoft Windows, GTK+, and CDE/Motif. The GTK+ look and feel requires a theme, and there are many available for free on the Internet.

  4. Create your own look and feel using the Synth package.

  5. Use an externally provided look and feel.

As shown in Figures 15.4 to 15.8, PasswordStore offers a choice of three look and feels. The Alloy and Synthetica look and feels have been provided courtesy of Incors.[6]

Java look and feel.

Figure 15.4. Java look and feel.

Windows look and feel.

Figure 15.5. Windows look and feel.

CDE/Motif look and feel.

Figure 15.6. CDE/Motif look and feel.

Default Alloy look and feel.

Figure 15.7. Default Alloy look and feel.

Synthetica look and feel.

Figure 15.8. Synthetica look and feel.

Drag and Drop and Data Transfer

The Swing toolkit supports the ability to transfer data between components within the same Java application, between different Java applications, and between Java and native applications. Data can be transferred via a drag and drop gesture, or via the clipboard using cut, copy, and paste.

Drag and Drop

Drag-and-drop support can be easily enabled for many of Swing’s components (sometimes with a single line of code). For example, it’s trivial to enable drag and drop and copy and paste support for JTable, Swing’s table component. All you need to provide is the data representing the selection and how to get your data from the clipboard—that’s it!

Cut, Copy, and Paste

Most of the text-based components, such as editor pane and text field, support cut/copy and paste out of the box. Of course, menu items need to be created and “wired up” to the appropriate actions. Other components, such as list and tree, can support cut, copy, and paste with some minimal work.

PasswordStore supports data transfer in a variety of ways:

  • The text in both the list and the table view supports cut, copy, and paste.

  • The text fields in the Details panel, the Filter text field, and the Notes text pane support cut/copy, paste, and drag and drop.

  • The Company icon region in the Details panel accepts a dropped image (jpg, png, gif, or tif).

Internationalization and Localization

Internationalization is the process of designing an application so that the user can run it using his or her cultural preferences without modifying or recompiling the code. These cultural preferences, collectively known as locale, include (but aren’t limited to): language, currency formatting, time and date formatting, and numeric formatting.

An internationalized program is designed so that text elements, such as status messages and GUI component labels, are stored outside the source code in resource bundles and retrieved dynamically. Separating the locale-specific information from the code is what allows a program to run in different languages and with different preferences without having to recompile.

Localization is the process of translating the text to a particular language and adding any locale-specific components. When an application is localized to a language and you run the app in that locale, Swing grabs the localized strings from the resource bundle and the layout manager resizes the component accordingly.

For example, an English-speaking person writes an application following the rules of internationalization; later, that application is localized to Japanese and Spanish. When a user with the Language System Preference set to Japanese runs the application, Swing detects this. When the application appears, the menus, labels, buttons, and so on, show Japanese text, and the components are scaled accordingly. If that user then quits the program, sets the language system preference to Spanish, and re-launches the application, the application appears in Spanish, scaled according to the new character set.

Swing’s layout managers understand how locale affects a UI—it is not necessary to create a new layout for each locale. For example, in a locale where text flows right to left, the layout manager will arrange components in the same orientation, if specified. Bidi text (mixed directional text, used by Hebrew and Arabic, for example) is supported as well.

Every program should be designed with internationalization in mind: GUI component labels, status messages, currency, date, phone, and address formats should not be hardcoded into programs. Once a program has been internationalized, a language expert can perform the actual translation at a later date without requiring any recompiling.

As Figures 15.9 and 15.10 show, PasswordStore has been localized to Japanese and Arabic.

PasswordStore in Japanese.

Figure 15.9. PasswordStore in Japanese.

PasswordStore in Arabic.

Figure 15.10. PasswordStore in Arabic.

Accessibility

Assistive technologies exist to enable people with permanent or temporary disabilities to use the computer. This includes a wide variety of techniques and equipment—voice interfaces, magnifiers, screen readers, closed captioning, keyboard enhancements, and so on. In many countries, including the United States, Australia, Canada, and the European Union, there are laws requiring that programs function smoothly with assistive technologies.[7]

A certain level of accessibility is built in to all Swing components, but full accessibility can be achieved by following some simple rules. For example, assign tooltips, keyboard alternatives, and textual descriptions for images, wherever possible.

The PasswordStore demo follows the rules set out for accessibility. In Figure 15.11, you can see an example of tooltip text.

PasswordStore with a tooltip.

Figure 15.11. PasswordStore with a tooltip.

Integrating with the Desktop

The Desktop API,[8] introduced in version 6 of the Java Platform, Standard Edition (Java SE), enables Java applications to integrate seamlessly with the desktop. Three types of integration are supported:

  • The ability to launch the host system’s default browser with a specific Uniform Resource Identifier (URI).

  • The ability to launch the host system’s default e-mail client.

  • The ability to launch applications to open, edit, or print files associated with those applications.

You can see this in the PasswordStore demo in the Notes text pane. Click on the link that is displayed in Figure 15.12—it opens the specified URI in the default browser.

Click on the URI and it opens in the default browser.

Figure 15.12. Click on the URI and it opens in the default browser.

For more information, see the Using the Desktop API in Java SE 6 article.[9]

System Tray Icon Support

The desktop of some platforms, such as Microsoft Windows, includes a system tray, as shown in Figure 15.13.

System tray on Windows XP.

Figure 15.13. System tray on Windows XP.

On Microsoft Windows, it is called the “Taskbar Status Area.” On Gnome, the “Notification Area,” and on KDE, the “System Tray.” Whatever it may be called, the system tray is shared by all applications.

On platforms where it is supported, an application may insert a mini-icon, called a tray icon, into the system tray. This icon can be used to notify the user of a change in the application’s status or a need to take a particular action. Clicking the tray icon can bring up the application window. A popup menu and a tooltip can also be attached to the tray icon.

System tray support[10] was added in version 6 of Java SE. For more information, see the New System Tray Functionality in Java SE 6 article.[11]

Questions: Graphical User Interfaces

Questions

1.

Does Swing support multiple look and feels?

2.

True or False: The Java look and feel is the only look and feel that works across all platforms.

3.

True or False: Swing’s Undo Framework supports an unlimited number of actions to undo (and redo).

4.

Can Swing’s list component (JList) only display text?

5.

Which Swing component provides undo support out of the box?

6.

Can Java applications interact with the native desktop components?

7.

Can I deploy my Swing application on the Web?

Answers

You can find answers to these Questions at:

tutorial/ui/features/QandE/answers.html


[1] /tutorial/uiswing/index.html

[2] Click the launch button found on tutorial/ui/overview/demo.html.

[3] The dice, flower, pill, and pocketwatch images used in the demo are courtesy of http://www.freeimages.co.uk. The polar bear and cubs image by Steve Amstrup and the mountain image are courtesy of http://www.fws.gov. The spiral galaxy image is courtesy of http://grin.hq.nasa.gov.

[4] tutorial/ui/overview/PasswordStore-1.0-src.zip

[7] For more information, see Sun Microsystems’ Accessibility Program—Relevant Laws, http://www.sun.com/access/background/laws.html.

[8] docs/api/java/awt/Desktop.html

[10] docs/api/java/awt/SystemTray.html

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.170.239