58
452 Trail: Graphical User Interfaces How do you write a program in the Java programming language with a graphical user interface? The short answer — the Swing toolkit! This trail gives you a brief overview of the graphical capabilities of the core Java platform with a special focus on Swing. This trail, part of The Java Tutorial, does not show how to implement these features. For a "how- to" on using the Swing toolkit, see Creating a GUI with JFC/Swing . A Brief Introduction to Swing provides a high-level table of the capabilities provided by the Swing toolkit and other Java Foundation Classes. A demo is provided that showcases many of these capabilities. Swing Features explains the basic features of Swing, such as drag and drop, internationalization, pluggable look and feel, and provides a visual list of the components available in the Swing toolkit. Lesson: A Brief Introduction to the Swing Package This lesson 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 lesson, Swing Features discusses these capabilities in more detail. What is Swing? The Swing toolkit, shipped as part of the Java SE platform, provides a rich set of GUI components. But Swing offers much more functionality than a collection of standard widgets. This section takes a look at Swing's rich functionality. A Swing Demo A rich multi-class Swing application, PasswordStore, is presented. The source code is provided as a reference to the user. 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.

Graphical User Interfaces (Swing)

Embed Size (px)

Citation preview

Page 1: Graphical User Interfaces (Swing)

452

Trail: Graphical User Interfaces

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

This trail, part of The Java Tutorial, does not show how to implement these features. For a "how-to" on using the Swing toolkit, see Creating a GUI with JFC/Swing.

A Brief Introduction to Swing provides a high-level table of the capabilities provided by the Swing toolkit and other Java Foundation Classes. A demo is provided that showcases many of these capabilities.

Swing Features explains the basic features of Swing, such as drag and drop, internationalization, pluggable look and feel, and provides a visual list of the components available in the Swing toolkit.

Lesson: A Brief Introduction to the Swing Package This lesson 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 lesson, Swing Features discusses these capabilities in more detail.

What is Swing?

The Swing toolkit, shipped as part of the Java SE platform, provides a rich set of GUI components. But Swing offers much more functionality than a collection of standard widgets. This section takes a look at Swing's rich functionality.

A Swing Demo

A rich multi-class Swing application, PasswordStore, is presented. The source code is provided as a reference to the user.

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.

Page 2: Graphical User Interfaces (Swing)

453

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.

The following list shows some of the features that Swing and the Java Foundation Classes provide.

Swing GUI Components The Swing toolkit includes a rich array of components: from basic components, such as buttons and check boxes, 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 2DTM 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

Page 3: Graphical User Interfaces (Swing)

454

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 the Deployment trail in this tutorial.

This trail 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 trail provides the programming techniques to take advantage of these features.

Next, a demo shows many of these features.

A Swing Demo Here is an example of an application, PasswordStore, that illustrates 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.

Click the launch button to run PasswordStore using Java Web Start. [Requires release 6.0.]

Page 4: Graphical User Interfaces (Swing)

455

The following highlights some of the specific features of the PasswordStore application:

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 the following figure, 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

Table View The Swing table component 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

Page 5: Graphical User Interfaces (Swing)

456

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)

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

Page 6: Graphical User Interfaces (Swing)

457

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.

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

2D Graphics Used

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.

Page 7: Graphical User Interfaces (Swing)

458

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

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

Page 8: Graphical User Interfaces (Swing)

459

Lesson: 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 (Java Look and Feel)

Swing is primarily known for its rich set of GUI components. This section provides a visual menu of Swing's components, grouped by type, using the Java look and feel.

A Visual Guide to Swing Components (Windows Look and Feel)

This page shows the same components, using the Windows look and feel.

Pluggable Look and Feel

The pluggable look and feel architecture allows a program to have control over its appearance. This section describes what options are available to the programmer.

Data Transfer

Most programs will want to use drag and drop or cut, copy and paste. This section talks a bit about data transfer and what is implemented for you.

Internationalization and Localization

Internationalizing an application makes it easy to tailor it to the customs and languages of end users around the world. This section describes the difference between internationalization and localization.

Accessibility

Making your program accessible means that it can be used, without modification, by anyone with permanent or temporary disabilities who may require special devices. And, in many countries, making programs accessible is the law.

Integrating with the Desktop

