Introduction To Swing: Before You Start
Introduction To Swing: Before You Start
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).
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/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/setLocation(): Gets/sets the location on the screen where the frame should appear.
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");
}
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);
}
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.
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.
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
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
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.
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.
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.
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"));
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());
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);
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.
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);
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.