Building An Application: Part1
Building An Application: Part1
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
-Redistribution of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
Neither the name of Sun Microsystems, Inc. or the names of contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
This software is provided "AS IS," without a warranty of any kind. ALL EXPRESS OR IMPLIED
CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED
WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND
ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS
A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE
THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS
SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
You acknowledge that this software is not designed, licensed or intended for use in the design,
construction, operation or maintenance of any nuclear facility.
8/17/01
Building an Application:
Introduction
by Dana Nourie, October 2001
Overview
What You Need
Start the Tutorial
Overview
Many JavaTM Application Programming Interfaces (APIs) are used in application programming. As you learn how to
create buttons or write text to files, figuring out how to fit the technologies together into a single application can be
difficult and confusing. Seeing an application built from the ground up can be more useful than just reading how to
make a menu bar or read a file into a Graphical User Interface (GUI).
This six-part tutorial details application development, using a single fully-featured application as an example. You'll
learn how to:
● Use predefined objects and creating new objects.
● Create GUI components, such as tabbed panes, buttons, menus, text fields, and text areas.
You'll also learn about packages and packaging an application for distribution, and the Java technologies referred to as
Java I/O, Project Swing, and AWT.
The application created for this series tutorial is a simple dive log, such as one a scuba diver might use to record dive
depth, water temperature and conditions, and air consumed.
Though to a certified scuba diver, this application falls short of being a robust, detailed dive log, it serves as an
example application, demonstrating features commonly used in application programming.
The tutorial begins with simple concepts and leads to more complex programming techniques, introducing new
concepts and repeating programming techniques throughout.
● The first half of each series part explains how to create the GUI for that particular pane.
● The second half details the functionality of any buttons, menus, text fields, and so forth.
Preparation
Before learning about the code for the Dive Log, you need to create a special directory for the files and images that
build this application.
Saving Files
The Dive Log is designed from many classes, therefore many files. Keep them organized and in place.
C:\divelog\images
%home/usr/divelog/images
Each object has its own characteristics, or state. The Title object is different from the Tab objects, and the Image
objects are different from the Text Area objects. But before an object comes into existence, the design must be written.
Before cars and houses are built, someone designs a blueprint. Before a batch of cookies is baked, a recipe is written.
Software objects are also created with a specific design.
The design for a software object is called a class. Classes detail, or specify, exactly how an object should appear and
how it is to behave. Instructions for creating software objects are carefully written into the class using variables for
data and information, and methods for manipulation of that data and information.
Do you think there is a limit to how many
objects make up an application?
Yes No
Submit
About Classes
More About Objects
The classes that are a part of the JavaTM J2SETM download are complete, Classes, Objects, and Constructors:
predefined classes you can use in your applications. These predefined What's the Difference?
classes provide features frequently used in creating applications, such as
writing to and reading from files, creating graphical components like Object-Oriented Programming Defined
buttons and menus, and making web pages interactive. What Is an Object?
To create an application, though, you need to define your own classes as
well as using predefined classes from the Java library.
When you define a class, you are planning how the object created from that class is going to appear and behave. A
class contains:
● Fields
Fields, or variables, store data and are frequently called data members. These variables often differentiate one
object from another and define attributes such as amounts, names, titles, and so forth.
● Methods
Methods manipulate variables or objects, such as doing math operations, inputting characters or strings, printing
text to the screen, adding a button to a menu bar, or simply instantiating an object.
What are Keywords? More on fields and methods later. For now, look at some kinds of classes
you'll write to create objects for the Dive Log.
Keywords are reserved words that cannot
be used as variable, method, or class You'll need a frame for the application. Other components of the
names because they are used in JavaTM application are organized into tabbed panes. Each of those tab objects has
programming syntax. white text and the background color blue. Later, you'll learn what goes on
for, while, public, if, and each pane and how to develop those objects. For now, you'll learn about
class are some keywords. frame and tab objects.
Designing the classes for these objects makes more sense as code is covered in detail.
You will start with designing a few objects (the frame and tabs), then build on those classes as you progress through
the lessons.
package divelog;
package divelog;
Submit
The purpose of using the package keyword is to group and store related
classes in a container, and to make the classes in a package accessible to
the compiler. More About Objects
Naming Conventions
Packages
Code Conventions for the Java
The JavaTM programming language has many predefined classes that can Programming Language
be used in applications. There are so many that the classes have been
It's All in the Packaging
organized into groups called packages.
Creating a Package
For instance, classes that support I/O (input and output) are contained
within the java.io package, and classes for creating applets are in the
java.applet package. Putting classes into packages organizes them
conveniently for the compiler and for you.
/java/
/applet
C:\divelog
or
%/usr/home/divelog
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
These import statements allow easy access of the predefined classes in those packages. In this case, the packages with
classes for GUI components have been imported, so now you needn't type out the fully qualified name, but instead can
directly name the class you need to use. In other words, import statements give you a shortcut to class names in other
packages. You'll see examples of this throughout the tutorial.
Class Definition
After package names and import statements, you are ready to define the class. The first class to define is the
framework for the application itself, the DiveLog class:
Notice this class name begins with an uppercase letter. Naming convention calls for the first letter of a class name to
be in uppercase, and the first letter of method names to be in lowercase. Using this naming scheme makes it easier to
read code because class names differ from method and variable names.
The { begins the class definition. At the end of the class you must have a closing }. Curly braces signify the beginning
and ending of classes and method bodies and statements.
Missing or extra curly braces are one of the most common causes of compilation errors. It's a good idea to create curly
braces in pairs, then insert your code between them, such as in this method:
multiline comments. */
First:
Second:
System.exit(0);
Declaring Variables
Objects contain data, and variables are holders of that data, or rather references to the data. The idea behind using a
variable, a reference to the data, rather than the data itself is so you can manipulate the data.
For instance, in the example below birthYear and currentYear are given values, while age represents
birthYear subtracted from currentYear:
birthYear = 1981;
currentYear = 2001;
In this example, the variable age has a value of 20. Change the value of either birthYear or currentYear and
the value of age changes accordingly.
Variables don't have to be hardcoded. The variable birthYear can instead be assigned to a text field for a user to
enter a number. Then the currentYear variable could be hardcoded, declared with the current year, such as 2001.
This kind of variable use is what makes applications dynamic. While one user types in 1962 as the value of the
birthYear, another user types in 1982 as the birthYear, a different value for the age is calculated according to
the user input.
Using variables in this way to represent data, a programmer doesn't have to know what the value is going to be in
advance. Bank applications are likely to have variables representing customers names, addresses, account numbers,
checking account amounts, and so forth, along with hardcoded variable values such as interest rates and bank fees.
In the Java programming language, variable types must be declared with the variable name. In other words, the
compiler has to know if the variable is going to represent a String, an int, or some other type. For the example
above to compile, the code must be rewritten:
Look closely at the code above, then see if you can answer the question below:
Which variable declaration is written incorrectly?
Submit
Variables
double amount = 80.11; Java 2 Platform Documentation
Variable Types
The JavaTM programming language is sometimes called a strongly typed language because you must declare variables
as a specific type before using them. A variable can be one of two basic types:
● Primitive type
● Reference type
Primitive Type
Primitive, or simple, types are the only types that are not objects.
The following are primitives:
● Integers, such as byte, short, int, and long
In other words, primitives are what you commonly call numbers, single characters, or true or false. Numbers can also
be represented as a String, but if you declare a number as a String, you cannot do mathematic operations on it,
and it becomes an object of type String.
Also, whenever numbers are entered at the command line or in a GUI, the entry is accepted as a String object and
must be converted to do calculations. Special classes called wrappers make this conversion and are covered later in
this tutorial.
Because primitive types are not objects, declaring them is a one-step process:
Reference Type
JFrame and JTabbedPane are reference types. In this case, the variables dlframe and tabbedPane refer to
classes in the javax.swing package. In the declarations above, no object has been created yet. For now, this code
just tells the compiler to reserve some memory for these two variables. Later in the code, objects of the JFrame and
JTabbedPane classes are instantiated, or created, to build a frame for the Dive Log application, with a tabbed pane
included.
Attribute Access
If none is provided Default or package, meaning from any class in the same package
You'll see more about variables and access attributes as you create classes for the Dive Log. The important point to
keep in mind is that the variables declared so far can be accessed only from the DiveLog.java class, and as yet
they have not been assigned a value. They've only been declared as a reference type, specific to the JFrame and
JTabbedPane classes. Until the key word new is used to instantiate them, these are not yet objects in memory.
Instantiating the JFrame and JTabbedPane objects occurs within a method. As mentioned earlier, methods make
something happen. Methods instantiate objects, perform math calculations, and more.
Constructing Objects
One important type of method to understand is a special method called a constructor. The main purpose of a
constructor is to set the initial state of an object when the object is created, or instantiated. A class details the data an
object contains and can work with, methods it uses to work with that data, and a constructor tells how the object is to
be built.
Constructors look like other methods with a few differences, which are described in the next section.
Use the DiveLog constructor as a guide to answer the following question:
public DiveLog()
A. public Button(){}
B. public Button(String mode){}
C. A and B are both correct.
Submit
Instantiate a Customer object by calling the Customer class constructor with the new keyword:
public DiveLog()
{ // Opens constructor
Notice this class constructor has the same name as the class itself and does not require any parameters, which ()
shows. The opening { begins the body of the constructor.
Recall at the beginning of DiveLog.java, the variable dlframe was declared, but not yet assigned a value. Now,
within the constructor, the JFrame constructor is assigned to the variable dlframe. A JFrame is simply a
predefined Java class that builds a frame with a border, a minimize and maximize button, and a close box. A JFrame
is a Swing container that can hold other containers and components. DiveLog initializes a JFrame as follows:
If you read the JFrame class documentation under the heading Constructor Summary, you'll discover several
constructors available for building a JFrame object:
● The first is the default constructor, which creates a JFrame that's invisible and doesn't have any other features.
● The second constructor creates a JFrame in the specified GraphicsConfiguration of a screen device
and a blank title.
● The third constructor accepts a String as an argument, and creates a JFrame with the title provided. This is
the constructor called in the DiveLog constructor.
● The last constructor creates a JFrame with the specified title and the specified GraphicsConfiguration
of a screen device.
Though a JFrame object is initialized with the title for the frame and assigned to the variable dlframe, it still needs
a bit more work.
The following snippet of code has some advanced concepts involved, so it will be explained fully at a later time. This
method insures that the Dive Log application can shut down fully and properly.
dlframe.addWindowListener(new WindowAdapter()
System.exit(0);
});
public DiveLog()
dlframe.addWindowListener(new WindowAdapter()
System.exit(0);
});
Next, the JTabbedPane is instantiated. At the top of the DiveLog class, the variable tabbedPane was declared
as type JTabbedPane, but not assigned. Here, in the constructor, the keyword new is used to create the
JTabbedPane object, passing in the necessary parameters to position the tabs on the left side of the window pane,
and the variable is assigned to the JTabbedPane object:
tabbedPane =
new JTabbedPane(SwingConstants.LEFT);
JTabbedPane is another handy Java class that creates tabs in an application and has two available constructors to
call. The DiveLog constructor calls the JTabbedPane class constructor that makes it possible to create tabs at the
TOP, BOTTOM, LEFT, or RIGHT. Simply type in your preference when calling the constructor. In the DiveLog
case, the tabs are set to the left of the screen. You can place them wherever you like.
tabbedPane.setBackground(Color.blue);
tabbedPane.setForeground(Color.white);
The methods setBackground and setForeground are called and used on the tabbedPane object, setting the
background and foreground colors. You can use these methods on any GUI component to change background and
foreground colors, simply by naming the object through its variable, then passing in the Color class as a parameter,
along with the color you want to use.
tabbedPane =
new JTabbedPane(SwingConstants.LEFT);
tabbedPane.setBackground(Color.blue);
tabbedPane.setForeground(Color.white);
Predefined methods are easy to use. When you decide you want to create an object of a certain class, then look that
class up in the documentation and see what methods are available. Create an instance of that class using the new
operator and assign a variable, then call the method by using the dot operator as demonstrated above. You'll see many
more examples of this as you progress through the Dive Log.
At this point, the JTabbedPane class constructor has been called and the object instantiated, but the individual tabs
have not been added.
How are the individual tabs added to the JTabbedPane?
Submit
Methods
populateTabbedPane();
Since the populateTabbedPane method is called in the DiveLog constructor, you must define a
populateTabbedPane method outside the constructor, which is covered in the next section.
populateTabbedPane();
Defining Methods
A method is a group of programming statements that is given a name. The statements can contain other method calls,
simple print statements, or complex operations. When a method is called, the flow of control transfers to that method.
Each statement in the method body is executed, one at a time, then control returns to the location where the call was
made.
A method's header gives the compiler important information:
● access modifier (optional)
Tells the compiler whether other classes or packages have access to this method
● return type (required)
If the method returns an object or primitive data, the type must be listed here. If the method doesn't return a
value, then it is type void.
● method name (required)
Like classes, methods need a name. Generally methods begin with a lowercase letter.
● parameter list or () (required)
In the DiveLog class, the method created to populate the tabbedPane object is called populateTabbedPane
because it is descriptive, making it easy to guess what the method does.
tabbedPane.addTab(
"Welcome",
null,
The last addTab method signature creates a tab with a title, a component,
and a string tip. Include the title by typing text enclosed in quote marks.
Since an icon is not provided on the tabs, null takes place of an icon
image name.
Next, a component, or more specifically, a new class called Welcome is
instantiated. The Welcome class displays the content for this tab, and is
covered fully in the next part of this Dive Log tutorial. Lastly, text for a
string tip is provided. This text appears when a user mouses over the tab.
Each tab initializes a new class that contains the code for that particular tabbed page:
tabbedPane.addTab(
"Welcome",
null,
new Welcome(),
"Diver Data",
null,
new Diver(),
tabbedPane.addTab(
"Log Dives",
null,
new Dives(),
tabbedPane.addTab(
"Statistics",
null,
new Statistics(),
tabbedPane.addTab(
null,
new WebSite(),
tabbedPane.addTab(
null,
new Resources(),
"of resources");
Tabs that initialize other classes provide organization for the application and prevent classes from becoming overly
long and confusing.
What happens if you do not create classes called Welcome.java,
Diver.java, Dives.java, and so forth?
Submit
What will happen if you do not create classes yet called Welcome, Diver, Dives, and so forth?
You get a compilation error if the compiler cannot locate every class that is called in the code. To prevent this type of
error, create classes that can be instantiated. For now, they don't need to do anything other than exist in memory.
Creating Placeholder Classes
The individual classes initialized with each tab are covered in the next More on Creating Objects
installments of the Dive Log tutorial. The Welcome class is the next class
to be covered in detail. Creating Objects
In the meantime, though, so you can compile the DiveLog class, create Learn How To Store Data in Objects
empty classes that do nothing but initialize placeholders. For now, these Beginning Java Objects
classes consist only of package and import statements, the class header,
and the closing and opening curly braces. Each class is saved in its own Creating Class Instances
file.
package divelog;
/**
* application.
* @version 1.0
*/
import javax.swing.*;
import java.awt.*;
{ //Opens class
}//Closes class
As you work through the tutorial, you'll be instructed to open these files later and fill them in as each class is covered.
This method is private to prevent other packages and classes from accessing it, and it is void because its only
purpose is to build a menu with a menu item called Exit, and to exit cleanly when Exit is selected. The name suggests
what the method does, and the parentheses are empty because no parameters are required.
Step 3 below shows you how to create application menus using the JMenuBar, JMenu, and JMenuItem classes.
You instantiate a new JMenuBar and assign it to mb. Next, you instantiate a JMenu object with the variable menu,
and pass in the String "File" to name a new menu. Lastly, instantiate a menu item object, including the
parameter "Exit" and assigning it to item.
// Method header
// and JMenuItem.
After the buildMenu is called in the DiveLog constructor, the code completes the construction of the DiveLog
object. Next the code needs to get the content pane and adds the tabbedPane object. The frame you have created for
the application is a container, and in this case is the top-level container. All Swing containers have another container
within, which is the content pane, where you place all child containers and components.
//menu item.
item.addActionListener(new ActionListener()
System.exit(0);
Pull the menu objects together, using the predefined add method, passing in the
variable reference.
2. Add the following:
menu.add(item);
mb.add(menu);
dlframe.setJMenuBar(mb);
Though it may seem as though the objects created so far have been added to the frame object, they haven't. Instead
dlframe.setVisible(true);
dlframe.getContentPane().add(tabbedPane);
dlframe.pack();
dlframe.setSize(765, 690);
dlframe.setBackground(Color.white);
dlframe.setVisible(true);
● The tabbedPane object contains tabs with titles, string tips, and initializes separate classes that contain the
details of those pages. (For now those classes are empty.)
With the instructions about how the DiveLog object is written out within the constructor, only one method remains:
Submit
API Documentation
Note you are in the divelog directory while running this command, and
be certain to insert a space between the last \ or / before
DiveLog.java.
2. Run the Dive Log with the following:
Windows:
When you mouse over each tab in your application, you get a string tip. In addition, you get a blank page
beside the tabs. Each of these pages are filled as you work through the tutorial and develop the classes
that, for now, remain empty.
Summary
Part 1 of the Dive Log provided an overview of many Java programming concepts:
Objects and Classes
● Classes define fields, methods, and constructors.
● Instantiate some objects by calling the constructor with the keyword new.
● Define methods with an access attribute, a return type, and a list of parameters or empty
parentheses.
● Call designed methods by name within the constructor.
● Call predefined methods using the reference variable and the dot operator.
● The main method is the entry point for an application.
● Import the necessary Java API to prevent having to type fully qualified class names.
The DiveLog class served as an introductory example to Java programming as well as the main class to
the Dive Log application. It is not a comprehensive guide to the Java programming language, but instead
is an example of a Java application that teaches basic programming concepts. The concepts are repeated
in subsequent Dive Log tutorial parts as each class that makes up the tabbed panes is defined.
The Dive Log tutorial series covers more about methods, objects, and constructors in addition to creating
other Swing GUI components and functionality. Each Dive Log class introduces new ideas as well as
repeats what has been presented in earlier parts of the tutorial. In addition, each class representing a
tabbed pane gets progressively more complex in terms of features and programming concepts.
Look for Part 2: Inheritance, Images, Text, and Layouts next.
Troubleshooting Guide
This page describes the most common problems for compiling and running packaged applications, and the
solutions to these problems.
Problems Compiling
Problem 1: Compiling Only the DiveLog.java File
Because the Dive Log consists of multiple files, it is packaged using the package keyword. This tells
the compiler where to locate the class files for the application and the packages the Dive Log uses. Unlike
small one class applications, you can't just use the command javac DiveLog.java. If you do, you
get an error that looks something like this:
C:\Applications\divelog
Step 1: cd to the divelog directory.
Step 2: Compile the Dive Log application with the following command:
If you leave off the .java extension for the DiveLog.java file, you get this error:
java DiveLog
For a single class application that command normally works. For a multi-class, packaged application it
does not.
Solution to Problem 1
The rules for compiling the Dive Log apply to running it as well.
To run a packaged application you must include the classpath which points to, but does not include, the
directory where the classes live. Do not include the package name with the dot, though. If your Dive Log
files are in the following directory:
C:\Applications\divelog
Step 1: cd to the divelog directory.
Step 2: Run the command to compile the Dive Log application with the following:
package divelog;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public DiveLog()
{ //Opens DiveLog constructor
dlframe.getContentPane().add(tabbedPane);
dlframe.pack();
dlframe.setSize(765, 690);
dlframe.setBackground(Color.white);
dlframe.setVisible(true);
} // Ends class constructor
tabbedPane.addTab("Welcome",
null,
new Welcome(),
"Welcome to the Dive Log");
tabbedPane.addTab("Diver Data",
null,
new Diver(),
"Click here to enter diver data");
tabbedPane.addTab("Log Dives",
null,
new Dives(),
"Click here to enter dives");
tabbedPane.addTab("Statistics",
null,
new Statistics(),
"Click here to calculate dive statistics");
menu.add(item);
mb.add(menu);
dlframe.setJMenuBar(mb);
}// Closes buildMenu method
package divelog;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public DiveLog()
{ // Opens constructor
} //Ends class
package divelog;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public DiveLog()
{ // Opens contructor
dlframe.getContentPane().add(tabbedPane);
dlframe.pack();
dlframe.setSize(765, 690);
dlframe.setBackground(Color.white);
dlframe.setVisible(true);
tabbedPane.addTab("Welcome",
null,
new Welcome(),
"Welcome to the Dive Log");
tabbedPane.addTab("Diver Data",
null,
new Diver(),
"Click here to enter diver data");
tabbedPane.addTab("Log Dives",
null,
new Dives(),
"Click here to enter dives");
tabbedPane.addTab("Statistics",
null,
new Statistics(),
"Click here to calculate dive statistics");
menu.add(item);
mb.add(menu);
dlframe.setJMenuBar(mb);
} //Ends class
package divelog;
/**
* This class creates the content on the
* Welcome tabbed pane in the Dive Log
* application.
* @version 1.0
*/
} // Closes class
package divelog;
import java.awt.*;
import javax.swing.*;
} // Closes class
package divelog;
import java.awt.*;
import javax.swing.*;
} // Closes class
package divelog;
import javax.swing.*;
import java.awt.*;
} // Closes class
package divelog;
import java.awt.*;
import javax.swing.*;
} // Closes class
package divelog;
import javax.swing.*;
import java.awt.*;
} // Closes class