An application that is well integrated with the desktop will, where appropriate, allow the user to launch the default mail application or internet browser, pre-populating text fields as needed. It will also allow the user to launch another application to open, edit or print a file associated with that application.

System Tray Icon Support

Some platforms, such as Microsoft Windows, feature a system tray on the desktop. As of version 6 of the Java SE, your application can now add a tray icon to the system tray.

Page 9: Graphical User Interfaces (Swing)

460

A Visual Guide to Swing Components (Java Look and Feel) This page shows Swing components in the Java look and feel. The following page shows the same components in the Windows look and feel. Basic Controls Simple components that are used primarily to get input from the user; they may also show simple state.

JButton

JCheckBox

JComboBox

JList

JMenu

JRadioButton

JSlider

Page 10: Graphical User Interfaces (Swing)

461

JSpinner

JTextField

JPasswordField

Interactive Displays of Highly Formatted Information These components display highly formatted information that (if you choose) can be modified by the user.

JColorChooser

JEditorPane and JTextPane

Page 11: Graphical User Interfaces (Swing)

462

JFileChooser

JTable

JTextArea

JTree

Uneditable Information Displays These components exist solely to give the user information.

Page 12: Graphical User Interfaces (Swing)

463

JLabel

JProgressBar

JSeparator

JToolTip

Top-Level Containers At least one of these components must be present in any Swing application.

JApplet

JDialog

JFrame

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

Page 13: Graphical User Interfaces (Swing)

464

JPanel

JScrollPane

JSplitPane

JTabbedPane

JToolBar Special-Purpose Containers These special-purpose containers play specific roles in the UI.

Page 14: Graphical User Interfaces (Swing)

465

JInternalFrame

JLayeredPane

Root pane

Page 15: Graphical User Interfaces (Swing)

466

A Visual Guide to Swing Components (Windows Look and Feel) This page shows Swing components in the Windows look and feel. The previous page shows the same components in the Java look and feel. Basic Controls Simple components that are used primarily to get input from the user; they may also show simple state.

JButton

JCheckBox

JComboBox

JList

JMenu

JRadioButton

JSlider

Page 16: Graphical User Interfaces (Swing)

467

JSpinner

JTextField

JPasswordField

Interactive Displays of Highly Formatted Information These components display highly formatted information that (if you choose) can be modified by the user.

JColorChooser

JEditorPane and JTextPane

Page 17: Graphical User Interfaces (Swing)

468

JFileChooser

JTable

JTextArea

JTree

Uneditable Information Displays These components exist solely to give the user information.

Page 18: Graphical User Interfaces (Swing)

469

JLabel

JProgressBar

JSeparator

JToolTip

Top-Level Containers At least one of these components must be present in any Swing application.

JApplet

JDialog

JFrame

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

Page 19: Graphical User Interfaces (Swing)

470

JPanel

JScrollPane

JSplitPane

JTabbedPane

JToolBar Special-Purpose Containers

Page 20: Graphical User Interfaces (Swing)

471

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

JInternalFrame

JLayeredPane

Root pane

Page 21: Graphical User Interfaces (Swing)

472

Page 22: Graphical User Interfaces (Swing)

473

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:

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.

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.

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.

Create your own look and feel using the Synth package. Use an externally provided look and feel.

As shown in the following figures, PasswordStore offers a choice of three look and feels. The Alloy and Synthetica look and feels have been provided courtesy of Incors.

Page 23: Graphical User Interfaces (Swing)

474

Java look and feel

Windows look and feel

Page 24: Graphical User Interfaces (Swing)

475

CDE/Motif look and feel

Page 25: Graphical User Interfaces (Swing)

476

Default Alloy look and feel

Page 26: Graphical User Interfaces (Swing)

477

Synthetica look and feel

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

Page 27: Graphical User Interfaces (Swing)

478

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 the following screenshots show, PasswordStore has been localized to Japanese and Arabic.

Page 28: Graphical User Interfaces (Swing)

479

PasswordStore in Japanese

Page 29: Graphical User Interfaces (Swing)

480

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. For more information, see Sun Microsystems' Accessibility Program - Relevant Laws.

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 tool tips, keyboard alternatives, and textual descriptions for images, wherever possible.

The PasswordStore demo follows the rules set out for accessibility. In the following figure, you can see an example of tool tip text.

Page 30: Graphical User Interfaces (Swing)

