0% found this document useful (0 votes)
70 views32 pages

Introduction To Swing: Before You Start

This document provides an introduction to the Swing GUI framework in Java. It begins by explaining what a user interface (UI) is and how Swing acts as the middleman between the user and computer to handle all UI aspects. It then discusses the Model-View-Controller design pattern used by Swing to separate responsibilities. The document proceeds to explain the basic JComponent class that all Swing components inherit from and introduces simple widgets like JLabel and JButton, describing their common methods.

Uploaded by

aninda.jobs
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views32 pages

Introduction To Swing: Before You Start

This document provides an introduction to the Swing GUI framework in Java. It begins by explaining what a user interface (UI) is and how Swing acts as the middleman between the user and computer to handle all UI aspects. It then discusses the Model-View-Controller design pattern used by Swing to separate responsibilities. The document proceeds to explain the basic JComponent class that all Swing components inherit from and introduces simple widgets like JLabel and JButton, describing their common methods.

Uploaded by

aninda.jobs
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Introduction to Swing

Michael Abernethy, Team Lead, IBM


Summary:  This hands-on introduction to Swing, the first in a two-part series on Swing
programming, walks through the essential components in the Swing library. Java developer and
Swing enthusiast Michael Abernethy guides you through the basic building blocks and then assists
as you build basic but functional Swing application. Along the way you'll learn how to use models to
ease the process of dealing with the data.

Before you start


About this tutorial
This tutorial is for Swing beginners. Perhaps you know others who use it, or you've seen it in an
application you use. Maybe you've even dabbled in it yourself. Whatever the case, this tutorial walks
you through a basic Swing application, starting with the ubiquitous HelloWorld application. After you
get that running on your machine, we'll build your Swing knowledge by creating a flight reservation
system, adding to it until you have a basic but fully functional application.
During the course of this tutorial, you will learn all the beginner components in Swing; by beginner
components, I mean the ones you would use to build simple user interfaces (UIs). You will learn how
to use basic methods to set their properties and how these Swing components interact with other
components. You will also read about other UI concepts you'll need to complete your Swing
knowledge, including layouts, event/listeners, and data models. By the end of the tutorial, you should
be able to build a simple Swing application.
Please note though that this tutorial is not intended to serve as an all-encompassing beginner's
guide to Swing. There are entire books dedicated to learning Swing, and I cannot possibly duplicate
that effort here. This tutorial instead focuses on the most commonly used components and functions
that you as a beginner will most likely run across in your work.
If, after completing this tutorial, you are interested in furthering your knowledge of Swing
programming, you should read the companion tutorial called "Intermediate Swing," which will build
on the concepts and the sample application developed in this tutorial.

Introduction to Swing
Introduction to UIs
Before you start to learn Swing, you must address the true beginner's question: What is a UI? Well,
the beginner's answer is a "user interface." But because this tutorial's goal is to ensure you are no
longer a mere beginner, we need a more advanced definition than that.
So, I'll pose the question again: What's a UI? Well, you could define it by saying it's the buttons you
press, the address bar you type in, and the windows you open and close, which are all elements of a
UI, but there's more to it than just things you see on the screen. The mouse, keyboard, volume of the
music, colors on the screen, fonts used, and the position of an object compared to another object
are all included in the UI. Basically, any object that plays a role in the interaction between the
computer and the user is part of the UI. That seems simple enough, but you'd be surprised how
many people and huge corporations have screwed this up over the years. In fact, there are now
college majors whose sole coursework is studying this interaction.
Swing's role
Swing is the Java platform's UI -- it acts as the software to handle all the interaction between a user
and the computer. It essentially serves as the middleman between the user and the guts of the
computer. How exactly does Swing do this? It provides mechanisms to handle the UI aspects
described in the previous panel:
 Keyboard: Swing provides a way to capture user input.
 Colors: Swing provides a way to change the colors you see on the screen.
 The address bar you type into: Swing provides text components that handle all the mundane
tasks.
 The volume of the music: Well ... Swing's not perfect.
In any case, Swing gives you all the tools you need to create your own UI.
Back to top
MVC
Swing even goes a step further and puts a common design pattern on top of the basic UI principles.
This design pattern is called Model-View-Controller (MVC) and seeks to "separate the roles." MVC
keeps the code responsible for how something looks separate from the code to handle the data
separate from the code that reacts to interaction and drives changes.
Confused? It's easier if I give you a non-technical example of this design pattern in the real world.
Think about a fashion show. Consider this your UI and pretend that the clothes are the data, the
computer information you present to your user. Now, imagine that this fashion show has only one
person in it. This person designed the clothes, modified the clothes, and walked them down the
runway all at the same time. That doesn't seem like a well-constructed or efficient design.
Now, consider this same fashion show using the MVC design pattern. Instead of one person doing
everything, the roles are divided up. The fashion models (not to be confused with the model in the
acronym MVC of course) present the clothes. They act as the view. They know the proper way to
display the clothes (data), but have no knowledge at all about how to create or design the clothes.
On the other hand, the clothing designer works behind the scenes, making changes to the clothes as
necessary. The designer acts as the controller. This person has no concept of how to walk a runway
but can create and manipulate the clothes. Both the fashion models and the designer work
independently with the clothes, and both have an area of expertise.
That is the concept behind the MVC design pattern: Let each aspect of the UI deal with what it's
good at. If you're still confused, the examples in the rest of the tutorial will hopefully alleviate that --
but keep the basic principle in mind as you continue: Visual components display data, and other
classes manipulate it.
Back to top
JComponent
The basic building block of the entire visual component library of Swing is the JComponent. It's the
super class of every component. It's an abstract class, so you can't actually create a JComponent,
but it contains literally hundreds of functions every component in Swing can use as a result of the
class hierarchy. Obviously, some concepts are more important than others, so for this tutorial, the
important things to learn are:
 JComponent is the base class not only for the Swing components but also for custom
