Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
This lesson gives you a brief introduction to using Swing. After telling you about Swing, it 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.
Feature
Description
Swing
GUI Includes everything from buttons to split panes to
Components
tables. Many components are capable of sorting,
printing, and drag and drop, to name a few of the
supported features.
Pluggable
Look- The look and feel of Swing applications is pluggable,
and-Feel Support
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.
Internationalizatio Allows developers to build applications that can
n
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 features as they apply to Swing components.
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
Install the latest release of the Java SE platform, if you haven't already done so.
can
download
the
latest
release
of
the
from http://www.oracle.com/technetwork/java/javase/downloads/index.html.
JDK
for
free
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.
The HelloWorldSwing.java example, like all of our Swing tutorial examples, is created inside a
package. If you look at the source code, you see the following line at the beginning of the file:
package start;
This means you must put the HelloWorldSwing.java file inside of a start directory. You compile
and run the example from the directory above the start directory. The tutorial examples from the Using
Swing Components lesson are inside of a components package and the examples from the Writing
Event Listeners lesson are inside a events package, and so on. For more information, you might want
to see the Packages lesson.
javac start/HelloWorldSwing.java
If you prefer, you may compile the example from within the start directory:
javac HelloWorldSwing.java
but you must remember to leave the start directory to execute the program.
If you are unable to compile, make sure you are using the compiler in a recent release of the Java
platform. You can verify the version of your compiler or Java Runtime Environment (JRE) using these
commands
javac -version
java -version
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 JRE and not the full Java Development Kit (JDK) needed to
compile these programs. Refer to the Getting Started trail to help you solve any compiling problems you
encounter. Another resource is the Troubleshooting Guide for Java SE 6 Desktop Technologies.
After you compile the program successfully, you can run it. From the directory above
the start directory:
java start.HelloWorldSwing
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.
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.
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.
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.
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.
The remainder of the fields should automatically be filled in, as shown above. Click the Finish button
when you are done.
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.
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, theDesign 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 ( JLabelis a text
label, JList is a drop-down list, etc.)
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.)
Figura 10. This figure has been reduced to fit on the page.
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.
Figura 11. This figure has been reduced to fit on the page.
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.
Figura 12. This figure has been reduced to fit on the page.
The Inspector
The last component of the NetBeans IDE that we will use in this lesson is 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.
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.
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.
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.
Finally, add a second JLabel, repeating the process in step 2. Place this second label to the right of
the JButton, as shown above.
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.
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.
Figura 23. This figure has been reduced to fit on the page.
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:
The new variable names are "txtTemperatura", "lblCelsius", "btnConvert", and "lblFahrenheit". 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.
Figura 26. This figure has been reduced to fit on the page.
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:
Figura 27. This figure has been reduced to fit on the page.
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.
Figura 28. This figure has been reduced to fit on the page.