481

PasswordStore With a Tooltip

Integrating with the Desktop The Desktop API, 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 email 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 the text pane — it opens the specified URI in the default browser.

Page 31: Graphical User Interfaces (Swing)

482

Click on the URI and it opens in the Default Browser

For more information, see the Using the Desktop API in Java SE 6 (Mustang) article.

System Tray Icon Support The desktop of some platforms, such as Microsoft Windows, includes a system tray, as shown in the following screenshot:

On Microsoft Windows, it is called the "Taskbar Status Area." On Gnome, the "Notification Area", and on KDE, the "System Tray." However 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 was added in version 6 of Java SE. For more information, see the New System Tray Functionality in Mustang article.

Page 32: Graphical User Interfaces (Swing)

483

Questions and Exercises: 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 to Questions and Exercises: Graphical User Interfaces

Questions

1. Does Swing support multiple look and feels? Yes. Sun provides implementations for the GTK+ look and feel, Windows look and feel, CDE/Motif look and feel, Synth (a customizable look and feel), and two variants of the Java look and feel.

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

True. The Java look and feel (also called Metal) comes in two themes. Previous to the 5.0 release, the theme was called Steel. The theme for 5.0 and beyond, is called Ocean.

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

True. Undo support is built-in to Swing's text component and can be added to other components.

4. Can Swing's list component (JList) only display text?

No, as the demo illustrated you can display anything you want in a JList, including rich graphics.

5. Which Swing component provides undo support out of the box?

Swing's text components.

6. Can Java applications interact with the native desktop? components.

Certainly, the Desktop API allows you to open up the browser and various other services and the TrayIcon API allows you to put a Swing component into the desktop tray.

Page 33: Graphical User Interfaces (Swing)

484

7. Can I deploy my Swing application on the web?

Certainly. You can use either Java Web Start or Java Plugin.

Graphical User Interfaces: End of Trail You've reached the end of the "Graphical User Interfaces" trail.

If you have comments or suggestions about this trail, use our feedback page to tell us about it.

What next? Once you've caught your breath, you have several choices of where to go next. You can go to the front page to see all of your choices, or you can go directly to one of the following related trails:

Creating a GUI with JFC/Swing: Learn how to create graphical user interfaces for applications and applets, using Swing components.

Page 34: Graphical User Interfaces (Swing)

485

Trail: Creating a GUI with JFC/Swing

Also known as The Swing Tutorial This trail tells you how to create graphical user interfaces (GUIs) for applications and applets, using the Swing components.

Getting Started with Swing is a quick start lesson. First it gives you a bit of background about the JFC and Swing. Then it tells you how to compile and run programs that use Swing components.

Learning Swing with the NetBeans IDE is the fastest and easiest way to begin working with Swing. This lesson explores the NetBeans IDE's GUI builder, a powerful feature that lets you visually construct your Graphical User Interfaces.

Using Swing Components tells you how to use each of the Swing components — buttons, tables, text components, and all the rest. It also tells you how to use borders and icons.

Concurrency in Swing discusses concurrency as it applies to Swing programming. Information on the event dispatch thread and the SwingWorker class are included.

Using Other Swing Features tells you how to use actions, timers, and the system tray; how to integrate with the desktop class, how to support assistive technologies, how to print tables and text, how to create a splash screen, and how to use modality in dialogs.

Laying Out Components Within a Container tells you how to choose a layout manager, how to use each of the layout manager classes the JavaTM platform provides, how to use absolute positioning instead of a layout manager, and how to create your own layout manager.

Modifying the Look and Feel tells you how to specify the look and feel of Swing components.

Drag and Drop and Data Transfer tells you what you need to know to implement data transfer in your application.

Writing Event Listeners tells you how to handle events in your programs.

Performing Custom Painting gives you information on painting your own Swing components. It discusses painting issues specific to Swing components, provides an overview of painting concepts, and has examples of custom components that paint themselves.

Other UI-Related Trails

Although this is the main trail for learning about GUIs, it isn't the only trail with UI-related information.

2D Graphics, which describes the 2D graphics features available in the JDK. Sound, which discusses the sound capabilities available in the JDK. Applets, which describes API available only to applets. Essential Classes, which covers many topics, including properties and the standard