components as well (more information in the "Intermediate Swing" tutorial).

 It provides the painting infrastructure for all components -- something that comes in handy for
custom components (again, there's more info on this subject in "Intermediate Swing").

 It knows how to handle all keyboard presses. Subclasses then only need to listen for specific
keys.

 It contains the add() method that lets you add other JComponents. Looking at this another
way, you can seemingly add any Swing component to any other Swing component to build
nested components (for example, a JPanel containing a JButton, or even weirder
combinations such as a JMenu containing a JButton).

Simple Swing widgets


JLabel
The most basic component in the Swing library is the JLabel. It does exactly what you'd expect: It
sits there and looks pretty and describes other components. The image below shows the JLabel in
action:
The JLabel 

Not very exciting, but still useful. In fact, you use JLabels throughout applications not only as text
descriptions, but also as picture descriptions. Any time you see a picture in a Swing application,
chances are it's a JLabel. JLabel doesn't have many methods for a Swing beginner outside of what
you might expect. The basic methods involve setting the text, image, alignment, and other
components the label describes:
 get/setText(): Gets/sets the text in the label.

 get/setIcon(): Gets/sets the image in the label.

 get/setHorizontalAlignment(): Gets/sets the horizontal position of the text.

 get/setVerticalAlignment(): Gets/sets the vertical position of the text.

 get/setDisplayedMnemonic(): Gets/sets the mnemonic (the underlined character) for the


label.

 get/setLabelFor(): Gets/sets the component this label is attached to; so when a user


presses Alt+mnemonic, the focus goes to the specified component.
Back to top
JButton
The basic action component in Swing, a JButton, is the push button you see with the OK and Cancel
in every window; it does exactly what you expect a button to do -- you click it and something
happens. What exactly happens? Well, you have to define that (see Events for more information). A
JButton in action looks like this:
The JButton 
The methods you use to change the JButton properties are similar to the JLabel methods (and you'll
find they're similar across most Swing components). They control the text, the images, and the
orientation:
 get/setText(): Gets/sets the text in the button.

 get/setIcon(): Gets/sets the image in the button.

 get/setHorizontalAlignment(): Gets/sets the horizontal position of the text.

 get/setVerticalAlignment(): Gets/sets the vertical position of the text.

 get/setDisplayedMnenomic(): Gets/sets the mnemonic (the underlined character) that


when combined with the Alt button, causes the button to click.
In addition to these methods, I'll introduce another group of methods the JButton contains. These
methods take advantage of all the different states of a button. A state is a property that describes a
component, usually in a true/false setting. In the case of a JButton, it contains the following possible
states: active/inactive, selected/not selected, mouse-over/mouse-off, pressed/unpressed. In addition,
you can combine states, so that, for example, a button can be selected with a mouse-over. Now you
might be asking yourself what the heck you're supposed to do with all these states. As an example,
go up to the Back button on your browser. Notice how the image changes when you mouse over it,
and how it changes when you press it. This button takes advantage of the various states. Using
different images with each state is a popular and effective way to indicate to a user that interaction is
taking place. The state methods on a JButton are:
 get/setDisabledIcon()

 get/setDisabledSelectedIcon()

 get/setIcon()

 get/setPressedIcon()

 get/setRolloverIcon()

 get/setRolloverSelectedIcon()

 get/setSelectedIcon()
Back to top
JTextField
The basic text component in Swing is the JTextField, and it allows a user to enter text into the UI. I'm
sure you're familiar with a text field; you had to use one to enter your user name and password to
take this tutorial. You enter text, delete text, highlight text, and move the caret around -- and Swing
takes care of all of that for you. As a UI developer, there's really little you need to do to take
advantage of the JTextField.
In any case, this what a JTextField looks like in action:
The JTextField 

You need to concern yourself with only one method when you deal with a JTextField -- and that
should be obvious -- the one that sets the text: get/setText(), which gets/sets the text inside the
JTextField.
Back to top
JFrame
So far I've talked about three basic building blocks of Swing, the label, button, and text field; but now
you need somewhere to put them. They can't just float around on the screen, hoping the user knows
how to deal with them. The JFrame class does just that -- it's a container that lets you add other
components to it in order to organize them and present them to the user. It contains many other
bonuses, but I think it's easiest to see a picture of it first:
The JFrame 

A JFrame actually does more than let you place components on it and present it to the user. For all
its apparent simplicity, it's actually one of the most complex components in the Swing packages. To
greatly simplify why, the JFrame acts as bridge between the OS-independent Swing parts and the
actual OS it runs on. The JFrame registers as a window in the native OS and by doing so gets many
of the familiar OS window features: minimize/maximize, resizing, and movement. For the purpose of
this tutorial though, it is quite enough to think of the JFrame as the palette you place the components
on. Some of the methods you can call on a JFrame to change its properties are:
 get/setTitle(): Gets/sets the title of the frame.

 get/setState(): Gets/sets the frame to be minimized, maximized, etc.

 is/setVisible(): Gets/sets the frame to be visible, in other words, appear on the screen.

 get/setLocation(): Gets/sets the location on the screen where the frame should appear.

 get/setSize(): Gets/sets the size of the frame.

 add(): Adds components to the frame.


Back to top
A simple application
Like all "Introduction to x" tutorials, this one has the requisite HelloWorld demonstration. This
example, however, is useful not only to see how a Swing app works but also to ensure your setup is
correct. Once you get this simple app to work, every example after this one will work as well. The
image below shows the completed example:
HelloWorld example 

Your first step is to create the class. A Swing application that places components on a JFrame
needs to subclass the JFrameclass, like this:
public class HelloWorld extends JFrame

By doing this, you get all the JFrame properties outlined above, most importantly native OS support
for the window. The next step is to place the components on the screen. In this example, you use a
null layout. You will learn more about layouts and layout managers later in the tutorial. For this
example though, the numbers indicate the pixel position on the JFrame:
public HelloWorld()
{
super();
this.setSize(300, 200);
this.getContentPane().setLayout(null);
this.add(getJLabel(), null);
this.add(getJTextField(), null);
this.add(getJButton(), null);
this.setTitle("HelloWorld");
}

private javax.swing.JLabel getJLabel() {


if(jLabel == null) {
jLabel = new javax.swing.JLabel();
jLabel.setBounds(34, 49, 53, 18);
jLabel.setText("Name:");
}
return jLabel;
}

private javax.swing.JTextField getJTextField() {


if(jTextField == null) {
jTextField = new javax.swing.JTextField();
jTextField.setBounds(96, 49, 160, 20);
}
return jTextField;
}

private javax.swing.JButton getJButton() {


if(jButton == null) {
jButton = new javax.swing.JButton();
jButton.setBounds(103, 110, 71, 27);
jButton.setText("OK");
}
return jButton;
}

Now that the components are laid out on the JFrame, you need the JFrame to show up on the
screen and make your application runnable. As in all Java applications, you must add a main
method to make a Swing application runnable. Inside this main method, you simply need to create
your HelloWorld application object and then call setVisible() on it:
public static void main(String[] args)
{
HelloWorld w = new HelloWorld();
w.setVisible(true);
}

And you're done! That's all there is to creating the application.


Additional Swing widgets
JComboBox
In this section we'll cover all the other components in the Swing library, how to use them, and what
they look like, which should give you a better idea of the power Swing gives you as a UI developer.
We'll start with the JComboBox. A combo box is the familiar drop-down selection, where users can
either select none or one (and only one) item from the list. In some versions of the combo box, you
can type in your own choice. A good example is the address bar in your browser; that is a combo
box that lets you type in your own choice. Here's what the JComboBox looks like in Swing:
The JComboBox 

The important functions with a JComboBox involve the data it contains. You need a way to set the
data in the JComboBox, change it, and get the users' choice once they've made a selection. You
can use the following JComboBox methods:
 addItem(): Adds an item to the JComboBox.

 get/setSelectedIndex(): Gets/sets the index of the selected item in JComboBox.

 get/setSelectedItem(): Gets/sets the selected object.

 removeAllItems(): Removes all the objects from the JComboBox.

 remoteItem(): Removes a specific object from the JComboBox.


Back to top
JPasswordField
A slight variation on the JTextField is the JPasswordField, which lets you hide all the characters
displayed in the text field area. After all, what good is a password everyone can read as you type it
in? Probably not very good one at all, and in this day and age when your private data is susceptible,
you need all the help you can get. Here's how a JPasswordField looks in Swing:
The JPasswordField 

The additional "security" methods on a JPasswordField change the behavior of a JTextField slightly
so you can't read the text:
 get/setEchoChar(): Gets/sets the character that appears in the JPasswordField every
time a character is entered. The "echo" is not returned when you get the password; the
actual character is returned instead.

 getText(): You should not use this function, as it poses possible security problems (for


those interested, the String would be kept in memory, and a possible heap dump could
reveal the password).

 getPassword(): This is the proper method to get the password from the JPasswordField,
as it returns a char[]containing the password. To ensure proper security, the array should
be cleared to 0 to ensure it does not remain in memory.
Back to top
JCheckBox/JRadioButton
The JCheckBox and JRadioButton components present options to a user, usually in a multiple-
choice format. What's the difference? From a practical standpoint, they aren't that different. They
behave in the same way. However, in common UI practices, they have a subtle difference:
JRadioButtons are usually grouped together to present to the user a question with a mandatory
answer, and these answers are exclusive (meaning there can be only one answer to the question).
The JRadioButton's behavior enforces this use. Once you select a JRadioButton, you cannot
deselect it unless you select another radio button in the group. This, in effect, makes the choices
unique and mandatory. The JCheckBox differs by letting you select/deselect at random, and allowing
you to select multiple answers to the question.
Here's an example. The question "Are you a guy or a girl?" leads to two unique answer choices
"Guy" or "Girl." The user must select one and cannot select both. On the other hand, the question
"What are your hobbies?" with the answers "Running," "Sleeping," or "Reading" should not allow
only one answer, because people can have more than one hobby.
The class that ties groups of these JCheckBoxes or JRadioButtons together is
the ButtonGroup class. It allows you to group choices together (such as "Guy" and "Girl") so that
when one is selected, the other one is automatically deselected.
Here's what JCheckBox and JRadioButton look like in Swing:
JCheckBox and JRadioButton 

The important ButtonGroup methods to remember are:


 add(): Adds a JCheckBox or JRadioButton to the ButtonGroup.

 getElements(): Gets all the components in the ButtonGroup, allowing you to iterate


through them to find the one selected.
Back to top
JMenu/JMenuItem/JMenuBar
The JMenu, JMenuItem, and JMenuBar components are the main building blocks to developing the
menu system on your JFrame. The base of any menu system is the JMenuBar. It's plain and boring,
but it's required because every JMenu and JMenuItem builds off it. You use
the setJMenuBar() method to attach the JMenuBar to the JFrame. Once it's anchored onto the
JFrame, you can add all the menus, submenus, and menu items you want.
The JMenu/JMenuItem difference might seem obvious, but is in fact underneath the covers and isn't
what it appears to be. If you look at the class hierarchy, JMenu is a subclass of JMenuItem.
However, on the surface, they have a difference: You use JMenu to contain other JMenuItems and
JMenus; JMenuItems, when chosen, trigger actions.
The JMenuItem also supports the notion of a shortcut key. As in most applications you've used,
Swing applications allow you to press Ctrl+(a key) to trigger an action as if the menu item itself was
selected. Think of the Ctrl+X and Ctrl+V you use to cut and paste.
In addition, both JMenu and JMenuItem support mnemonics. You use the Alt key in association with
a letter to mimic the selection of the menu itself (for example, pressing Alt+F then Alt+x closes an
application in Windows).
Here's what a JMenuBar with JMenus and JMenuItems looks like in Swing:
JMenuBar, JMenu, and JMenuItem 

The important methods you need for these classes are:


 JMenuItem and JMenu:
o get/setAccelerator(): Gets/sets the Ctrl+key you use for shortcuts.
o get/setText(): Gets/sets the text for the menu.
o get/setIcon(): Gets/sets the image used in the menu.

 JMenu only:
o add(): adds another JMenu or JMenuItem to the JMenu (creating a nested menu).
Back to top
JSlider
You use the JSlider in applications to allow for a change in a numerical value. It's a quick and easy
way to let users visually get feedback on not only their current choice, but also their range of
acceptable values. If you think about it, you could provide a text field and allow your user to enter a
value, but then you'd have the added hassle of ensuring that the value is a number and also that it
fits in the required numerical range. As an example, if you have a financial Web site, and it asks
what percent you'd like to invest in stocks, you'd have to check the values typed into a text field to
ensure they are numbers and are between 0 and 100. If you use a JSlider instead, you are
guaranteed that the selection is a number within the required range.
In Swing, a JSlider looks like this:
The JSlider 

The important methods in a JSlider are:


 get/setMinimum(): Gets/sets the minimum value you can select.

 get/setMaximum(): Gets/sets the maximum value you can select.

 get/setOrientation(): Gets/sets the JSlider to be an up/down or left/right slider.

 get/setValue(): Gets/sets the initial value of the JSlider.


Back to top
JSpinner
Much like the JSlider, you can use the JSpinner to allow a user to select an integer value. One major
advantage of the JSlider is its compact space compared to the JSlider. Its disadvantage, though, is
that you cannot easily set its bounds.
However, the comparison between the two components ends there. The JSpinner is much more
flexible and can be used to choose between any group of values. Besides choosing between
numbers, it can be used to choose between dates, names, colors, anything. This makes the
JSpinner extremely powerful by allowing you to provide a component that contains only
predetermined choices. In this way, it is similar to JComboBox, although their use shouldn't be
interchanged. You should use a JSpinner only for logically consecutive choices -- numbers and
dates being the most logical choices. A JComboBox, on the other hand, is a better choice to present
seemingly random choices that have no connection between one choice and the next.
A JSpinner looks like this:
The JSpinner 

The important methods are:


 get/setValue(): Gets/sets the initial value of the JSpinner, which in the basic instance,
needs to be an integer.
 getNextValue(): Gets the next value that will be selected after pressing the up-arrow
button.
 getPreviousValue(): Gets the previous value that will be selected after pressing the
down-arrow button.
Back to top
JToolBar
The JToolBar acts as the palette for other components (JButtons, JComboBoxes, etc.) that together
form the toolbars you are familiar with in most applications. The toolbar allows a program to place
commonly used commands in a quick-to-find location, and group them together in groups of
common commands. Often times, but not always, the toolbar buttons have a matching command in
the menu bar. Although this is not required, it has become common practice and you should attempt
to do that as well.
The JToolBar also offers another function you have seen in other toolbars, the ability to "float" (that
is, become a separate frame on top of the main frame).
The image below shows a non-floating JToolBar:
Non-floating JToolBar 

The important method to remember with a JToolBar is: is/setFloatable(), which gets/sets


whether the JToolBar can float.
Back to top
JToolTip
You've probably seen JToolTips everywhere but never knew what they were called. They're kind of
like the plastic parts at the end of your shoelaces -- they're everywhere, but you don't know the
proper name (they're called aglets, in case you're wondering). JToolTips are the little "bubbles" that
pop up when you hold your mouse over something. They can be quite useful in applications,
providing help for difficult-to-use items, extending information, or even showing the complete text of
an item in a crowded UI. They are triggered in Swing by leaving the mouse over a component for a
set amount of time; they usually appear about a second after the mouse becomes inactive. They
stay visible as long as the mouse remains over that component.
The great part about the JToolTip is its ease of use. The setToolTip() method is a method in
the JComponent class, meaning every Swing component can have a tool tip associated with it.
Although the JToolTip is a Swing class itself, it really provides no additional functionality for your
needs at this time, and shouldn't be created itself. You can access and use it by calling
thesetToolTip() function in JComponent.
Here's what a JToolTip looks like:
A JToolTip 

Back to top
JOptionPane
The JOptionPane is something of a "shortcut" class in Swing. Often times as a UI developer you'd
like to present a quick message to your users, letting them know about an error or some information.
You might even be trying to get some quick data, such as a name or a number. In Swing,
the JOptionPane class provides a shortcut for these rather mundane tasks. Rather than make
every developer recreate the wheel, Swing has provided this basic but useful class to give UI
developers an easy way to get and receive simple messages.
Here's a JOptionPane:
A JOptionPane 

The somewhat tricky part of working with JOptionPane is all the possible options you can use. While
simple, it still provides numerous options that can cause confusion. One of the best ways to learn
JOptionPane is to play around with it; code it and see what pops up. The component lets you
change nearly every aspect of it: the title of the frame, the message itself, the icon displayed, the
button choices, and whether or not a text response is necessary. There are far too many possibilities
to list here in this tutorial, and your best bet is to visit the JOptionPane API page to see its many
possibilities.
Back to top
JTextArea
The JTextArea takes the JTextField a step further. While the JTextField is limited to one line of text,
the JTextArea extends that capability by allowing for multiple rows of text. Think of it as an empty
page allowing you to type anywhere in it. As you can probably guess, the JTextArea contains many
of the same functions as the JTextField; after all, they are practically the exact same component.
However, the JTextArea offers a few additional important functions that set it apart. These features
include the ability to word wrap (that is, wrap a long word to the next line instead of cutting it off mid-
word) and the ability to wrap the text (that is, move long lines of text to the next line instead of
creating a very long line that would require a horizontal scroll bar).
A JTextArea in Swing looks like you'd probably expect:
A JTextArea 

The important methods to enable line wrapping and word wrapping are:
 is/setLineWrap(): Sets whether the line should wrap when it gets too long.

 is/setWrapStyleWord(): Sets whether a long word should be moved to the next line


when it is too long.
Back to top
JScrollPane
Building off of the example above, suppose that the JTextArea contains too much text to contain in
the given space. Then what? If you think that scroll bars will appear automatically, unfortunately, you
are wrong. The JScrollPane fills that gap, though, providing a Swing component to handle all scroll
bar-related actions. So while it might be a slight pain to provide a scroll pane for every component
that could need it, once you add it, it handles everything automatically, including hiding/showing the
scroll bars when needed.
You don't have to deal with the JScrollPane directly, outside of creating it using the component to be
wrapped. Building off the above example, by calling the JScrollPane constructor with the JTextArea,
you create the ability for the JTextArea to scroll when the text gets too long:
JScrollPane scroll = new JScrollPane(getTextArea());
add(scroll);

This updated example looks like this:


JScrollPane example 

The JScrollPane also exposes the two JScrollBars it will create. These JScrollBar components also
contain methods you can use to change their behavior (although they are outside the scope of this
tutorial).
The methods you need to work with JScrollPane are:
 getHorizontalScrollBar(): Returns the horizontal JScrollBar component.

 getVerticalScrollBar(): Returns the vertical JScrollBar component.

 get/setHorizontalScrollBarPolicy(): This "policy" can be one of three things:


Always, Never, or As Needed.
 get/setVerticalScrollBarPolicy(): The same as the horizontal function.
Back to top
JList
The JList is a useful component for presenting many choices to a user. You can think of it as an
extension to the JComboBox. JList provides more choices and adds the capability for multiple
choices. The choice between a JList and JComboBox often comes down to these two features: If
you require multiple choices or if the options include more than 15 choices (although that number is
not a general rule), you should always choose a JList.
You should use the JList in conjunction with the JScrollPane, as demonstrated above, because it
can present more options than its space can contain.
The JList contains the notion of a selection model (also seen in JTables), where you can set your
JList to accept different types of choices. These types are the single selection, where you can only
select one choice, the single interval selection, where you can only select contiguous choices, but as
many as desired, or the multiple interval selection, where you can select any number of choices in
any combination.
The JList is the first of what I call the "complex components," which also include the JTable and the
JTree that allow a large amount of custom changes, including changing the way the UI looks and
how it deals with data. Because this tutorial only strives to cover the basics, I won't get into these
more advanced functions, but it's something to remember when working with these components --
they present a more difficult challenge than those components I've introduced up to this point.
The JList appears like this in Swing:
The JList 

There are many functions in the JList to deal with the data, and as I said, these just touch the
surface of everything required to work in detail with the JList. Here are the basic methods:
 get/setSelectedIndex(): Gets/sets the selected row of the list; in the case of multiple-
selection lists, an int[] is returned.
 get/setSelectionMode(): As explained above, gets/sets the selection mode to be either
single, single interval, or multiple interval.
 setListData(): Sets the data to be used in the JList.

 get/setSelectedValue(): Gets the selected object (as opposed to the selected row


number).
Back to top
JTable
Think of an Excel spreadsheet when you think of a JTable and that should give you a clear picture of
what the JTable does in Swing. It shares many of the same characteristics: cells, rows, columns,
moving columns, and hiding columns. The JTable takes the idea of a JList a step further. Instead of
displaying data in one column, it displays it in multiple columns. Let's use a person as an example. A
JList would only be able to display one property of a person -- his or her name for instance. A
JTable, however, would be able to display multiple properties -- a name, an age, an address, etc.
The JTable is the Swing component that allows you to provide the most information about your data.
Unfortunately, as a trade-off, it is also notoriously the most difficult Swing component to tackle. Many
UI developers have gotten headaches trying to learn every detail of a JTable. I hope to save you
from that here, and just get the ball rolling with your JTable knowledge.
Many of the same concepts in JLists extend to JTables as well, including the idea of different
selection intervals, for example. But the one-row idea of a JList changes to the cell structure of a
JTable. This means you have different ways to make these selections in JTables, as columns, rows,
or individual cells.
In Swing, a JTable looks like this:
A JTable 

Ultimately, a majority of the functionality of a JTable is beyond the scope of this tutorial;
"Intermediate Swing" will go into more detail on this complex component.
Back to top
JTree
The JTree is another complex component that is not as difficult to use as the JTable but isn't as easy
as the JList either. The tricky part of working with the JTree is the required data models.
The JTree takes its functionality from the concept of a tree with branches and leaves. You might be
familiar with this concept from working with Internet Explorer in Windows -- you can expand and
collapse a branch to show the different leaves you can select and deselect.
You will most likely find that the tree is not as useful in an application as a table or a list, so there
aren't as many helpful examples on the Internet. In fact, like the JTable, the JTree does not have any
beginner-level functions. If you decide to use JTree, you will immediately be at the intermediate level
and must learn the concepts that go with it. On that note, the example application does not cover the
JTree, so unfortunately, neither the beginner nor the intermediate tutorial will delve into this less
popular component.
However, there are times when a tree is the logical UI component for your needs. File/directory
systems are one example, as in Internet Explorer, and the JTree is the best component in the case
where data takes a hierarchical structure -- in other words, when the data is in the form of a tree.
In Swing, a JTree looks like this:
A JTree 

Swing concepts
Layouts, models, and events, oh my!
Now that you know about most (but definitely not all) of the components you can use to make a UI,
you have to actually do something with them. You can't just place them randomly on the screen and
expect them to instantly work. You must place them in specific spots, react to interaction with them,
update them based on this interaction, and populate them with data. More learning is necessary to
fill in the gaps of your UI knowledge with the other important parts of a UI.
Therefore, let's examine:
 Layouts: Swing includes a lot of layouts, which are classes that handle where a component
is placed on the application and what should happen to them when the application is resized
or components are deleted or added.

 Events: You need to respond to the button presses, the mouse clicks, and everything else a
user can do to a UI. Think about what would happen if you didn't -- users would click and
nothing would change.

 Models: For the more advanced components (Lists, Tables, Trees), and even some easier
ones such as the JComboBox, models are the most efficient way to deal with the data. They
remove most of the work of handling the data from the actual component itself (think back to
the earlier MVC discussion) and provide a wrapper for common data object classes (such
as Vector and ArrayList).
Back to top
Easy layouts
As mentioned in the last section, a layout handles the placement of components on the application
for you. Your first question might be "why can't I just tell it where to go by using pixels?" Well, you
can, but then you'd immediately be in trouble if the window was resized, or worse, when users
changed their screen resolutions, or even when someone tried it on another OS. Layout managers
take all those worries away. Not everyone uses the same settings, so layout managers work to
create "relative" layouts, letting you specify how things should get resized relative to how the other
components are laid out. Here's the good part: it's easier than it sounds. You simply
call setLayout(yourLayout) to set up the layout manager. Subsequent calls to add()add the
component to the container and let the layout manager take care of placing it where it belongs.
Numerous layouts are included in Swing nowadays; it seems there's a new one every release that
serves another purpose. However, some tried-and-true layouts that have been around forever, and
by forever, I mean forever -- since the first release of the Java language back in 1995. These layouts
are the FlowLayout, GridLayout, and BorderLayout.
The FlowLayout lays out components from left to right. When it runs out of space, it moves down to
the next line. It is the simplest layout to use, and conversely, also the least powerful layout:
setLayout(new FlowLayout());
add(new JButton("Button1"));
add(new JButton("Button2"));
add(new JButton("Button3"));
The FlowLayout at work 

The GridLayout does exactly what you'd think: it lets you specify the number of rows and the number
of columns and then places components in these cells as they are added:
setLayout(new GridLayout(1,2));
add(new JButton("Button1"));
add(new JButton("Button2"));
add(new JButton("Button3"));

The GridLayout at work 


The BorderLayout is still a very useful layout manager, even with all the other new ones added to
Swing. Even experienced UI developers use the BorderLayout often. It uses the notions of North,
South, East, West, and Center to place components on the screen:
setLayout(new BorderLayout());
add(new JButton("Button1"), "North");
add(new JButton("Button2"), "Center");
add(new JButton("Button3"), "West");

The BorderLayout at work 

Back to top
GridBagLayout
While the examples from above are good for easy layouts, more advanced UIs need a more
advanced layout manager. That's where the GridBagLayout comes into play. Unfortunately, it is
extremely confusing and difficult to work with, and anyone who has worked with it will agree. I can't
disagree either; but despite its difficulties, it's probably the best way to create a clean-looking UI with
the layout managers built into Swing.
Here's my first bit of advice: In the newest versions of Eclipse, there's a built-in visual builder that
automatically generates the required GridBagLayout code needed for each screen. Use it! It will
save countless hours of fiddling around with the numbers to make it just right. So while I could use
this slide to explain how GridBagLayout works and how to tweak it to make it work best, I'll just offer
my advice to find a visual builder and generate the code. It will you save hours of work.
Back to top
Events
Finally, we get to one of the most important parts of Swing: dealing with events and reacting to
interaction with the UI. Swing handles events by using the event/listener model. This model works by
allowing certain classes to register for events from a component. This class that registers for events
is called a listener, because it waits for events to occur from the component and then takes an action
when that happens. The component itself knows how to "fire" events (that is, it knows the types of
interaction it can generate and how to let the listeners know when that interaction happens). It
communicates this interaction with events, classes that contain information about the interaction.
With the technical babble aside, let's look at some examples of how events work in Swing. I'll start
with the simplest example, a JButton and printing out "Hello" on the console when it is pressed.
The JButton knows when it is pressed; this is handled internally, and there's no code needed to
handle that. However, the listener needs to register to receive that event from the JButton so you
can print out "Hello." The listener class does this by implementing the listener interface and
then calling addActionListener() on the JButton:
// Create the JButton
JButton b = new JButton("Button");
// Register as a listener
b.addActionListener(new HelloListener());

class HelloListener implements ActionListener


{
// The interface method to receive button clicks
public void actionPerformed(ActionEvent e)
{
System.out.println("Hello");
}
}

A JList works in a similar way. When someone selects something on a JList, you want to print out
what object is selected to the console:
// myList is a JList populate with data
myList.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
Object o = myList.getSelectedItem();
System.out.println(o.toString());
}
}
);
From these two examples, you should be able to understand how the event/listener model works in
Swing. In fact, every interaction in Swing is handled this way, so by understanding this model, you
can instantly understand how every event is handled in Swing and react to any possible interaction a
user might throw at you.
Back to top
Models
Now, you should know about the Java Collections, a set of Java classes that handle data. These
classes include an ArrayList, a HashMap, and a Set. Most applications use these classes
ubiquitously as they shuttle data back and forth. However, one limitation arises when you need to
use these data classes in a UI. A UI doesn't know how to display them. Think about it for a minute. If
you have a JList and an ArrayList of some data object (such as a Person object), how does
the JList know what to display? Does it display the first name or both the first name and the last
name?
That's where the idea of a model comes in. While the term model refers to the larger scope, in this
tutorial's examples I use the term UI model to describe the classes that components use to display
data.
Every component that deals with a collection of data in Swing uses the concept of a model, and it is
the preferable way to use and manipulate data. It clearly separates the UI work from the underlying
data (think back to the MVC example). The model works by describing to the component how to
display the collection of data. What do I mean by describing? Each component requires a slightly
different description:
 JComboBox requires its model to tell it what text to display as a choice and how many
choices exist.

 JSpinner requires its model to tell it what text to display, and also what the previous and next
choices are.

 JList also requires its model to tell it what text to display as a choice and how many choices
exist.

 JTable requires much more: It requires the model to tell it how many columns and rows exist,
the column names, the class of each column, and what text to display in each cell.

 JTree requires its model to tell it the root node, the parents, and the children for the entire
tree.
Why do all this work, you might ask. Why do you need to separate all this functionality? Imagine this
scenario: You have a complicated JTable with many columns of data, and you use this table in many
different screens. If you suddenly decide to get rid of one of the columns, what would be easier,
changing the code in every single JTable instance you used, or changing it in one model class you
created to use with every JTable instance. Obviously, changing fewer classes is better.
Back to top
Model examples
Let's take a look at how a model works by using it with an easy example, the JComboBox. In the
previous slide of a JComboBox, I showed you how to add items to the data by calling setItem().
While this is acceptable for simple demonstrations, it isn't much use in a real application. After all,
when there are 25 choices, and they are continually changing, do you really want to loop through
them each time calling addItem() 25 times? Certainly not.
The JComboBox contains a method call setModel() that accepts an instance of
the ComboBoxModel class. You should use this method instead of the addItem() method to create
the data in a JComboBox.
Suppose you have an ArrayList with the alphabet as its data ("A", "B", "C", etc.):
MyComboModel model = new MyComboModel(alphaList);
myComboBox.setModel(model);