I/O streams. The Bonus trail contains Full-Screen Exclusive Mode API, a lesson that describes

how to use API introduced in v1.4 to render graphics directly to the screen.

Page 35: Graphical User Interfaces (Swing)

486

Lesson: Getting Started with Swing Examples Index

This lesson gives you a brief introduction to using the Java Foundation Classes (JFC) and Swing. After telling you about JFC and Swing, it helps you get the necessary software and walks you through how to compile and run a program that uses the Swing packages.

The following lesson, Learning Swing with the NetBeans IDE, will build on these first steps to help you create several progressively more complex examples. For now, let's start with the basics.

About the JFC and Swing

This section gives you an overview of the JFC and Swing.

Compiling and Running Swing Programs

This section gives you detailed instructions on where to obtain the latest JDK and how to create, compile and run a program that uses Swing components. About the JFC and Swing JFC is short for Java Foundation Classes, which encompass a group of features for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications. It is defined as containing the features shown in the table below.

Features of the Java Foundation Classes Feature Description

Swing GUI Components

Includes everything from buttons to split panes to tables. Many components are capable of sorting, printing, and drag and drop, to name a few of the supported features.

Pluggable Look-and-Feel Support

The look and feel of Swing applications is pluggable, allowing a choice of look and feel. For example, the same program can use either the Java or the Windows look and feel. Additionally, the Java platform supports the GTK+ look and feel, which makes hundreds of existing look and feels available to Swing programs. Many more look-and-feel packages are available from various sources.

Accessibility API Enables assistive technologies, such as screen readers and Braille displays, to get information from the user interface.

Java 2D API Enables developers to easily incorporate high-quality 2D graphics, text, and images in applications and applets. Java 2D includes extensive APIs for generating and sending high-quality output to printing devices.

Internationalization

Allows developers to build applications that can interact with users worldwide in their own languages and cultural conventions. With the input method framework developers can build applications that accept text in languages that use thousands of different characters, such as Japanese, Chinese, or Korean.

This trail concentrates on the Swing components. We help you choose the appropriate components for your GUI, tell you how to use them, and give you the background information you need to use them effectively. We also discuss other JFC features as they apply to Swing components.

Page 36: Graphical User Interfaces (Swing)

487

Which Swing Packages Should I Use?

The Swing API is powerful, flexible — and immense. The Swing API has 18 public packages: javax.accessibility javax.swing.plaf javax.swing.text javax.swing javax.swing.plaf.basic javax.swing.text.html javax.swing.border javax.swing.plaf.metal javax.swing.text.html.parser javax.swing.colorchooser javax.swing.plaf.multi javax.swing.text.rtf javax.swing.event javax.swing.plaf.synth javax.swing.tree javax.swing.filechooser javax.swing.table javax.swing.undo Fortunately, most programs use only a small subset of the API. This trail sorts out the API for you, giving you examples of common code and pointing you to methods and classes you're likely to need. Most of the code in this trail uses only one or two Swing packages:

javax.swing javax.swing.event (not always required)

Compiling and Running Swing Programs This section explains how to compile and run a Swing application from the command line. For information on compiling and running a Swing application using NetBeans IDE, see Running Tutorial Examples in NetBeans IDE. The compilation instructions work for all Swing programs — applets, as well as applications. Here are the steps you need to follow:

Install the latest release of the Java SE platform, if you haven't already done so. Create a program that uses Swing components. Compile the program. Run the program.

Install the Latest Release of the Java SE Platform

You can download the latest release of the JDK for free from http://java.sun.com/javase/downloads.

Create a Program That Uses Swing Components

You can use a simple program we provide, called HelloWorldSwing, that brings up the GUI shown in the figure below. The program is in a single file, HelloWorldSwing.java. When you save this file, you must match the spelling and capitalization of its name exactly.

Compile the Program

Your next step is to compile the program. Here's an example of compiling HelloWorldSwing.java: javac HelloWorldSwing.java If you can't compile, make sure you're using the compiler in a recent release of the Java platform. Once you've updated your JDK, you should be able to use the programs in this trail without changes. Another common mistake is installing the Java Runtime Environment (JRE) and not the full Java Development Kit (JDK) needed to compile these programs. Refer to the Getting Started trail to help

Page 37: Graphical User Interfaces (Swing)

488