public class MyComboModel implements ComboBoxModel


{
private List data = new ArrayList();
private int selected = 0;

public MyComboModel(List list)


{
data = list;
}

public void setSelectedItem(Object o)


{
selected = data.indexOf(o);
}

public Object getSelectedItem()


{
return data.get(selected);
}

public int getSize()


{
return data.size();
}

public Object getElementAt(int i)


{
return data.get(i);
}
}

The great part about using a model is that you can reuse it over and over again. As an example, say
the JComboBox's data needs to change from letters of the alphabet to the numbers 1 to 27. You can
achieve this change in one simple line that uses the new List of data to populate the JComboBox
without using additional code:
myComboBox.setModel(new MyComboModel(numberList));

Models are a beneficial feature in Swing as they provide the ability for code reuse and make dealing
with data much easier. As is often the case in large-scale applications, the server-side developers
create and retrieve the data and pass it to the UI developer. It's up to the UI developer to deal with
this data and display it properly, and models are the tools to get this done.

Putting it all together


Example application
After all these examples, you probably want to see this stuff in action. Enough with the pretty
pictures. Let's get down to a concrete example that ties together everything you've learned so far in
this tutorial.
Here's the concept for the example application: a simple flight reservation system. It lets the user
type in a departure and arrival city and then press a button to search. It has a fake database with
flights stored in it. This database can be searched, and a table is used to display the results of the
search. Once the table populates, users can select flights from the table and buy tickets by changing
the number of tickets they desire and clicking a button.
It's a seemingly simple application that allows you to see all the parts of Swing in practice. This
example application should answer any questions you might have had from previous sections.
Before I start, let's look at the finished product:
Example application 

Back to top
Step 1: Lay out the components
As I mentioned earlier, there's little need to learn complex layouts because you can use a visual
editor.
Back to top
Step 2: Initialize the data
The application can't work without data. Let's think about what kind of data you need in this
application. First, you need a list of cities to choose from for the departure and destination cities.
Then, you need a list of flights to search.
For this example, I use some fake data because the focus of the application is on Swing not on the
data. You create all the data in the DataHandler class. This class manages the departure and
destination cities and also handles flight search and record retrieval.
The cities are stored as simple Strings. The flights however, are stored in data objects
called Flights that contain fields for the departure city, destination city, flight number, and number
of available tickets.
Now, with all that red tape out of the way, let's get back to the application.
Back to top
Step 3: Handling events
Let's examine the application and consider what actions must take place. First, you need to know
when a user presses the Search button, so you can search the data for flights. Second, you need to
know when a user selects the table of records to prevent possible errors when a user tries to buy a
record with no records selected. Finally, you must be aware of when a user presses the Purchase
button to send the purchasing data back to the data handler class.
Let's start with the Search button. As outlined above, you must call
the addActionListener() method on the button to register for events from a button press. To
keep things simple, I use the FlightReservation class to listen for all possible events. Here's the
code to handle the Search button press:
String dest = getComboDest().getSelectedItem().toString();
String depart = getComboDepart().getSelectedItem().toString();
List l = DataHandler.searchRecords(depart, dest);
flightModel.updateData(l);