you solve any compiling problems you encounter. Another resource is the Troubleshooting Guide for Java™ SE 6 Desktop Technologies.

Run the Program

After you compile the program successfully, you can run it. For example: java HelloWorldSwing

Lesson: Learning Swing with the NetBeans IDE

This lesson provides an introduction to Graphical User Interface (GUI) programming with Swing and the NetBeans IDE. As you learned in the "Hello World!" lesson, the NetBeans IDE is a free, open-source, cross-platform integrated development environment with built-in support for the Java programming language. It offers many advantages over coding with a text editor; we recommend its use whenever possible. If you have not yet read the above lesson, please take a moment to do so now. It provides valuable information about downloading and installing the JDK and NetBeans IDE.

The goal of this lesson is to introduce the Swing API by designing a simple application that converts temperature from Celsius to Fahrenheit. Its GUI will be basic, focusing on only a subset of the available Swing components. We will use the NetBeans IDE GUI builder, which makes user interface creation a simple matter of drag and drop. Its automatic code generation feature simplifies the GUI development process, letting you focus on the application logic instead of the underlying infrastructure.

Because this lesson is a step-by-step checklist of specific actions to take, we recommend that you run the NetBeans IDE and perform each step as you read along. This will be the quickest and easiest way to begin programming with Swing. If you are unable to do so, simply reading along should still be useful, since each step is illustrated with screenshots.

If you prefer the traditional approach of programming each component manually (without the assistance of an IDE), think of this lesson as an entry point into the lower-level discussions already provided elsewhere in the tutorial. Hyperlinks in each discussion will take you to related lessons, should you wish to learn such lower-level details.

The finished GUI for this application will look as follows:

The CelsiusConverter Application.

Click the Launch button to run CelsiusConverter using Java™ Web Start (download JDK 6). Alternatively, to compile and run the example yourself, consult the example index.

Page 38: Graphical User Interfaces (Swing)

489

From an end-user's perspective, usage is simple: enter a temperature (in Celsius) into the text box, click the "Convert" button, and watch the converted temperature (in Fahrenheit) appear on screen. The minimize, maximize, and close buttons will behave as expected, and the application will also have a title that appears along the top of the window.

From a programmer's perspective, we will write the application in two main stages. First, we will populate the GUI with the various Swing components and arrange them as shown above. Then, we will add the application logic, so that the program actually performs a conversion when the user presses the "Convert" button.

Setting up the CelsiusConverter Project If you have worked with the NetBeans IDE in the past, much of this section will look familiar, since the initial steps are similar for most projects. Still, the following steps describe settings that are specific to this application, so take care to follow them closely.

Step 1: Create a New Project

To create a new project, launch the NetBeans IDE and choose New Project from the File menu:

Creating a New Project

Keyboard shortcuts for each command appear on the far right of each menu item. The look and feel of the NetBeans IDE may vary across platforms, but the functionality will remain the same.

Step 2: Choose General -> Java Application

Next, select General from the Categories column, and Java Application from the Projects column:

Page 39: Graphical User Interfaces (Swing)

490

This figure has been reduced to fit on the page.

Click the image to view it at its natural size.

You may notice mention of "J2SE" in the description pane; that is the old name for what is now known as the "Java SE" platform. Press the button labeled "Next" to proceed.

Step 3: Set a Project Name

Now enter "CelsiusConverterProject" as the project name. You can leave the Project Location and Project Folder fields set to their default values, or click the Browse button to choose an alternate location on your system.

Page 40: Graphical User Interfaces (Swing)

491

This figure has been reduced to fit on the page.

Click the image to view it at its natural size.

Make sure to deselect the "Create Main Class" checkbox; leaving this option selected generates a new class as the main entry point for the application, but our main GUI window (created in the next step) will serve that purpose, so checking this box is not necessary. Click the "Finish" button when you are done.

Page 41: Graphical User Interfaces (Swing)

492

This figure has been reduced to fit on the page.

Click the image to view it at its natural size.

When the IDE finishes loading, you will see a screen similar to the above. All panes will be empty except for the Projects pane in the upper left hand corner, which shows the newly created project.

Step 4: Add a JFrame Form

Page 42: Graphical User Interfaces (Swing)

493

This figure has been reduced to fit on the page.

Click the image to view it at its natural size.

Now right-click the CelsiusConverterProject name and choose New -> JFrame Form (JFrame is the Swing class responsible for the main frame for your application.) You will learn how to designate this class as the application's entry point later in this lesson.

Step 5: Name the GUI Class

Next, type CelsiusConverterGUI as the class name, and learn as the package name. You can actually name this package anything you want, but here we are following the tutorial convention of naming the package after the lesson in which is resides.

Page 43: Graphical User Interfaces (Swing)

494

This figure has been reduced to fit on the page.

Click the image to view it at its natural size.

The remainder of the fields should automatically be filled in, as shown above. Click the Finish button when you are done.

Page 44: Graphical User Interfaces (Swing)

495

This figure has been reduced to fit on the page.

Click the image to view it at its natural size.

When the IDE finishes loading, the right pane will display a design-time, graphical view of the CelsiusConverterGUI. It is on this screen that you will visually drag, drop, and manipulate the various Swing components.

NetBeans IDE Basics It is not necessary to learn every feature of the NetBeans IDE before exploring its GUI creation capabilities. In fact, the only features that you really need to understand are the Palette, the Design Area, the Property Editor, and the Inspector. We will discuss these features below.

The Palette

The Palette contains all of the components offered by the Swing API. You can probably already guess what many of these components are for, even if this is your first time using them (JLabel is a text label, JList is a drop-down list, etc.)

Page 45: Graphical User Interfaces (Swing)

496

This figure has been reduced to fit on the page.

Click the image to view it at its natural size.

From this list, our application will use only JLabel (a basic text label), JTextField (for the user to enter the temperature), and JButton (to convert the temperature from Celsius to Fahrenheit.)

The Design Area

The Design Area is where you will visually construct your GUI. It has two views: source view, and design view. Design view is the default, as shown below. You can toggle between views at any time by clicking their respective tabs.

This figure has been reduced to fit on the page.

Click the image to view it at its natural size.

The figure above shows a single JFrame object, as represented by the large shaded rectangle with blue border. Commonly expected behavior (such as quitting when the user clicks the "close" button) is auto-generated by the IDE and appears in the source view between uneditable blue sections of code known as guarded blocks.

Page 46: Graphical User Interfaces (Swing)

497

This figure has been reduced to fit on the page.

Click the image to view it at its natural size.

A quick look at the source view reveals that the IDE has created a private method named initComponents, which initializes the various components of the GUI. It also tells the application to "exit on close", performs some layout-specific tasks, then packs the (soon to be added) components together on screen.

Don't feel that you need to understand this code in any detail; we mention it here simply to explore the source tab. For more information about these components, see:

How to Make Frames (Main Windows) and Laying Out Components Within a Container.

The Property Editor

The Property Editor does what its name implies: it allows you to edit the properties of each component. The Property Editor is intuitive to use; in it you will see a series of rows — one row per property — that you can click and edit without entering the source code directly. The following figure shows the Property Editor for the newly added JFrame object:

Page 47: Graphical User Interfaces (Swing)

498

This figure has been reduced to fit on the page.

Click the image to view it at its natural size. The screenshot above shows the various properties of this object, such as background color, foreground color, font, and cursor.

The Inspector

The last component of the NetBeans IDE that we will use in this lesson is the Inspector:

The Inspector

The Inspector provides a graphical representation of your application's components. We will use the Inspector only once, to change a few variable names to something other than their defaults.

Creating the CelsiusConverter GUI

This section explains how to use the NetBeans IDE to create the application's GUI. As you drag each component from the Palette to the Design Area, the IDE will auto-generate the appropriate source code.

Page 48: Graphical User Interfaces (Swing)

499

Step 1: Set the Title

First, set the title of the application's JFrame to "Celsius Converter", by single-clicking the JFrame in the Inspector:

Selecting the JFrame

Then, set its title with the Property Editor:

Setting the Title

You can set the title by either double-clicking the title property and entering the new text directly, or by clicking the button and entering the title in the provided field. Or, as a shortcut, you could single-click the JFrame of the inspector and enter its new text directly without using the property editor.

Step 2: Add a JTextField

Page 49: Graphical User Interfaces (Swing)

500

Next, drag a JTextField from the Palette to the upper left corner of the Design Area. As you approach the upper left corner, the GUI builder will will provide visual cues (dashed lines) that suggest the appropriate spacing. Using these cues as a guide, drop a JTextField into the upper left hand corner of the window as shown below:

Adding a JTextField

You may be tempted to erase the default text "JTextField1", but just leave it in place for now. We will replace it later in this lesson as we make the final adjustments to each component. For more information about this component, see How to Use Text Fields.

Step 3: Add a JLabel

Next, drag a JLabel onto the Design Area. Place it to the right of the JTextField, again watching for visual cues that suggest an appropriate amount of spacing. Make sure that text base for this component is aligned with that of the JTextField. The visual cues provided by the IDE should make this easy to determine.

Page 50: Graphical User Interfaces (Swing)

501

Adding a JLabel

For more information about this component, see How to Use Labels.

Step 4: Add a JButton

Next, drag a JButton from the Palette and position it to the left and underneath the JTextField. Again, the visual cues will help guide it into place.

Page 51: Graphical User Interfaces (Swing)

502

Adding a JButton

You may be tempted to manually adjust the width of the JButton and JTextField, but just leave them as they are for now. You will learn how to correctly adjust these components later in this lesson. For more information about this component, see How to Use Buttons.

Step 5: Add a Second JLabel

Adding a Second JLabel

Finally, add a second JLabel, repeating the process in step 2. Place this second label to the right of the JButton, as shown above.

Adjusting the CelsiusConverter GUI With the GUI components now in place, it is time to make the final adjustments. There are a few different ways to do this; the order suggested here is just one possible approach.

Step 1: Set the Component Text

First, slowly double-click the JTextField and JButton to change the default text that was inserted by the IDE. To do this, click, then pause, then click again on the component. Alternately, you can right-click the component and then choose Edit Text. When you erase the text from the JTextField, it will shrink in size as shown below. Change the text of the JButton from "JButton1" to "Convert." Also change the top JLabel text to "Celsius" and the bottom to "Fahrenheit."

Page 52: Graphical User Interfaces (Swing)

503

Setting the Component Text

Step 2: Set the Component Size

Next, shift-click the JTextField and JButton components. This will highlight each showing that they are selected. Right-click (control-click for mac users) Same Size -> Same Width. The components will now be the same width, as shown below. When you perform this step, make sure that JFrame itself is not also selected. If it is, the Same Size menu will not be active.

Page 53: Graphical User Interfaces (Swing)

504

Setting the JTextField and JButton Sizes

Step 3: Remove Extra Space

Finally, grab the lower right-hand corner of the JFrame and adjust its size to eliminate any extra whitespace. Note that if you eliminate all of the extra space (as shown below) the title (which only appears at runtime) may not show completely. The end-user is free to resize the application as desired, but you may want to leave some extra space on the right side to make sure that everything fits correctly. Experiment, and use the screenshot of the finished GUI as a guide.

The Completed GUI

The GUI portion of this application is now complete! If the NetBeans IDE has done its job, you should feel that creating this GUI was a simple, if not trivial, task. But take a minute to click on the source tab; you might be surprised at the amount of code that has been generated.

Page 54: Graphical User Interfaces (Swing)

505

This figure has been reduced to fit on the page.

Click the image to view it at its natural size.

To see the code in its entirety, scroll up and down within the IDE as necessary. You can expand or collapse certain blocks of code (such as method bodies) by clicking the + or - symbol on the left-hand side of the source editor.

Adding the Application Logic It is now time to add in the application logic.

Step 1: Change the Default Variable Names

The figure below shows the default variable names as they currently appear within the Inspector. For each component, the variable name appears first, followed by the object's type in square brackets. For example, jTextField1 [JTextField] means that "jTextField1" is the variable name and "JTextField" is its type.

Page 55: Graphical User Interfaces (Swing)

506

Default Variable Names

The default names are not very relevant in the context of this application, so it makes sense to change them from their defaults to something that is more meaningful. Right-click each variable name and choose "Change variable name." When you are finished, the variable names should appear as follows:

New Variable Names

The new variable names are "tempTextField", "celsiusLabel", "convertButton", and "fahrenheitLabel." Each change that you make in the Inspector will automatically propagate its way back into the source code. You can rest assured that compilation will not fail due to typos or mistakes of that nature — mistakes that are common when editing by hand.

Step 2: Register the Event Listeners