The two cities are gathered from the combo boxes and used to search the records for the
corresponding flights. Once the flights are found, they are passed to the table's table model; more on
how the table models work below. But know that once the table model has the updated data, it will
display the results.
Next, let's examine what happens when a user presses the Purchase button:
Object o = flightModel.getData().get(getTblFlights().getSelectedRow());
int tixx = Integer.parseInt(getTxtNumTixx().getText());
DataHandler.updateRecords(o, tixx);

Now, conversely, when a user presses the Purchase button, the table model figures out which flight
the user selected and then passes this record and the number of tickets the user wishes to purchase
to the data handler.
Finally, you need to error-check and ensure that someone doesn't try to purchase a ticket without
selecting a flight in the table. The easiest way to do this is to disable the components a user would
use to purchase tickets (the text field and button) and only enable them when a user selects a row:
boolean selected = getTblFlights().getSelectedRow() > -1;
getLblNumTixx().setEnabled(selected);
getTxtNumTixx().setEnabled(selected);
getBtnPurchase().setEnabled(selected);

Back to top
Step 4: Models
Next, let's look at the models you use to handle all the data flying back and forth in this application.
By analyzing the application and going through this demo, you should clearly see that you need two
models: a model for the JComboBoxes and a model for the JTable.
Let's begin with the easiest, the JComboBox's model. I won't paste the code in here because it's the
same as the example a few slides ago (and in fact can be used for any of your JComboBoxes).
There are some important things to note though: Remember the advantage of using models, and
you'll see it in use here. Although you only have one model class, you reuse it by creating two
instances of it and supplying one to each of the JComboBoxes. That way both instances can handle
their own data, but of course, you only write one class to do it. Here's how you set it up:
comboModel1 = new CityComboModel(DataHandler.getCities());
comboModel2 = new CityComboModel(DataHandler.getCities());