When an end-user interacts with a Swing GUI component (such as clicking the Convert button), that component will generate a special kind of object — called an event object — which it will then broadcast to any other objects that have previously registered themselves as listeners for that event. The NetBeans IDE makes event listener registration extremely simple:

Page 56: Graphical User Interfaces (Swing)

507

This figure has been reduced to fit on the page.

Click the image to view it at its natural size.

In the Design Area, click on the Convert button to select it. Make sure that only the Convert button is selected (if the JFrame itself is also selected, this step will not work.) Right-click the Convert button and choose Events -> Action -> ActionPerformed. This will generate the required event-handling code, leaving you with empty method bodies in which to add your own functionality:

This figure has been reduced to fit on the page.

Click the image to view it at its natural size.

There are many different event types representing the various kinds of actions that an end-user can take (clicking the mouse triggers one type of event, typing at the keyboard triggers another, moving the mouse yet another, and so on.) Our application is only concerned with the ActionEvent; for more information about event handling, see Writing Event Listeners.

Step 3: Add the Temperature Conversion Code

Page 57: Graphical User Interfaces (Swing)

508

The final step is to simply paste the temperature conversion code into the empty method body. The following code is all that is necessary to convert a temperature from Celsius to Fahrenheit: //Parse degrees Celsius as a double and convert to Fahrenheit. int tempFahr = (int)((Double.parseDouble(tempTextField.getText())) * 1.8 + 32); fahrenheitLabel.setText(tempFahr + " Fahrenheit"); Simply copy this code and paste it into the convertButtonActionPerformed method as shown below:

This figure has been reduced to fit on the page.

Click the image to view it at its natural size. With the conversion code in place, the application is now complete.

Step 4: Run the Application

Running the application is simply a matter of choosing Run -> Run Main Project within the NetBeans IDE. The first time you run this application, you will be prompted with a dialog asking to set CelsiusConverterGUI as the main class for this project. Click the OK button, and when the program finishes compiling, you should see the application running in its own window.

Congratulations! You have completed your first Swing application!

Questions and Exercises: Learning Swing with the NetBeans IDE

Questions

1. When creating this new project, we left the "Create Main Class" checkbox deselected. Why? 2. The _____ contains all of the components offered by the Swing API. 3. What is the purpose of the Design Area? 4. Explain the difference between the Source and Design tabs. 5. Name some advantages to editing an object with the Property Editor (as opposed to editing it

directly in the source code.) 6. This lesson used Swing objects of three different types. What were they? 7. Describe the process for setting two components to the same width in the Design Area.

Exercises

1. Use the property editor to change the appearance of this application. Experiment by changing some values and seeing what effect your changes have.

Answers: Learning Swing with the NetBeans IDE

Page 58: Graphical User Interfaces (Swing)

509

Questions

Question 1: When creating this new project, we left the "Create Main Class" checkbox deselected. Why? Answer 1: We left this checkbox deselected because the CelsiusConverterGUI is the application's main entry point. Question 2: The _____ contains all of the components offered by the Swing API. Answer 2: Palette Question 3: What is the purpose of the Design Area? Answer 3: The Design Area is where you visually arrange the various components of the application's GUI. It cuts development time because all of the application's layout code is auto-generated. Question 4: Explain the difference between the Source and Design tabs. Answer 4: These tabs provide two different views of the same application. The Design tab shows what the application actually looks like, and the Source tab shows its source code. Some portions of the source tab are auto-generated and not directly editable by the user. Question 5: Name some advantages to editing an object with the Property Editor (as opposed to editing it directly in the source code.) Answer 5: Using the property editor elimates typing errors, accidental modification of the wrong code, and provides a listing of all properties exposed by a particular object. Question 6:This lesson used Swing objects of three different types. What were they? Answer 6: JLabel, JButton, and JTextField Question 7:In the Design Area, describe the process for setting two components to the same width. Answer 7:Shift-click the two target components; this will highlight each showing that they are selected. Right-click (control-click for mac users) Same Size -> Same Width. The components will now be the same width.

Exercises

1. Use the property editor to change the appearance of this application. Experiment by changing some values and seeing what effect your changes have. This is a quick and easy way to explore the properties of the various Swing components.

Below we've modified the application to use DialogInput font, and have changed the cursor to a hand cursor.

A modified CelsiusConverter Application.