Let's move on to the JTable's model. This model is a bit more complicated than the JComboBox and
requires a little more inspection. Let's start with your knowledge of the ComboBoxModel and see
what you need to add for a JTable. Because a JTable contains data like a ComboBox, but in multiple
columns, you need a lot more information from the model dealing with the column information. So, in
addition to knowing the number of rows of data, you need to know the number of columns, the
column names, and the value at an individual cell, instead of just the object itself. This allows you to
not only display a data object, but also to display fields of a data object. In the case of this example,
you don't display the Flight object; you instead display the fields of a departure city, destination
city, flight number, and the number of tickets available. Below is the code you use to create
the TableModel and how to set it on the JTable:
flightModel = new FlightTableModel();
getTblFlights().setModel(flightModel);

Because of the amount of code you need to create a TableModel , I'll hold off on pasting it here, but
will instead direct you to the source code of the sample application (see Resources to download the
code) to take a closer look at how it works. Also, this has really just touched on the TableModel. As
I mentioned earlier, the JTable is the most difficult and complex component to work with in Swing
and its parts, including the TableModel, are not any easier. That said, I will revisit
the TableModel in "Intermediate Swing" in addition to other JTable functionality.
Back to top
Step 5: Bells and whistles
Users have come to expect a certain amount of bells and whistles in any application, both as extra
functionality and also as a way to prevent the occurrence of errors. In this example, although the
basic functionality of searching for a flight and purchasing tickets works, you haven't addressed
possible errors that might happen. For error-proofing, you need to add an error message when a
user attempts to order more tickets than are available. How do you display errors? If you think back
to the slide on the JOptionPane, Swing has a ready-made component for this type of instant
feedback.
Let's look at the error condition and see what triggers the error message:
try
{
DataHandler.updateRecords(o, tixx);
}
catch (Exception ex) {
// display error message here
}

Now let's take care of the error message. Remember the JOptionPane and its plentiful amount of
options. Let's lay out the options you want in your error message before you decide what kind of
JOptionPane to create. It should be an error message and not an informative message. Use a
simple title such as "Error." The detailed message consists of what the exception says. And finally,
the users have made an error, so simple OK and Cancel buttons should suffice.
Here's the code to create that exact JOptionPane:
JOptionPane.showConfirmDialog(this, ex.getMessage(), "Error",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE);

And here's what it looks like:


Example error message 

Back to top
And in the end ...
Hopefully, you now understand how everything described in this tutorial came together to form a
basic but functional Swing application. Unfortunately, I can't squeeze every possible line of code
from the example application into these slides, although I encourage you to look through the
example application to see for yourself how it all developed.
Especially note how I used the models to ease the process of dealing with the data. Using some
rather simple code, you can handle any kind of data that both the JTable and JComboBox can
receive. Also, note the event/listener relationships -- how the components that interact all take on the
event/listener relationship, meaning that interested parties (other components especially) must
register for these events.
Finally, if you decide to continue to the intermediate tutorial, I will build off your knowledge of this
existing flight reservation system. So, if you choose to move to the next phase, please be sure you
understand how that system works in its basic form.

You might also like