D17249GC11
Edition 1.1
August 2004
D39816
Authors
Jeff Gallus
Glenn Stokol
Technical Contributors
and Reviewers
Kenneth Cooper
Peter Driver
Christian Dugas
Craig Hollister
Chika Izumi
Pete Laseau
Glenn Maslen
Monica Motley
Gayathri Rajagopal
Publisher
Poornima G
Contents
Preface
I
Introduction
Objectives I-2
Course Overview I-3
iii
iv
vi
vii
viii
ix
xi
xii
Schedule:
Timing
60 minutes
30 minutes
90 minutes
Topic
Lecture
Practice
Total
Objectives
11-2
Lesson Aim
This lesson shows how to use Java collection objects, introducing the Java array of
primitive, array of Object references and other collection classes such as Vectors,
Hashtables, Properties, Enumerators and Iterators.
What Is an Array?
[0]
[1]
[2]
[3]
11-3
[0]
Action
[1]
Comedy
[2]
Drama
2
4
8
Arrays
Arrays are useful when you want a group of objects that you can manipulate as a whole.
For example, if you are writing a program to allow users to search for a movie, you would
probably store the list of categories in an array.
The slide shows an array of four integers and an array of three strings. The following slides
show how to create and initialize the arrays. As you will soon see, an array in Java is an
object.
Null
arrayName
0
arrayName
0
1
2
4
// Example
null
11-5
Declaring an Array
There are two ways to declare an array:
Syntax
type[] arrayname;
type arrayname[];
E xam ple
int[] powers;
int powers[];
Most Java programmers use the first style because it separates the variable type (in the
example, an array of int) from the variable name, making the code clearer to read.
When you declare an array variable, it refers to null initially, until you initialize the array
by using new.
Instructor Note
Although an array is an object, there is no array class. Instead, for every primitive type or
class, Java automatically provides an array class.
11-6
0
0
0
0
// SIZE is a constant
11-8
1
0
0
0
[0]
[1]
[2]
[3]
[0]
3 [1]
5 [2]
7 [3]
2
primes
null
arrVar
null
null
null
arrVar
Action
Comedy
Drama
11-10
11-11
ArrayIndexOutOfBoundsException occurs
when an array index is invalid:
11-12
Multidimensional Arrays
[0][0]
[0][1]
[1]
[2]
[3]
[0]
11-13
Multidimensional Arrays
Java supports multidimensional arrays; that is arrays of arrays:
int[][] tax = new int[5][4];
This declares and creates a two-dimensional matrix; the matrix contains five rows, each of
which contains four columns. Individual elements can be accessed as follows:
tax[rowIndex][colIndex] = value;
main() Revisited
11-14
11-15
Vectors
The Vector class, belonging to the java.util package, provides a resizeable
collection of objects. Remember that Java arrays are fixed in size, so a vector is useful
when you do not know how large an array will be at the time when you create the array.
For example, you may get a list of names from a server and want to store the names in a
local array. Before you fetch the data from the server, you have no idea how large the list
is.
You cannot create a vector of int, float, or any other primitive. Instead, you must use
the wrapper classes, which were discussed in the lesson titled Using Strings,
StringBuffer, Wrapper and Text-Formatting Classes, and create a vector of
Integer, Float, and so on.
The Vector class provides methods to modify and access the vector. The following slides
show some of these methods; the JDK 1.4 online documentation provides complete
information.
Instructor Note
To use vectors, you must import the Vector class:
import java.util.Vector;
Modifying a Vector
11-16
Modifying a Vector
When you add an element to a vector, the vector is automatically expanded by one element.
When you remove an element from a vector, the size of the vector decreases automatically.
When you insert an element at a specific position, all elements after that position increase
their indexes by 1.
Accessing a Vector
11-17
Vector Indexing
The index of the first element of a vector is 0.
Note that a vector always contains objects. It can contain objects of different types. When
you get an element from a vector, you must cast it to the type of object that you added to
the vector.
Example of a Vector Containing Different Objects
The Vector.addElement() method accepts an Object as its parameter type. By
applying the principle of object reference substitution (subclass object plug-compatibility
with its superclass), the parameter can be any subclass of the java.lang. The
Object class, which includes just about every object that you can create. Here is a simple
example, assuming that you have a class called Member:
Vector v = new Vector();
v.addElement(new Member());
v.addElement("pat");
v.addElement(new Integer(10));
You must be sure of the type of object that you are getting returned from methods such as
Vector elementAt() or firstElement(). You can use the instanceof
operator to determine the object type that is returned by these methods.
11-18
11-20
11-21
ArrayList
The ArrayList is a resizable-array implementation of the List interface. It implements
all optional list operations, and permits all elements, including null. In addition to
implementing the List interface, this class provides methods to manipulate the size of the
array that is used internally to store the list.
Hashtable
The java.util.Hashtable class provides a table of keys, where each key is hashed
to an associated value object. The key and value can be any Java object. Here is an
example of using the Hashtable to store String objects on information about a book.
import java.util.Hashtable;
public class HashtableDemo {
public static void main (String args[]) {
Hashtable ht = new Hashtable();
ht.put ("title", "Beyond Freedom and Diginity");
ht.put ("author", "B.F. Skinner");
ht.put ("year", "1971");
System.out.println(ht);
System.out.println("Year: " + ht.get("year"));
}
}
Oracle10g: Java Programming 11-21
Using Iterators
11-22
Summary
11-23
11-24
Schedule:
Timing
40 minutes
30 minutes
70 minutes
Topic
Lecture
Practice
Total
Objectives
12-2
Lesson Aim
This lesson shows how abstract classes and abstract methods can be defined and used in
Java. The lesson also introduces interfaces, and shows how they can be used to specify a set
of methods that interested classes can implement if they want to. You learn how to use
interfaces as an effective alternative to multiple inheritance.
Abstract
superclass
InventoryItem
Concrete
subclasses
12-3
Movie
VCR
Abstract Classes
In Java, you can define classes that are high-level abstractions of real-world objects. Using
these high-level classes gives the designer a vote in what subclasses look like and even
which methods are mandatory in the subclass.
An abstract class is simply a class that cannot be instantiated; only its nonabstract subclasses
may be instantiated. For example, an InventoryItem does not contain sufficient detail to
provide anything meaningful to the business. It must either be a movie or a VCR. An
InventoryItem does, however, serve as a collection of data and behaviors that are
common to all items that are available for rent.
Abstract Methods
Abstract methods go a step beyond standard inheritance. An abstract method is defined only
within an abstract class, and must be implemented by a subclass. The class designer can use
this technique to decide exactly what behaviors a subclass must be able to perform. The
designer of the abstract class cannot determine how the behaviors will be implemented, only
that they will be implemented.
Interfaces
An interface is the specification of a set of methods, which is similar to an abstract class. In
addition to what an abstract class offers, an interface can effectively provide multiple
inheritance. A class can implement an unlimited number of interfaces but can only extend
one superclass.
Oracle10g: Java Programming 12-3
12-4
// This is fine
// This is fine too
An abstract method:
Is an implementation placeholder
Is part of an abstract class
Must be overridden by a concrete subclass
12-5
12-7
When you declare an abstract method, you provide only the signature for the method,
which comprises its name, its argument list, and its return type. You do not provide a body
for the method. Each concrete subclass must override the method and provide its own body.
Now that the method is declared as abstract, a subclass must provide an implementation of
that method.
Abstract classes can contain methods that are not declared as abstract. Those methods can be
overridden by the subclasses but it is not mandatory.
12-8
What Is an Interface?
An interface is similar to an abstract class, except that it cannot have any concrete methods
or instance variables. It is a collection of abstract method declarations and constants; that is,
static final variables. It is like a contract that the subclass must obey.
Any class that implements an interface must implement some or all of the methods that are
specified in that interface. If it does not implement all of the methods, then the class is an
abstract class and a subclass of the abstract class must implement the remaining abstract
methods.
A class can implement many interfaces but can extend only one class. Java does not support
inheritance from multiple classes, but it does support implementing multiple interfaces. For
example:
class Movie extends InventoryItem implements Sortable, Listable {
Examples of Interfaces
Nonsteerable
12-9
Steerable
Examples of Interfaces
Interfaces describe an aspect of behavior that many different classes require. The name of an
interface is often an adjective such as Steerable, Traceable, Sortable, and so on.
This is in contrast to a class name, which is usually a noun such as Movie or Customer.
The Steerable interface may include such methods as turnRight(), turnLeft(),
returnCenter(), and so on. Any class that needs to be steerable may implement the
Steerable interface.
The classes that implement an interface may be completely unrelated. The only thing that
they may have in common is the need to be steered.
For example, the core Java packages include a number of standard interfaces such as
Runnable, Cloneable, and ActionListener. These interfaces are implemented by
all types of classes that have nothing in common except the need to be Cloneable, or to
implement an ActionListener.
Instructor Note
Interface is a way to bypass the multiple inheritance restriction that Java has.
Creating Interfaces
12-10
Creating Interfaces
You can define an interface by using the interface keyword. All methods that are
specified in an interface are implicitly public and abstract. Any variables that are
specified in an interface are implicitly public, static, and final; that is, they are
constants.
Therefore, the interface definition that is shown in the slide is equivalent to the following
definition, where the public, static, final, and abstract keywords have been
specified explicitly.
public interface Steerable {
public static final int MAXTURN = 45;
public abstract void turnLeft(int deg);
public abstract void turnRight(int deg);
}
Implementing Interfaces
12-12
Implementing Interfaces
The slide shows an example of a Yacht class, that implements the Steerable interface.
Yacht must implement some or all of the methods in any interface that it implements; in
this case, Yacht may implement turnLeft() and turnRight().
A class can implement more than one interface by specifying a list of interfaces separated by
commas. Consider the following example:
public class Yacht
extends Boat
implements Steerable, Taxable {
Here, the Yacht class implements two interfaces: Steerable and Taxable. This means
that the Yacht class must implement all the methods that are declared in both Steerable
and Taxable.
12-13
Sort
A sort is a classic example of the use of an interface. Many completely unrelated classes
must use a sort. A sort is a well-known and well-defined process that does not need to be
written repeatedly.
A sort routine must provide the ability to sort any object in the way that fits that particular
object. The traditional programming approach dictates several subroutines and an evergrowing decision tree to manage each new object type. By using good OO programming
technique and interfaces, you can eliminate all of the maintenance difficulties that are
associated with the traditional approach.
The Sortable interface specifies the methods that are required to make the sort work on
each type of object that needs to be sorted. Each class implements the interface based on its
specific sorting needs. Only the class needs to know its object comparison, or sorting rules.
Implementing the sort in the OO way provides a model that supports very good code reuse.
The sort code is completely isolated from the objects that implement the sort.
Instructor Note
Use the sort examples to demonstrate. Open the Demo.jws. There are two projects: Sort
and ExtendedSort. Start with the Sort project and launch the SortApplication.java
for a simple demonstration. Use the ExtendedSort project for a more complex
demonstration. Launch the ExtendedSortApplication.java file to demonstrate a
double sort application.
Oracle10g: Java Programming 12-13
12-14
public abstract
class Sort
public class
MyApplication
MyApplication represents any application that must sort a list of movies. It can be
a form displaying a sortable list of movies.
Oracle10g: Java Programming 12-14
sortObjects()
returns the
sorted list.
MyApplication passes
an array of movies to
Sort.sortObjects().
Sort
The movie
returns the
result of the
comparison.
sortObjects()
asks a movie to
2
compare itself with
another movie.
3
Movie
12-15
//
a value > 0 if this object > obj2
int compare(Object obj2);
}
12-16
Value
Meaning
Positive integer
Negative integer
Zero
Holds sortObjects():
public abstract class Sort {
public static void sortObjects(Sortable[] items) {
// Step through the array comparing and swapping;
// do this length-1 times
for (int i = 1; i < items.length; i++) {
for (int j = 0; j < items.length - 1; j++) {
if (items[j].compare(items[j+1]) > 0) {
Sortable tempitem = items[j+1];
items[j+1] = items[j];
items[j] = tempitem; } } } } }
12-17
Implements Sortable:
public class Movie extends InventoryItem
implements Sortable {
String title;
public int compare(Object movie2) {
String title1 = this.title;
String title2 = ((Movie)movie2).getTitle();
return(title1.compareTo(title2));
}
}
12-18
12-19
12-20
Summary
12-21
12-22
Schedule:
Timing
45 minutes
25 minutes
70 minutes
Topic
Lecture
Practice
Total
Objectives
13-2
Lesson Aim
Many Java methods in the Java Development Kit (JDK) class library throw an exception
when they encounter a serious problem that they do not know how to handle. This lesson
explains how exceptions work in Java, and shows you how to handle such exceptions in
your applications.
What Is an Exception?
13-3
What Is an Exception?
An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions. For example, trying to access an element outside the bounds of
an array, trying to divide a number by zero, and trying to access a URL with an invalid
protocol are all exceptions.
What Is an Error?
An error in Java is an unrecoverable abnormal condition. For example, an error condition
exists if there is some internal error in Java Virtual Machine (JVM) or if JVM runs out of
memory.
What Is the Difference?
Your code can handle an exception and move on; if an error occurs, then your program must
exit.
Instructor Note
There are some instances when errors can be caught and handled. For example, under some
circumstances your code can catch the error java.lang.ThreadDeath. See the
javadoc for details.
Oracle10g: Java Programming 13-3
Exception object
Yes
13-4
Handler
for this
exception?
No
13-5
The traditional way of checking for the potential errors in this function is to test each
possible error and set an error code. The table on the next page compares the traditional
method with Javas exception handling; the original three statements are in bold.
readFirstLine {
int errcode = 0;
open the file;
if (openError) {
errcode = OPEN_ERR;
}
else {
read the first line;
if (readError) {
errcode = READ_ERR;
}
close the file;
if (closeError) {
errcode = errcode
and CLOSE_ERR;
}
}
return errcode;
}
readFirstLine {
try {
open the file;
read the first line;
close the file;
}
catch (openError) {
handle error;
}
catch (readError) {
handle error;
}
catch (closeError) {
handle error;
}
}
Java separates the details of handling unexpected errors from the main work of the program,
making the code clearer to read (which, in turn, makes it less prone to bugs).
Instructor Note
The term try means that the code is trying something that may throw an exception; catch
means that the code is handling the exception.
Java exceptions
Error
code
Error
code
Error
code
method3
method4
13-7
Method1
//handle ex
method2
method3
Exception
ex
method4
method4 throws an
exception; eventually
method1 catches it.
Java exceptions
method1
//handle error
method1
//handle ex
method2
method2
method3
method3
method4
Error
code
13-8
Exception
ex
method4
The exception must be
caught and handled
somewhere.
Error
Unrecoverable
errors
Exception
Checked
exceptions
RuntimeException
Unchecked (run-time)
exceptions
13-9
13-11
Handling Exceptions
If you call a method that may throw a checked exception, then you have three choices:
Catch the exception and handle it.
Allow the exception to pass through your method; another handler somewhere else
must handle it.
Catch the exception and throw a different exception; the new exception must be
handled by another handler somewhere else.
Run-Time Exceptions
Your code does not need to handle run-time exceptions; these are handled by JVM. JVM
handles run-time exceptions by terminating your program; if you do not want a run-time
exception to have this effect, then you must handle it.
try {
Handle each
exception in a catch
block.
Perform any final
processing in a
finally block.
13-12
int qty;
String s = getQtyFromForm();
try {
// Might throw NumberFormatException
qty = Integer.parseInt(s);
}
catch ( NumberFormatException e ) {
// Handle the exception
}
// If no exceptions were thrown, we end up here
13-13
13-14
You will use a single catch block if you wanted your code to behave in the same way for
either exception.
Order of catch Statements
Note that you get a compiler error if you specify a catch handler for a superclass first,
followed by a catch handler for a subclass. This is because the superclass catch handler
hides the subclass catch handler, which will therefore never see any exceptions. For
example, reversing the two catch blocks in the example causes a compiler error.
Oracle10g: Java Programming 13-14
13-15
You cannot, however, have a finally block on its own, without a try block preceding it.
Oracle10g: Java Programming 13-15
13-16
block
makeConnection
URL: <url>
block
13-17
try
catch (Exception e) {}
catch (IndexOutOfBoundsException e) {}
Instructor Note
1. Caught Exception
No more exceptions
Goodbye
2. The code will not compile because the second catch block can never be reached.
The relevant subclassing information is:
public class RuntimeException extends Exception
public class IndexOutOfBoundsException extends
RuntimeException
public class IllegalArgumentException extends
RuntimeException
Oracle10g: Java Programming 13-17
13-18
Throwing Exceptions
13-19
Throwing Exceptions
You can throw exceptions in your own code to indicate some abnormal situation. The
exceptions that you throw can be standard system exceptions, or you can create your own.
If you do decide to throw exceptions, remember that what you are really doing is creating an
object and passing it to a higher-level method. Therefore, you must create this exception
object by using the new operator, as shown in the slide.
A method can throw multiple exceptions, in which case the exception names are separated
by commas.
Four types of exception are System, Application, Run-time and Custom. The
java.lang.IndexOutOfBoundsException is a run-time Exception.
Creating Exceptions
13-20
Creating Exceptions
You can create your own exceptions by extending the Exception class. You must not
extend the RuntimeException class because this is for common exceptions that need
not be checked.
The example creates an exception called UserFileException with one constructor that
just calls the constructor of the superclass.
You can create multiple exceptions for different circumstances in your code. For example, if
your code accesses different files, then you can throw a different exception for each file.
This approach is useful for several reasons:
You can handle each exception differently.
If your exception handlers print out the exception, then this gives you or your users
more information about where the exception occurred.
You can customize your exception. For example, you can add a
UserFileException constructor that sets an attribute for the line number of the
file and a method that prints out the line number.
13-21
Summary
13-22
13-23
Schedule:
Timing
55 minutes
35 minutes
90 minutes
Topic
Lecture
Practice
Total
Objectives
14-2
Lesson Aim
This lesson shows you how to provide a Java applet or application with a graphical user
interface based on Swing components, such as buttons and text fields. Participants learn how
to embed Swing components into Swing containers and how to use layout managers to
provide an interface that is usable across platforms.
14-3
Swing (javax.swing):
A more powerful graphical user interface library
Built on top of the AWT class hierarchy
14-4
Swing Features
A set of visual components that have been available
since JDK 1.1, but part of core JDK since version 1.2:
Lightweight components compared to AWT
Pluggable look and feel API
InventoryItem
Many more components than AWT
14-6
JButton
JSlider
JComboBox
JTextField
JTree
JProgressBar
Heavyweight components
Strong dependency on
native peer code
Each rendered in its own
opaque window
Early AWT components
were mostly
heavyweight
Include some Swing
top-level components
(JFrame, JApplet,
JDialog)
14-8
Lightweight components
No dependence on native
peer code
Can have transparent
backgrounds
Most Swing components
are lightweight
When displayed, they can
appear nonrectangular
Must be displayed in
heavyweight container
14-9
Top-level containers
Frame
Frame
Dialog
Applet
Intermediate containers
Panel
Scroll Pane
Atomic components
Label
Text items
Buttons
14-10
Panel
Atomic
components
Top-Level Containers
14-12
Top-Level Containers
Each Swing application has at least one top-level container or frame. The top-level container
can be an instance of JFrame, JDialog, or JApplet. It is easy to customize the toplevel content pane to add a border or set the layout manager. However, using the top-level
content pane methods is tricky. The methods of the top-level containers return a
Container object, not a JComponent object. This means that you must typecast the
return value of the methods in order to use them.
An easier way to achieve the same results is to create your own content pane, typically by
using a JPanel object. You then call the JFrame setContentPane() method to set
the top-level content pane to be your customized JPanel. You now have complete control
of the content pane without the restrictions of the top-level or root container.
Intermediate Containers
14-14
Intermediate Containers
The next level of containers in Swing is designed for the sole purpose of containing other
components. These containers may hold any other Swing component including other
containers. By nesting intermediate containers within other containers, you can control the
layout of your application. This technique is described later in this lesson.
The intermediate containers are the following:
Panels: These are the most frequently used intermediate containers. They are
implemented with the JPanel class. They are generally used to group components
for logical presentation to the user. A JPanel can use any layout manager; by default
it uses the FlowLayout, and you can set its border to any border.
Scroll pane: These provide scroll bars around any large component or one that may
grow. They are implemented with JScrollPane.
Split pane: This container is used to present two components in a fixed amount of
space while letting the user adjust the space that is devoted to each item. Split Pane is
implemented with JSplitPane.
Tabbed pane: This container possesses multiple components but the user can see only
one at a time. The user can switch between the components by clicking on the visible
tabs. Tabs are implemented with JTabbedPane.
Toolbar: In addition to holding multiple components, instances of JToolBar can be
repositioned by the user.
Internal frame: Top-level containers can support internal windows or frames, which
are implemented by JInternalFrame and best used with a JDesktopPane.
Oracle10g: Java Programming 14-14
Atomic Components
14-15
Buttons
Check boxes
Combo boxes
Text
Lists
Labels
Atomic Components
Atomic components exist solely to present or accept information. They do not serve as
containers for other components. Atomic components inherit from JComponent and thus
support standard component features such as borders and tool tips.
14-16
Border Layout
14-18
Border Layout
Border layout provides five areas for components: north, south, east, west, and center. If the
user enlarges the window, then the center area expands to use as much of the space as
possible. The other areas expand only as much as necessary to fill the available space. For
example, if the user makes the frame wider, then the center will expand horizontally, but the
east and west areas will not; however, the south area will expand to fill the new window
size.
Each area will display only one component. To overcome this restriction and make Border a
useful layout manager, add containers to the areas instead of atomic components. Most
panels that use Border use only one or two of the areas, such as center and south. South may
be used for a toolbar or navigation, whereas center may contain a panel that will hold all the
atomic data components. This technique is useful in creating a resizable frame.
GridBag Layout
14-19
Is based on a grid
Allows components to span multiple rows and
columns
Allows rows and columns to differ in size
Uses the components preferred size to control
cell size
GridBag Layout
GridBag layout is the most flexible and the most complex of the layout managers. The
flexibility comes from its ability to allow components to span multiple rows and columns. In
addition to spanning multiple columns and rows, the components can provide hints or
suggestions about how the component would like to appear. For instance, a component can
specify how much space to automatically set around the component, both inside and outside
of the components cell. You can also specify minimum, maximum, and preferred size for
each component.
Components can span multiple cells in both directions, row and column. The row and
column sizes are determined by the size of the components that occupy the row or column.
GridBag Constraints
External insets
Component
padding
Cell position
Cell span
Expansion
weighting
Anchoring
Fill rules
14-20
GridBag Constraints
Each component in a GridBagLayout container has properties that you can set to control
the layout behavior for the component. You edit the constraints by selecting the component
and clicking constraints in the Properties Inspector window. Alternatively, you can rightclick the component and select constraints from the context menu.
Layout Constraints
Cell position: The X and Y properties specify the grid cell for the upper left corner of
the component. The values are integers and represent the cell number in a row and
column.
Cell Span: These properties specify how many columns (Width) and rows (Height) the
component occupies.
External Insets: These values specify the amount of space between the component
and the edge of its display area. You can specify a value for the top, bottom, left, and
right.
Component padding: These values specify the amount of space around a component
within a cell. The width of the component is calculated as the minimum width plus the
width property. The height is calculated as the minimum height plus the height
property.
14-22
Set properties
myFrame.setLayout(layoutMgr);
Add items
myFrame.add(new JButton(), BorderLayout.NORTH);
myFrame.add(new JTextField(), BorderLayout.SOUTH);
myFrame.add(new JPanel(), BorderLayout.CENTER);
Border
null
VerticalFlow
GridBag
Grid
14-24
14-25
Note
By default the JFrame default operation on a close event is to hide the window. The
call to setDefaultCloseOperation(EXIT_ON_CLOSE) changes the default
operation that is performed by the JVM when the window is closed. The
EXIT_ON_CLOSE constant is defined in javax.swing.WindowConstants,
which is an interface implemented by JFrame.
The getContentPane() method is used to access the frames default container and
change the background color to blue.
The setLocation() determines the top left x and y coordinates (in pixels) of the
window relative to the top left corner of the screen.
The setSize() method sets the width and height of the window (in pixels).
The setLocation() and setSize() can be done in one step by calling
setBounds(x, y, width, height).
The example shows how you can set properties of the frame in the constructor, or by
using a reference to the frame (as shown in the main() method).
14-27
jPanel1.setBorder(BorderFactory.createBevelBorder(
BevelBorder.LOWERED,Color.lightGray,Color.darkGray));
Border etchedBorder =
BorderFactory.createEtchedBorder();//pre-create border
jPanel2.setBorder(etchedBorder);
// use border`
14-29
14-30
The desktop pane provides methods to obtain an array of internal frame objects that have
been added to its container; for example:
getAllFrames() returns an array of JInternalFrame objects.
getSelecedFrame() returns the currently selected JInternalFrame.
Note
The text in boldface highlights some of the important parts of the code, such as:
Creation of the desktop pane (line 14), and internal frame objects (from line 16 through
18)
Replacing MdiFrame default content pane with the desktop pane (line 21)
Adding the internal frames into the desktop frame (lines 24 and 25)
Making the second internal frame the front/top internal frame (line 26)
Making the internal frames visible (line 34)
Oracle10g: Java Programming 14-31
14-32
Adding Components
with Oracle JDeveloper 10g
14-33
Creating a Frame
Frame
14-34
Creating a Frame
To create a new JFrame, select File > New from the JDeveloper menu. Expand the Client
Tier, then select the SWING/AWT node. Look for the Frame item in the Items list. In the
Frame Builder Wizard, change the name of the class and the frame title to something
meaningful. Select javax.swing.JFrame as the base class. You can ask the wizard to
create a menu bar, status bar, toolbar, and about box. These are all optional attributes.
You can use the wizard to specify the preferred superclass for the new frame. JDeveloper
will generate a class with the required import statements and the code that is necessary to
create a usable frame. Now you can use the JDeveloper UI Editor to construct the
application UI structure visually.
Adding Components
Use the Component Palette to add
Swing items to the Frame
14-35
Adding Components
The JFrame that is created by the Frame Builder Wizard includes the frame and an
intermediate JPanel container. The wizard does not set the layout manager for the
generated JPanel. It uses the default layout manager for its type of container
(FlowLayout).
Because it is a default layout manager, JDeveloper cannot provide the ability to alter the
properties of the layout manager. It is best to change the layout manager so that you can
manipulate the layout properties.
After setting the layout manager, you can then add components by selecting them from the
Swing component toolbar and dragging an area onto the JPanel in the Design window.
Alternatively, you can click the component and then click JPanel in the Component pane of
the structure window. If you choose the latter, then JDeveloper uses default sizes for
components. In either case, the layout manager affects the final location of the component.
14-37
Note: If you want to change the look and feel dynamically, then you can call the
SwingUtilities.updateComponentTreeUI(getContent Pane())method.
This method will make the existing components reflect the new look and feel.
Summary
14-39
14-40
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout
Goal
The goal of this practice is to use JDeveloper to create the main application frame as an MDI
window, and the internal order frames that will be contained within the main window. These
frames will serve as a way to explore Swing classes and ways of building GUI applications.
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful and
you would like to move on to this practice, then change to the les13 directory, load up the
OrderEntryWorkspaceLes13 workspace, and continue with this practice.
Your Assignment
Create the main window as an extension of the JFrame class. This class will contain a
JDesktopPane object to manage the internal frame layout. You will also create a class
based on the JInternalFrame class in which the customer and order details will be
entered via atomic Swing components. The components layout will be managed through the
use of panels and associated layout managers. You use the JDeveloper Frame Wizard to
create a basic menu for the application, and a status bar in the main application window.
Create the Main Application Window
1. In OrderEntryProject, create a new subclass of the JFrame class.
a. Right-click the project name in the navigator, and select New from the context
menu. Select the Frame item from Client tier > Swing/AWT category, and click
the OK button.
b. In the Create Frame dialog box, enter the class name OrderEntryMDIFrame,
and extend javax.swing.JFrame. In the Optional Attributes section, set the
Title field to: Order Entry Application, and select only the Menu Bar
and Status Bar check boxes. Then click the OK button.
c. Examine the code for the new class that is generated by JDeveloper by selecting
the Source tab. You will notice that JDeveloper creates a jbInit() method
that is called from the default no-arg constructor. The jbInit() method should
contain all code to initialize the user interface structure. You should modify the
code if required, to match with the one displayed.
d. In the Editor window, select the Design tab, and examine the visual container
hierarchy and presentation of the frame. The container hierarchy is visible in the
JDeveloper Structure pane (located under the Navigator pane).
e. Return to the Code Editor for the class by selecting the Source tab
and make the following changes:
Replace the JPanel panelCenter variable declaration, with:
JDesktopPane desktopPane = new JDesktopPane();
Note: Remember to import javax.swing.JDesktopPane.
In the jbInit() method, replace panelCenter references with
desktopPane.
f. Compile and save the OrderEntryMDIFrame class.
g. Modify OrderEntry.java by renaming the main() method to
test1().
Create a new public static void main(String[] args)
method, which creates an instance of the OrderEntryMDIFrame and makes
it visible.
Oracle10g: Java Programming 14-41
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
h. Compile, save, and run the OrderEntry application.
Create the JInternalFrame Class for Order Data
This frame will contain the bulk of the UI code for data entry and user interaction for an
order, and assigning a customer and adding items to the order.
2. Right-click the OrderEntryProject and select New from the context menu.
a. Navigate to the Client Tier > Swing/AWT node and select the Frame item. In the
New FrameWizard, enter the class name OrderEntryFrame, and extend the
javax.swing.JInternalFrame. Set the title to the text Order.Then
click the OK button.
Note: The JInternalFrame class can be selected by clicking the Browse
button.
b. The OrderEntryFrame that is generated does not have the desired layout
manager or content pane. To set the layout manager, and add a panel to the
content pane, open OrderEntryFrame with the UI Editor.
Note: When the UI Editor is activated (UI Editor can be invoked by clicking the
Design tab), the Property Inspector window is also displayed, showing the
properties of the object that is selected in the UI Editor.
c. Select the internal frame object by clicking the frame title bar in the UI Editor or
the node labeled this in the structure window. (You may have to expand the UI
node to view objects in the containment hierarchy.) In the Inspector pane, locate
the layout property and select BorderLayout from the pop-up list options.
d. Which lines of code has JDeveloper added or changed in your class? When
creating a Swing UI by using the JDeveloper UI Editor, it is wise to view
changes that are made to the source code as an aid to learning what you would
need to write yourself if you are building the UI manually. Remove the
private declaration from the BorderLayout.
e. JDeveloper provides a Component Palette in the toolbar (ask the instructor, if
needed). In the palette, choose Swing Containers from the pop-up list.
Click the JPanel icon, and then click the center of the frame in the UI Editor (or
click the node labeled this in the UI Structure pane) to add a new panel to the
center region of the border layout.
If the JPanel icon is not visible, they have to expand the Component Palette
window by increasing the height.
Note: Confirm that the panel is in the center by selecting the JPanel object
added and checking that its constraints property (in the Inspector) has the
value Center. If not, then set it to Center.
3. The panel was added to the frames content pane, and will be used to lay out the rest of
the application UI objects. The panel will be divided into two areas: a top (for order
and customer data), and a bottom (for order item data). Divide the panel into two by
using a GridLayout for the layout, with one column and two rows:
a. Select jPanel1, and set its layout manager property to GridLayout.
b. Expand jPanel1 in the UI Structure pane, select the gridLayout1 object,
set the columns property to 1 and press the Enter key, set the rows property
to 2, and then press Enter.
Oracle10g: Java Programming 14-42
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
Using the following picture as a visual guide to the desired results for the layout of
these containers, add another panel to the top, and a scroll pane to the bottom
of the content panel.
c. Add a second panel to the top half (or first row) of the first panel, by clicking the
JPanel icon in the Swing Components palette, and then clicking the jPanel1
object in the UI Editor, or in the Structure pane.
Note: Confirm that the new panel is called jPanel2, and more importantly,
that it is nested inside jPanel1 in the hierarchy.
d. Add a raised-bevel border to the new panel, called jPanel2, by selecting its
border property in the Inspector, and select Swing Border from the pop-up
list. In the Border dialog box, choose BevelBorder and select the RAISED
option button, then click the OK button.
Note: jPanel2 should visually occupy the top half of the jPanel1.
e. Add a scroll pane object to the bottom half (second row) of the jPanel1, by
clicking the JScrollPane icon in the Swing Components palette, and click the
bottom area of the jPanel1. (Alternatively, click the jPanel1 object in the
Structure pane to add the JScrollPane.)
f. Use the Structure pane to check whether you have the following containment
hierarchy:
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
Modify OrderEntryMDIFrame Class to Contain an Internal OrderEntryFrame
4. To view the visual results of your internal frame at run time modify the constructor in
OrderEntryMDIFrame to create an instance of OrderEntryFrame, and make it
visible.
a. Edit OrderEntryMDIFrame.java, and at the end of the constructor add the
following lines of code:
OrderEntryFrame iFrame = new OrderEntryFrame();
iFrame.setVisible(true);
desktopPane.add(iFrame);
Note: The bounds (size and location) of the internal frame must now
be set, otherwise it will not become visible. In addition, you must also alter the
dimensions of OrderEntryMDIFrame to be larger than the initial size of the
internal frame OrderEntryFrame.
b. In the jbInit() method of the OrderEntryMDIFrame class, locate the
following statement:
this.setSize(new Dimension(400,300));
Then modify the dimension arguments to be 700,500.
c. In the OrderEntryFrame, add the following line into the jbInit()
method:
this.setBounds(0, 0, 400, 300);
d. Compile and save OrderEntryMDIFrame and OrderEntryFrame.
e. Run the OrderEntry class to view the results.
5. You will notice that the internal frame cannot be maximized, iconified (minimized),
or closed. Make changes to OrderEntryFrame to enable these features.
a. In the jbInit() method, add the following lines of code to enable the internal
frame to maximized, iconified, and closed.
this.setMaximizable(true);
this.setIconifiable(true);
this.setClosable(true);
b. Compile and save the changes to OrderEntryFrame.java.
c. Run the OrderEntry application, and observe the changes.
Add UI Components to OrderEntryFrame
6. Before adding UI components to jPanel2 in OrderEntryFrame, set its layout to
null.
Note: You could also use the JDeveloper XYLayout.
In either case, JDeveloper will use absolute positioning and sizing for components that
are added to the panel. It is easier to use absolute positioning when building the initial
UI layout. You will change the layout again in a subsequent lesson.
Use the following image as a guide to the desired results:
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
a. In the Design mode, select the Swing option in the Component Palette pop-up
list. Then add a Jlabel to jPanel2 and set its text property to Order Id.
Resize the label to see the label value, if needed. What lines of code have been
added to your class?
Hint: You should find at least five lines of code (some of them in the
jbInit() method). Try to identify the three that make the object visible in the
panel.
Note: The setBounds value can be modified if required in the source to make
the label clearly visible.
b. From Swing icons, select and add a JTextField component into jPanel2, to
the right of the label, then delete the default value in the text property of the
text field (remember to press the Enter key after deleting the text value).
Note: setBounds values can be changed if required.
c. Compile and save OrderEntryFrame, and run OrderEntry to view the
results.
Schedule:
Timing
50 minutes
70 minutes
120 minutes
Topic
Lecture
Practice (total for both mid lesson and end of lesson)
Total
Objectives
15-2
Lesson Aim
This lesson shows how to provide a Java applet (or application) with a graphical user
interface based on components, such as buttons and text fields. You learn how to use
standard Java Swing components as well as the more sophisticated controls provided by
JDeveloper. You also learn how to provide event handler methods, to deal with events such
as button clicks and text changes.
Instructor Note
Further reading: The Java tutorial has a very good section on the Swing components:
http://java.sun.com/docs/books/tutorial/
Swing Components
Text controls
JTextField
JPasswordField
JTextArea
JEditorPane
JTextPane
Graphic controls
JTree
JTable
JToggleButton
15-3
Swing Components
Swing text components display text and can optionally allow the user to edit text. There are
five different text components that support the varying complexities and requirements. They
are:
JTextField: Can display and edit only one line of text at a time
JTextArea: Can display and edit multiple lines of text (This component is used to
allow the user to enter text of any length. It can display text in any font.)
JEditorPane: Allows the use of more sophisticated text styles including multiple
fonts and embedded images (JEditorPane can read and write plain text, HTML,
and RTF text.)
15-5
JEditorPane: A styled text area that can display text in different formats including
RTF and HTML
JSlider: A component that the user can use to select a value by sliding a knob
JTextPane: A styled text area that you can use to define your own text formats
JToggleButton: Toggle buttons are similar to JCheckBox. When they are pushed
(set to true), they remain true until they are programmatically set to false.
Code Editor
System Navigator
Context menu
15-7
UI Editor
You can invoke the Context menu by right-clicking the class in the Application Navigator
and selecting Open to view the class. The class will be displayed in the Code Editor. On the
bottom of the pane, there will be three tabs: Source, Class, and Design. Clicking the Design
tab will display the class using the UI Editor.
15-8
15-10
Generated Code
Whenever you modify a UI in JDeveloper, it automatically updates the source code for that
class in order to achieve the design that you have just specified. In fact, the source code is all
that matters; the Designer tool is just an easy way to generate the source code that is
required to achieve a certain visual appearance.
Instance Variables and Their Names
Each time you add a component to the UI, JDeveloper adds a corresponding instance
variable to your class. By default, the instance variable is assigned a default name based on
the class name and number, for example, jButton1 (as shown on the slide). To give the
variable a more meaningful name, change its name property in the Inspector, to replace all
usages of the name in the class. If you change the variable name manually in the source
code, then you must remember to replace all occurrences of the variable in the class.
The code lines that are generated in the jbInit() method to initialize the component and
add it to its container will vary based on the type of layout manager that is used by the
container. On the slide, the second parameter to the add() method on the content pane uses
the XYConstraints object because the container layout manager is XYLayout.
where X and Y are the coordinates of the component relative to the upper left-hand corner of its
container.
Creating a Menu
15-12
Context menu
when
right-clicking a
menu item
Click
menu bar
object in
Structure pane
to display
menu bar
15-13
15-14
15-15
Use the JDeveloper UI Editor to modify the menu to include the Order menu and its
menu items, as shown above.
Note: File > Exit already exists.
a. Edit the OrderEntryMDIFrame by using the UI Editor, expand the Menu
item in the Structure pane, and click the menuBar entry to display the initial
menu structure in the UI Editor window.
Oracle10g: Java Programming 15-17
Hint: You may want to add all menu labels first, and then set the name
properties.
b. Save and compile the class. Then run OrderEntry.java to view the menu.
Add Components to OrderEntryFrame to Form its Visual Structure
3. To add UI components, open OrderEntryFrame.java by right-clicking its name
in the Navigator; select the Design tab to invoke the UI Editor.
a. In the top panel, add Jlabel and JTextField components for the Customer
details. (These components can be found in the Swing pulldown.) Use the sample
window on the previous pages as a guide for the layout. Create label and text
field items by using the following table:
JLabel text property
JTextField name property
Customer Id
custIdTxt
Name
custNameTxt
Address
custAddressTxt
Phone
custPhoneTxt
Hint: Aligning UI components works best with XYLayout manager, in which
alignment is relative to the first component clicked. Select additional
components, while holding [Shift] or [Control]. Right-click a selected component
and choose an Align option from the context menu. (Null layout hints on next
page).
Oracle10g: Java Programming 15-18
How it works:
Event originates from source and generates an
event object.
An event listener hears a specific event.
An event handler determines what to do.
Setting it up:
1. Create an event source object.
2. Create an event listener object implementing an
interface with methods to handle the event object.
3. Write an event-specific method to handle the event.
4. Register the listener object with the event source
for the specified event.
15-20
15-21
Source
OK
15-22
The event handling model is enforced because the classes follow coding rules as follows:
The event object class is called XXXEvent.
The listener implements an interface called XXXListener interface.
The event source provides an addXXXListener() method, which accepts an object
argument that implements the appropriate XXXListener interface.
Handler method
15-24
Source
OK
Source
15-25
Instructor Note
Writing event handling code can be confusing. If the students have problems understanding
the implementation details, you could tell them that JDeveloper simplifies the
implementation of event handling. They must understand the concepts and have an idea of
the different classes; JDeveloper handles the rest. Handling errors with JDeveloper is
covered later in this lesson.
Controller
modify
modify
View
View
Notify update
Model
Terms explained:
Model represents the data or information.
View provides a visual representation of the data.
Controller handles events modifying the
view/model.
15-27
Model interface
JTextField, JPasswordField,
JTextArea, JTextPane,
JEditorPane
JButton, JCheckBox,
JCheckBoxMenuItem, JMenu,
JMenuItem, JRadioButton,
JRadioButtonMenuItem,
JToggleButton
JComboBox
JProgessBar, JScrollBar,
JSlider
JList
Document (found in
javax.swing.text package).
ButtonModel
DefaultButtonModel.
ComboBoxModel
BoundedRangeModel
DefaultComboBoxModel.
DefaultBoundedRangeModel
ListModel, ListSelectionModel
JTable
TableModel (found in
javax.swing.table package)
ListSelectionModel
TreeModel TreeSelectionModel
(both interfaces found in
javax.swing.table package)
DefaultListModel,
DefaultListSelectionModel
DefaultTableModel,
DefaultListSelectionModel
JTree
DefaultTreeModel,
DefaultTreeSelectionModel
Swing components, by default, implicitly create and store data in a default model that suits
their requirement. You can use all components to explicitly create and use an appropriate
model, usually based on those shown in the table above.
15-30
void setModel(ListModel)
Sets model representing the data and clears
selection. Uses DefaultListModel class for the
model.
Object getSelectedValue()
Returns the selected object, or null if nothing is
selected
int getSelectedIndex()
Returns the index of the selected item, or 1 if
nothing is selected
15-31
List Components
The JList and JComboBox are Swing components that handle lists of data. The slide
discusses some of the methods that are provided by the JList class.
Vector vector = new Vector();
Jlist list = new JList(vector);
For example, if you create a JList object with the constructor accepting a vector, then the
vector elements are copied to an internally created DefaultListModel object. Thus, if
you add elements to the vector, with the addElement() method, then the new elements
will not be visible through the Jlist, unless you call the JList.setListData()
method passing the updated vector object as an argument. This is inefficient as the
elements are copied from the vector again and a new DefaultListModel object
is created internally.
It is better to create the DefaultListModel object first, and use it like you would a
Vector, and create the JList with the appropriate constructor, for example:
DefaultListModel model = new DefaultListMode();
Jlist list = new JList(model);
Event handler
methods
15-32
15-33
findButton.addActionListener(
Find
new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
findButton_actionPerformed(e);
}
});
void findButton_actionPerformed(ActionEvent e) {
// Your code to handle the ActionEvent
}
15-34
15-35
Summary
15-36
15-37
b. Add the following method to create a new order object and display its
contents in the appropriate components in the frame:
private void initOrder() {
order = new Order();
orderIdTxt.setText(
Integer.toString(order.getId()));
orderDateLbl.setText(
Util.toDateString(order.getOrderDate()));
orderTotalLbl.setText(
Util.toMoney(order.getOrderTotal()));
}
static
static
static
static
int x
int y
final
final
= 0;
= 0;
int OFFSET = 20;
int MAX_OFFSET = 200;
Note: This method will be called from the Order > New menu event
handler.
g. Compile and save the OrderEntryFrame class.
2. Edit OrderEntryMDIFrame.java to create the event handler code for the
new order menu option.
a. Open OrderEntryMDIFrame.java in the UI Editor, and expand the
menu either in the visual editor, or the Structure pane, and then select the
New menu item under the Order menu.
b. Click the Events tab of the Inspector window (second icon from the left), click in
the text area to the right of the first event called actionPerformed. The text
area will show a button with three dots (ellipses). Click this button to
display the actionPerformed event generation dialog. Take note of the
name of the action method and accept the defaults, and then click the OK
button.
Note: JDeveloper will generate the event listener code as an anonymous
inner class (in the jbInit() method), that calls the method that is
named in the event dialog window. JDeveloper will put the cursor in the
Code Editor inside the empty body of the event handler method created.
Oracle10g: Java Programming 15-39
Also add the following line, after adding the frame to the desktop pane:
iFrame.setActive(true);
b. Compile and save the code. Run the OrderEntry application to test the
code.
Add products to the order (product IDs start at 2000). Did you see the
products
visually added to the list? If not, explain why. Did the order total get
updated?
5. Modify the Order class to support the UI by replacing the Vector type for
items to be a javax.swing.DefaultListModel. Provide a method in the
Order class to return the reference to the model.
a. Edit the Order.java class and replace the items declaration as shown:
// private Vector items = null; // replace with ...
private DefaultListModel items = null;
c. Add a new method with the signature shown to return the items
reference
to the caller:
public DefaultListModel getModel() { }
Note: This method will be used as the model for the JList, causing it to
dynamically display OrderItem objects as products are added to the
order.
Modify the OrderEntryFrame and add the call to use the method in the
button orderItemList.setModel(order.getModel());
d. Compile and save the changes to the Order class.
e. Save and compile the OrderEntryFrame, and run the OrderEntry
application to test if items are dynamically displayed in the list as they are
added.
Oracle10g: Java Programming 15-42
Schedule:
Timing
50 minutes
30 minutes
80 minutes
Topic
Lecture
Practice
Total
Objectives
16-2
Lesson Aim
This lesson introduces you to using Java to access an Oracle database. This lesson
introduces you to the basic use of JDBC to query a database from a Java class. It presents
the different steps required to perform SQL statements.
Client
Web
server
Application
server
Presentation
Business
logic
Data
Oracle
database
Oracle
Application Server 10g
J2EE Certified Environment
JDBC
16-3
Client application
or applet
16-4
JDBC
Relational DB
What Is JDBC?
16-5
16-6
[Oracle Home]/jdbc/lib/classes12.jar
(and optionally [Oracle Home]/jdbc/lib/nls_charset12.jar) for full
NLS character support)
or:
[Oracle Home]/jdbc/lib/classes111.jar
(and optionally [Oracle Home]/jdbc/lib/nls_charset11.jar) for full
NLS character support)
Ensure that there is only one classes*.zip file version and one nls_charset*.zip
file version in your CLASSPATH.
2. Obtain a connection.
16-8
6. Close connections.
16-9
Using the Class.forName() method calls the static initializer of the driver class. The
driver class does not need to be present at compile time. However, this method is valid only
for JDK-compliant Java Virtual Machines.
You can register the driver at execution time. In this case, the registering statements that
may exist in your Java class are ignored.
Example of using the Djdbc option in the command line:
C:>java -Djdbc.drivers=oracle.jdbc.OracleDriver MyClass
Instructor Note
oracle.jdbc.OracleDriver class provides new interfaces and classes that can be
used in place of the previous oracle.jdbc.driver.OracleDriver classes.
16-10
Thin client
OCI
Server-based
Database
commands
Database
Applet
JDBC
Thin driver
Client
16-11
Oracle
Server
ocixxx.dll
Client
16-12
Oracle
Server
Type of Program
Driver
Applet
Thin
Client application
Thin
Thin
EJB, servlet
(on the middle tier)
Stored procedure
16-13
OCI
OCI
Server side
Example:
Connection conn =
DriverManager.getConnection(
"jdbc:oracle:thin:@myhost:1521:ORCL",
"scott","tiger");
16-14
getConnection(String url)
Protocol
Database identification
jdbc:oracle:<driver>:@<database>
16-15
JDBC URLs
JDBC uses a URL to identify the database connection. A JDBC URL looks different from an
HTTP or FTP URL. But, like any URL, it is a locator for a particular resource; in this case, a
database. The structure of a JDBC URL is flexible, allowing the driver writer to specify
what to include in the URL. End users need to learn what structure their vendor uses.
The slide shows the general syntax for a JDBC URL and the syntax that Oracle uses for
connecting with an Oracle driver. The general syntax of a JDBC URL is as follows:
jdbc:<subprotocol>:<subname>
<subname> identifies the database. The structure and contents of this string are
determined by the driver developer. For Oracle JDBC drivers, the subname is
<driver>:@<database>, where:
- <driver> is the driver
- <database> provides database connectivity information
The following slides describe the syntax of an Oracle JDBC URL for the different JDBC
drivers for client-side Java application code.
Oracle10g: Java Programming 16-15
jdbc:oracle:thin:@<host>:<port>:<SID>
Example: "jdbc:oracle:thin:@myhost:1521:orcl"
jdbc:oracle:oci:@<tnsname entry>
Example: "jdbc:oracle:oci:@orcl"
16-16
16-17
16-18
16-19
16-20
Example:
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("DELETE FROM order_items
WHERE order_id = 2354");
16-21
Example:
Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("CREATE TABLE temp (col1 NUMBER(5,2),
col2 VARCHAR2(30)");
16-22
16-23
16-26
Column Name
Type
Method
empno
NUMBER
getInt()
hiredate
DATE
getDate()
job
VARCHAR2
getString()
Java Type
java.lang.String
java.io.InputStream
java.math.BigDecimal
boolean
byte
short
int
long
float
double
byte[]
java.io.InputStream
java.sql.Date
java.sql.Time
java.sql.Timestamp
ResultSet Method
getString()
getAsciiStream()
getBigDecimal()
getBoolean()
getByte()
getShort()
getInt()
getLong()
getFloat()
getDouble()
getBytes()
getBinaryStream()
getDate()
getTime()
getTimestamp()
Oracle Type
Oracle.Types.NUMBER
Oracle.Types.CHAR
Oracle.Types.RAW
Oracle.Types.DATE
Oracle.Types.ROWID
Oracle.Types.BLOB
Oracle.Types.CLOB
n/a
Oracle.Types.STRUCT
Oracle.Types.REF
Oracle.Types.ARRAY
Type Extension
oracle.sql.NUMBER
oracle.sql.CHAR
oracle.sql.RAW
oracle.sql.DATE
oracle.sql.ROWID
oracle.sql.BLOB
oracle.sql.CLOB
oracle.sql.BFILE
oracle.sql.STRUCT
oracle.sql.REF
oracle.sql.ARRAY
16-28
Handling Exceptions
{
rset = stmt.executeQuery("SELECT empno,
ename FROM emp");
}
catch (java.sql.SQLException e)
{ ... /* handle SQL errors */ }
...
finally { // clean up
try { if (rset != null) rset.close(); }
catch (Exception e)
{ ... /* handle closing errors */ }
...
16-29
Handling Exceptions
You can use the try-catch-finally block structure for closing resources.
Code Example
Connection conn = null; Statement stmt =
ResultSet rset = null; // initialize
stmt = conn.createStatement();
try {
rset = stmt.executeQuery("SELECT empno,
}
catch (java.sql.SQLException e)
{ ... /* handle errors */ }
...
// Clean up resources
finally {
try { if (rset != null) rset.close(); }
try { if (stmt != null) stmt.close(); }
try { if (conn != null) conn.close(); }
}
null;
catch (Exception e) {}
catch (Exception e) {}
catch (Exception e) {}
Managing Transactions
16-30
rollback() drops all changes because the previous commit or rollback releases any
database locks. commit() and rollback() must be called only when you are not
in autocommit mode.
Note: The server-side driver does not support autocommit mode. You must control
transactions explicitly.
Oracle10g: Java Programming 16-30
16-31
PreparedStatement
PreparedStatement is inherited from Statement; the difference is that
PreparedStatement holds precompiled SQL statements.
If you execute a Statement object many times, its SQL statement is compiled each time.
PreparedStatement is more efficient because its SQL statement is compiled only once,
when you first prepare PreparedStatement. After that, each time you execute the SQL
statement in PreparedStatement, the SQL statement does not have to be recompiled.
Therefore, if you need to execute the same SQL statement several times in an application, it
is more efficient to use PreparedStatement than Statement.
PreparedStatement Parameters
PreparedStatement does not have to execute exactly the same query each time. You
can specify parameters in the PreparedStatement SQL string and supply the actual
values for these parameters when the statement is executed.
The next slide shows how to supply parameters and execute a prepared statement.
16-32
Creating a PreparedStatement
To write changes to the database, such as for INSERT or UPDATE operations, you typically
create a PreparedStatement object. You can use the PreparedStatement object
to execute a statement with varying sets of input parameters. The prepareStatement()
method of your JDBC Connection object allows you to define a statement that takes bind
variable parameters, and returns a JDBC PreparedStatement object with your
statement definition.
16-33
16-34
Connection Pooling
Middle tier
Java servlet
Data source
Middle-tier server code
ConnectionPoolDataSource
JDBC
driver
Database
Database
commands
16-35
Note: Connection pooling is supported in both JDK1.1 and JDK 1.2 OCI and thin drivers.
Connection pooling is not supported for the server driver because the server driver can have
only one connection, which is to the logged-in session in which it is running.
Oracle10g: Java Programming 16-35
Summary
16-38
16-39
Schedule:
Timing
20 minutes
30 minutes
50 minutes
Topic
Lecture
Practice
Total
Objectives
17-2
Lesson Aim
This lesson describes how to deploy a Java application by using WebStart. The lesson
covers the sequence of steps necessary to create a deployment profile and an application
archive. After the application archive has been created and deployed, the lesson describes
the role of the Java Network Launching Protocol (JNLP) file and how to create it.
17-3
1. Request the
application.
2. Launch Web Start on
the local machine.
3. Download the
application.
4. Launch the
application (Draw).
17-4
HTTP
3
HTTP
4
17-5
17-6
17-7
17-8
17-9
17-10
17-11
If you do not enter a name in the Main Class field for the JAR archive, you can still execute
any class with a main() method contained in the JAR file from the command line as
follows:
1. Set the CLASSPATH to include the Java Archive file name java
package.ClassName
Or use the -classpath command-line option as follows:
java -classpath {archivefilename}.jar package.ClassName
17-12
17-13
17-14
17-15
17-16
17-17
17-18
Summary
17-19
17-20
Practice Solutions
Customer
int nextCustomerId
int id
String name
String address
Person
String
phoneclass
toString()
getNamen()
setName()
getAddress()
setAddress()
Company
Individual
String contact
int discount
Person class
String licNumber
toString()
setContact()
getContact()
setDiscount()
getDiscount()
toString()
setLicNumber()
getLicNumber()
Person class
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout
Goal
The goal of this practice is to use JDeveloper to create the main application frame as an
MDI window, and the internal order frames that will be contained within the main window.
These frames will serve as a way to explore Swing classes and ways of building GUI
applications.
Note: If you have successfully completed the previous practice, then continue using the
same directory and files. If the compilation from the previous practice was unsuccessful
and you want to move on to this practice, then change to the les13 directory, load the
OrderEntryWorkspaceLes13 workspace, and continue with this practice.
Your Assignment
Create the main window as an extension of the JFrame class. This class will contain a
JDesktopPane object to manage the internal frame layout. You also create a class based
on the JInternalFrame class in which the customer and order details will be entered
via atomic Swing components. The components layout will be managed through the use of
panels and associated layout managers. You use the JDeveloper Frame Wizard to create a
basic menu for the application, and a status bar in the main application window.
Create the Main Application Window
1. In OrderEntryProject, create a new subclass of the JFrame class.
a. Right-click the project name in the Navigator, and select New from the
context menu. Select the Frame item from Client tier->Swing/AWT category,
and click the OK button.
b. In the Create Frame dialog box, enter the class name
OrderEntryMDIFrame, and extend javax.swing.JFrame. In the
Optional Attributes section, set the Title field to: Order Entry
Application, and select only the Menu Bar and Status Bar check boxes.
Then, click the OK button.
c. Examine the code for the new class that is generated by JDeveloper by selecting
the Source tab. You will notice that JDeveloper creates a jbInit() method
that is called from the default no-arg constructor. The jbInit() method must
contain all code to initialize the user interface structure. You must modify the
code if required, to match the one displayed.
Initial generated code for OrderEntryMDIFrame:
package oe;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
Rest of the Code for OrderEntryMDIFrame
public class OrderEntryMDIFrame extends JFrame {
JLabel statusBar = new JLabel();
JMenuItem menuFileExit = new JMenuItem();
JMenu menuFile = new JMenu();
JMenuBar menuBar1 = new JMenuBar();
JPanel jPanel1 = new JPanel();
BorderLayout borderLayout1 = new BorderLayout();
public OrderEntryMDIFrame() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.setJMenuBar(menuBar1);
this.getContentPane().setLayout(borderLayout1);
jPanel1.setLayout(null);
this.setSize(new Dimension(400, 300));
this.setTitle("Order Entry Application");
menuFile.setText("File");
menuFileExit.setText("Exit");
menuFileExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae) {
fileExit_ActionPerformed(ae);
}
});
statusBar.setText("");
menuFile.add(menuFileExit);
menuBar1.add(menuFile);
this.getContentPane().add(statusBar,
BorderLayout.SOUTH);
this.getContentPane().add(jPanel1,
BorderLayout.CENTER);
}
void fileExit_ActionPerformed(ActionEvent e) {
System.exit(0);
}
}
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
d. In the Editor window, select the Design tab, and examine the visual container
hierarchy and presentation of the frame. The container hierarchy is visible in the
JDeveloper Structure pane (located under the Navigator pane).
e. Return to the Code Editor for the class by selecting the Source tab
and make the following changes:
- Replace the JPanel jPanel1 variable declaration, with:
JDesktopPane desktopPane = new JDesktopPane();
Note: Remember to import javax.swing.JDesktopPane.
- In the jbInit() method, replace jPanel1 references with
desktopPane.
package oe;
:
import java.awt.event.ActionListener;
import javax.swing.JDesktopPane;
public class OrderEntryMDIFrame extends JFrame {
:
JMenuBar menuBar1 = new JMenuBar();
//Jpanel jPanel1 = new JPanel(); // replaced with ...
JDesktopPane desktopPane = new JDesktopPane();
BorderLayout borderLayout1 = new BorderLayout();
:
private void jbInit() throws Exception {
this.setJMenuBar(menuBar1);
this.getContentPane().setLayout(borderLayout1);
desktopPane.setLayout(null); // was jPanel1
:
this.getContentPane().add(desktopPane, //was jPanel1
BorderLayout.CENTER);
}
}
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
f. Compile and save the OrderEntryMDIFrame class.
g. Modify OrderEntry.java by renaming the main() method to
test1(). Create a new public static void main(String[] args)
method that creates an instance of the OrderEntryMDIFrame, and makes it
visible.
package oe;
import java.util.Date;
public class OrderEntry {
public static void main(String[] args) {
OrderEntryMDIFrame frame=new
OrderEntryMDIFrame();
frame.setVisible(true);
}
public static void test1(String[] args) {
Order
order = new Order();
double orderTotal;
: // etc ...
}
}
h. Compile, save, and run the OrderEntry application.
Create in the JInternalFrame Class for Order Data
This frame will contain the bulk of the UI code for data entry and user interaction for an
order. Assign a customer and add items to the order.
2. Right-click the OrderEntryProject and select New from the context menu.
a. Select the Frame item from the Client Tier->Swing/AWT category. In the New
Frame Wizard, enter the class name OrderEntryFrame, and extend the
javax.swing.JInternalFrame. Set the title to the text Order. Then,
click the OK button.
Note: The JInternalFrame class can be selected by clicking the Browse
button.
Generated Code for OrderEntryFrame:
package oe;
import javax.swing.JInternalFrame;
public class OrderEntryFrame extends JInternalFrame {
public OrderEntryFrame() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.setTitle("Order");
}
}
Oracle10g: Java Programming A-82
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
b. The OrderEntryFrame that is generated does not have the desired layout
manager or content pane. To set the layout manager, and add a panel to the
content pane, open OrderEntryFrame with the UI Editor.
Note: When the UI Editor is activated (UI Editor can be invoked by clicking the
Design tab), the Property Inspector window is also displayed, showing the
properties of the object that is selected in the UI Editor.
c. Select the internal frame object by clicking the frame title bar in the UI Editor
or the node labeled this in the Structure window. (You may have to expand
the UI node to view objects in the containment hierarchy.) In the Inspector pane,
locate the layout property and select BorderLayout from the pop-up list
options.
d. Which lines of code has JDeveloper added or changed in your class? When
creating a Swing UI by using the JDeveloper UI Editor, it is wise to view
changes that are made to the source code as an aid to learning what you will
need to write yourself if you are building the UI manually. Remove the
private declaration from BorderLayout. The boldfaced lines highlight
the code lines that are added by changing the layout property:
package oe;
import javax.swing.JInternalFrame;
import java.awt.BorderLayout;
public class OrderEntryFrame extends JInternalFrame
{
BorderLayout borderLayout1 = new BorderLayout();
public OrderEntryFrame() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception{
this.setTitle("Order");
this.getContentPane().setLayout(borderLayout1);
}
}
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
e. JDeveloper provides a Component Palette in the toolbar (ask the instructor, if
needed). In the palette, choose Swing Containers from the pop-up list. Click the
JPanel icon., then click the center of the frame in the UI Editor (or click the
node labeled this in the UI Structure pane) to add a new panel to the center
region of the border layout. If the JPanel icon is not visible they have to expand
the Component Palette window by increasing the height.
Note: Confirm whether the panel is in the center, by selecting the JPanel
object added and checking whether its constraints property (in the
Inspector) has the value Center. If not, then set it to Center.
Lines of code that are added (shown in bold below) include:
import javax.swing.JPanel;
public class OrderEntryFrame extends JInternalFrame
{
BorderLayout borderLayout1 = new BorderLayout();
JPanel jPanel1 = new JPanel();
:
private void jbInit() throws Exception {
this.setTitle("Order");
this.getContentPane().setLayout(borderLayout1);
this.getContentPane().add(jPanel1,
BorderLayout.CENTER);
}
}
3. The panel was added to the frames content pane, and will be used to lay out the rest
of the application UI objects. The panel will be divided into two areas: a top (for
order and customer data), and a bottom (for order item data). Divide the panel into
two by using a GridLayout for the layout, with one column and two rows:
a. Select jPanel1, and set its layout manager property to GridLayout.
b. Expand jPanel1 in the UI Structure pane, and select the gridLayout1
object, set the columns property to 1 and press [Enter], then set the rows
property to 2, and press [Enter].
Code changes that are generated by 3a and 3b:
import java.awt.GridLayout;
public class OrderEntryFrame extends JInternalFrame
{
:
GridLayout gridLayout1 = new GridLayout();
:
private void jbInit() throws Exception {
:
jPanel1.setLayout(gridLayout1);
gridLayout1.setColumns(1);
gridLayout1.setRows(2); // etc
}
}
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
Use the following picture as a visual guide to the desired results for the layout of
these containers. Add another panel to the top, and a scroll pane to the bottom
of the content panel.
c. Add a second panel to the top half (or first row ) of the first panel, by clicking
the JPanel icon in the Swing Components palette, and then clicking the
jPanel1 object in the UI Editor, or in the Structure pane.
Note: Confirm that the new panel is called jPanel2, and more importantly,
that it is nested inside jPanel1 in the hierarchy.
Code changes that are generated (shown in bold):
public class OrderEntryFrame extends JInternalFrame
{
:
GridLayout gridLayout1 = new GridLayout();
JPanel jPanel2 = new JPanel();
:
private void jbInit() throws Exception {
:
gridLayout1.setRows(2);
jPanel1.add(jPanel2, null);
this.getContentPane().add(jPanel1,
BorderLayout.CENTER);
}
}
d. Add a raised-bevel border to the new panel, called jPanel2, by selecting its
border property in the Inspector, and select Swing Border from the pop-up
list. In the Border dialog box, choose BevelBorder and select the RAISED
option button, and then click the OK button.
Note: jPanel2 should visually occupy in the top half of the jPanel1.
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
e. Add a scroll pane object to the bottom half (second row) of the jPanel1, by
clicking the JScrollPane icon in the Swing Components palette, and click the
bottom area of the jPanel1. (Alternatively, click the jPanel1 object in the
Structure pane to add the JScrollPane.)
Code that is generated for steps 3d (on the previous page) and 3e above:
import javax.swing.BorderFactory;
import javax.swing.border.BevelBorder;
import javax.swing.JScrollPane;
public class OrderEntryFrame extends JInternalFrame
{
:
JPanel jPanel2 = new JPanel();
JScrollPane jScrollPane1 = new JScrollPane();
:
private void jbInit() throws Exception {
:
gridLayout1.setRows(2);
jPanel2.setBorder(
BorderFactory.createBevelBorder(
BevelBorder.RAISED));
jPanel1.add(jPanel2, null);
jPanel1.add(jScrollPane1, null);
this.getContentPane().add(jPanel1,
BorderLayout.CENTER);
}
}
f. Use the Structure pane to check whether you have the following containment
hierarchy:
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
Modify OrderEntryMDIFrame Class Containing an Internal OrderEntryFrame
4. To view the visual results of your internal frame at run time, modify the constructor
in OrderEntryMDIFrame to create an instance of OrderEntryFrame, and
make it visible.
a. Edit OrderEntryMDIFrame.java, and at the end of the constructor, add
the following lines of code:
OrderEntryFrame iFrame = new OrderEntryFrame();
iFrame.setVisible(true);
desktopPane.add(iFrame);
Results are:
package oe;
:
public class OrderEntryMDIFrame extends JFrame {
:
public OrderEntryMDIFrame() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
OrderEntryFrame iFrame = new OrderEntryFrame();
iFrame.setVisible(true);
desktopPane.add(iFrame);
}
}
Note: The bounds (size and location) of the internal frame must now be set;
otherwise, it will not become visible. In addition, you must also alter the
dimensions of OrderEntryMDIFrame to be larger than the initial size of the
internal frame OrderEntryFrame.
b. In the jbInit() method of the OrderEntryMDIFrame class, locate the
following statement:
this.setSize(new Dimension(400,300));
Then modify the dimension arguments to be 700,500.
Results:
private void jbInit() throws Exception {
:
this.setSize(new Dimension(700, 500));
this.setTitle("Order Entry Application"); ...
}
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
c. In the OrderEntryFrame, add the following line into the jbInit()
method:
this.setBounds(0, 0, 400, 300);
Results:
package oe;
:
public class OrderEntryFrame extends JInternalFrame
{
:
private void jbInit() throws Exception {
this.setTitle("Order");
this.setBounds(0, 0, 400, 300);
:
}
}
d. Compile and save OrderEntryMDIFrame and OrderEntryFrame.
e. Run the OrderEntry class to view the results.
5. You will notice that the internal frame cannot be maximized, iconified
(minimized), or closed. Make changes to OrderEntryFrame to enable these
features.
a. In the jbInit() method, add the following lines of code to enable the internal
frame to maximized, iconified, and closed.
this.setMaximizable(true);
this.setInconifiable(true);
this.setClosable(true);
Results:
package oe;
:
public class OrderEntryFrame extends JInternalFrame
{
:
private void jbInit() throws Exception {
this.setTitle("Order");
this.setBounds(0, 0, 400, 300);
this.setMaximizable(true);
this.setInconifiable(true);
this.setClosable(true);
:
}
}
b. Compile and save the changes to OrderEntryFrame.java.
c. Run the OrderEntry application, and observe the changes.
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
Add UI Components to OrderEntryFrame
6. Before adding UI components to jPanel2 in OrderEntryFrame, set its layout
to null.
Note: You can also use the JDeveloper XYLayout.
In either case, JDeveloper will use absolute positioning and sizing for components
that are added to the panel. It is easier to use absolute positioning when building the
initial UI layout. You change the layout again in a subsequent lesson. Use the
following image as a guide to the desired results:
a. In the Design mode, select the Swing option in the Component Palette pop-up
list. Then add a Jlabel to jPanel2 and set its text property to Order
Id. Resize the label to see the label value, if needed. What lines of code have
been added to your class?
Hint: You should find at least five lines of code (some of them in the
jbInit() method). Try to identify the three that make the object visible in the
panel.
Note: The setBounds value can be modifed if required in the Source to make
the label clearly visible
Bold lines show the key 5 lines of code that are added by JDeveloper, using
the null layout manager, after step 6a (if you use the XYLayout
manager, then some classes and settings will differ). The bold italic lines of
code are other changes that are made:
package oe;
:
import javax.swing.JLabel;
import java.awt.Rectangle;
public class OrderEntryFrame extends JInternalFrame
{
:
JLabel jLabel1 = new JLabel();
private void jbInit() throws Exception {
:
jPanel2.setLayout(null);
jLabel1.setText("Order Id");
jLabel1.setBounds(new Rectangle(5, 10, 50, 15));
jPanel2.add(jLabel1, null);
:
}
}
Oracle10g: Java Programming A-89
Practice 14: User Interface Design: Swing Basics Planning the Application
Layout (continued)
b. From Swing icons, select and add a JTextField component into jPanel2,
to the right of the label, then delete the default value in the text property of
the text field (remember to press the Enter key after deleting the text value).
Resulting code changes are:
package oe;
:
import javax.swing.JLabel;
import java.awt.Rectangle;
import javax.swing.JTextField;
public class OrderEntryFrame extends JInternalFrame
{
:
JLabel jLabel1 = new JLabel();
JTextField jTextField1 = new JTextField();
private void jbInit() throws Exception {
:
jPanel2.setLayout(null);
jLabel1.setText("Order Id");
jLabel1.setBounds(new Rectangle(5, 10, 50, 15));
jTextField1.setBounds(
new Rectangle(55, 5, 59, 20));
jPanel2.add(jTextField1, null);
jPanel2.add(jLabel1, null);
:
}
}
c. Compile and save OrderEntryFrame, and run OrderEntry to view
results.
B
Java Language
Quick-Reference
Guide
Console Output
Java applications and applets can output simple messages to the console as
follows:
System.out.println("This is displayed on the console");
Data Types
boolean
byte
char
short
int
long
float
double
Operators
+ - * / %
++ --
+= -= *= /= %= etc.
&&
||
!
== != > >= < <=
& | ^ ~
<< >> >>>
instanceof
if (dayname.equals("Sat") || dayname.equals("Sun")){
System.out.println("Hooray for the weekend");
}
else if (dayname.equals("Mon")) {
System.out.println("I dont like Mondays");
}
else {
System.out.println("Not long for the weekend!");
}
Control Flow: switch
switch is used to check an integer (or character) against a fixed list of
alternative values:
int daynum;
switch (daynum) {
case 0:
case 6:
System.out.println("Hooray for the weekend");
break;
case 1:
System.out.println("I dont like Mondays");
break;
default:
System.out.println("Not long for the weekend!");
break;
}
i*i);
i*i);
int positiveValue;
do {
positiveValue = getNumFromUser();
}
while (positiveValue < 0);
Defining Classes
When you define a class, you define the data attributes (usually private) and
the methods (usually public) for a new data type. The class definition is placed
in a .java file as follows:
// This file is Student.java. The class is declared
// public, so that it can be used anywhere in the program
public class Student {
private String name;
private int
numCourses = 0;
// Constructor to initialize all the data members
public Student(String n, int c) {
name = n;
numCourses = c;
}
// No-arg constructor, to initialize with defaults
public Student() {
this("Anon", 0);
// Call other constructor
}
// finalize() is called when obj is garbage collected
public void finalize() {
System.out.println("Goodbye to this object");
}
// Other methods
public void attendCourse() {
numCourses++;
}
public void cancelPlaceOnCourse() {
numCourses--;
}
public boolean isEligibleForChampagne() {
return (numCourses >= 3);
}
}
Using Classes
To create an object and send messages to the object:
public class MyTestClass {
public static void main(String[] args) {
// Step 1 - Declare object references
// These refer to null initially in this example
Student me, you;
if (me.isEligibleForChampagne())
System.out.println("Thanks very much");
}
}
Arrays
An array behaves like an object. Arrays are created and manipulated as follows:
// Step 1 - Declare a reference to an array
int[] squares;
// Could write int squares[];
// Step 2 - Create the array "object" itself
squares = new int[5]; // Creates array with 5 slots
// Step 3 - Initialize slots in the array
for (int i=0; i < squares.length; i++) {
squares[i] = i * i;
System.out.println(squares[i]);
}
Note that array elements start at [0], and that arrays have a length property that
gives you the size of the array. If you inadvertently exceed an arrays bounds, an
exception is thrown at run time and the program aborts.
Note: Arrays can also be set up by using the following abbreviated syntax:
String[] cities = {
"San Francisco",
"Dallas",
"Minneapolis",
"New York",
"Washington, D.C."
};
Abstract Classes
An abstract class is one that can never be instantiated; in other words, you cannot
create an object of such a class. Abstract classes are specified as follows:
// Abstract superclass
public abstract class Mammal {
// Concrete subclasses
public class Cat extends Mammal {
}
public class Dog extends Mammal {
}
public class Mouse extends Mammal {
Abstract Methods
An abstract method is one that does not have a body in the superclass. Each concrete
subclass is obliged to override the abstract method and provide an implementation;
otherwise, the subclass is itself deemed abstract because it does not implement all its
methods.
// Abstract superclass
public abstract class Mammal {
// Declare some
public abstract
public abstract
public abstract
abstract methods
void eat();
void move();
void reproduce();
Interfaces
An interface is similar to an abstract class with 100% abstract methods and no
instance variables. An interface is defined as follows:
public interface Runnable {
public void run();
}
A class can implement an interface as follows. The class is obliged to provide an
implementation for every method specified in the interface; otherwise, the class
must be declared abstract because it does not implement all its methods.
public class MyApp extends Applet implements Runnable {
public void run() {
// This is called when the Applet is kicked off
// in a separate thread
Static Variables
A static variable is like a global variable for a class. In other words, you get
only one instance of the variable for the whole class, regardless of how many
objects exist. static variables are declared in the class as follows:
public class Account {
private String accnum;
private double balance = 0.0;
// Instance var
// Instance var
// Class var
}
Static Methods
A static method in a class is one that can access only static items; it cannot
access any non-static data or methods. static methods are defined in the
class as follows:
public class Account {
public static void setIntRate(double newRate) {
intRate = newRate;
}
public static double getIntRate() {
return intRate;
}
}
To invoke a static method, use the name of the class as follows:
public class MyTestClass {
public static void main(String[] args) {
System.out.println("Interest rate is" +
Account.getIntRate());
}
}
Packages
Related classes can be placed in a common package as follows:
// Car.java
package mycarpkg;
public class Car {
// Engine.java
package mycarpkg;
public class Engine {
// Transmission.java
package mycarpkg;
public class Transmission {
}
Importing Packages
Anyone needing to use the classes in this package can import all or some of the
classes in the package as follows:
import mycarpkg.*;
or
import mycarpkg.Car; // just import individual classes
// final methods
public class MySecurityClass {
public final void validatePassword(String password) {
}
}
// final variables
public class MyTrigClass {
public static final double PI = 3.1415;
Exception Handling
Exception handling is achieved through five keywords in Java:
try
The block of code where statements that can cause an exception are
placed
catch The block of code where error processing is placed
finally An optional block of code after a try block, for unconditional
execution
throw The keyword that is used in the low-level code to generate or throw an
exception
throws The keyword that specifies the list of exceptions that a method can
throw
Here are some examples:
public class MyClass {
public void anyMethod() {
try {
func1();
func2();
func3();
}
catch (IOException e) {
System.out.println("IOException:" + e);
}
catch (MalformedURLException e) {
System.out.println("MalformedURLException:" + e);
}
finally {
System.out.println("This is always displayed");
}
}
public void func1() throws IOException {
}
public void func2() throws MalformedURLException {
}
public void func3() throws IOException,
MalformedURLException {
}
}
Company.java
package oe;
public class Company extends Customer
{
private String contact;
private int discount;
public Company(String aName, String aAddress, String aPhone,
String aContact, int aDiscount)
{
super(aName, aAddress, aPhone);
contact = aContact;
discount = aDiscount;
}
public String getContact()
{
return contact;
}
public void setContact(String newContact)
{
contact = newContact;
}
public int getDiscount()
{
return discount;
}
public void setDiscount(int newDiscount)
{
discount = newDiscount;
}
public String toString()
{
return super.toString() + " (" + contact + ", " + discount +
"%)";
}
}
Customer.java
package oe;
public class Customer
{
private static int nextCustomerId = 0;
private int id;
private String name;
private String address;
private String phone;
public Customer()
{
nextCustomerId++;
setId(nextCustomerId);
}
public Customer(String theName, String theAddress, String
thePhone)
{
this();
name = theName;
address = theAddress;
phone = thePhone;
}
public int getId()
{
return id;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public String getPhone()
{
return phone;
}
Customer.java (continued)
public void setId(int newId)
{
id = newId;
}
public void setName(String newName)
{
name = newName;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public void setPhone(String newPhone)
{
phone = newPhone;
}
public String toString()
{
return "[" + Util.getClassName(this) + "] " + id + " " +
name + " " + address + " " + phone;
}
}
DataMan.java
package oe;
import java.util.HashMap;
public class DataMan
{
private static class ProductMap extends HashMap
{
public void add(Product p)
{
String key = Integer.toString(p.getId());
put(key, p);
}
}
private static Customer[] customers = null;
private static ProductMap products = null;
public static void buildCustomers()
{
if (customers != null) return;
customers = new Customer[6];
customers[0] = new Customer("Gary Williams", "Houston, TX",
"713.555.8765");
customers[1] = new Customer("Lynn Munsinger", "Orlando, FL",
"407.695.2210");
customers[2] = new Customer("Rachael O'leary", "Brisbane,
QLD", "07.3031.1100");
customers[3] = new Customer("Tony Obermeit", "Brisbane,
QLD", "07.3031.9987");
customers[4] = new Company("Oracle Corporation", "Redwood
Shores, CA", "800-ORACLE-1", "Larry Ellison", 20);
customers[5] = new Individual("Mel Gibson", "Hollywood, CA",
"213.MEL.GIBSON", "MAD-MAX");
}
DataMan.java (continued)
public static void buildProducts()
{
if (products != null) return;
products = new ProductMap();
products.add(new Hardware("SDRAM - 128 MB", null, 299.0));
products.add(new Hardware("GP 800x600", null, 48.0));
products.add(new Software("Spreadsheet-SSP/V2.0", null,
45.0));
products.add(new Software("Word Processing-SWP/V4.5", null,
65.0));
products.add(new Manual("Manual-Vision OS/2x +", null,
125.0));
}
public static Customer findCustomerById(int custId) throws
NotFoundException
{
Customer c = null;
for (int i = 0; i < customers.length; i++)
{
if (customers[i].getId() == custId)
{
c = customers[i];
break;
}
}
if (c == null)
{
throw new NotFoundException("Customer with id " + custId +
" does not exist");
}
return c;
}
DataMan.java (continued)
public static Product findProductById(int id) throws
NotFoundException
{
String key = Integer.toString(id);
Product product = (Product) products.get(key);
if (product == null)
{
throw new NotFoundException("Product with id " + id + " is
not found");
}
return product;
}
static
{
buildCustomers();
buildProducts();
}
}
Hardware.java
package oe;
public class Hardware extends Product implements Taxable
{
private int warrantyPeriod = 6;
public Hardware(String name, String desc, double price)
{
setName(name);
setDescription(desc);
setRetailPrice(price);
}
public int getWarrantyPeriod()
{
return warrantyPeriod;
}
public void setWarrantyPeriod(int newWarrantyPeriod)
{
warrantyPeriod = newWarrantyPeriod;
}
public double getTax(double amount)
{
return amount * TAX_RATE;
}
}
Individual.java
package oe;
public class Individual extends Customer
{
private String licNumber;
public Individual(String aName, String aAddress, String
aPhone, String aLicNumber)
{
super(aName, aAddress, aPhone);
licNumber = aLicNumber;
}
public String getLicNumber()
{
return licNumber;
}
public void setLicNumber(String newLicNumber)
{
licNumber = newLicNumber;
}
public String toString()
{
return super.toString() + " (" + licNumber + ")";
}
}
Manual.java
package oe;
public class Manual extends Product
{
private String publisher = "Oradev Press";
public Manual(String name, String desc, double price)
{
setName(name);
setDescription(desc);
setRetailPrice(price);
}
public String getPublisher()
{
return publisher;
}
public void setPublisher(String newPublisher)
{
publisher = newPublisher;
}
}
NotFoundException.java
package oe;
public class NotFoundException extends Exception
{
public NotFoundException(String message)
{
super(message);
}
}
Order.java
package oe;
import
import
import
import
import
import
java.util.Date;
java.util.Calendar;
java.text.MessageFormat;
java.util.Vector;
java.util.Enumeration;
javax.swing.DefaultListModel;
Order.java (continued)
public int getId()
{
return id;
}
public Date getOrderDate()
{
return orderDate;
}
public String getShipDate(char region)
{
int daysToShip = Util.getDaysToShip(region);
Calendar c = Calendar.getInstance();
c.setTime(orderDate);
c.add(Calendar.DAY_OF_MONTH, daysToShip);
return c.getTime().toString();
}
public String getShipMode()
{
return shipMode;
}
public double getOrderTotal()
{
return orderTotal;
}
public String getstatus()
{
return status;
}
public void setId(int newId)
{
id = newId;
}
Order.java (continued)
public void setOrderDate(int d, int m, int y)
{
int daysInMonth = Util.lastDayInMonth(m, y);
if (d > 0 && d <= daysInMonth)
{
if ((m > 0 && m <= 12) && (y > 0))
{
Calendar c = Calendar.getInstance();
c.set(y, m - 1, d);
orderDate = c.getTime();
}
}
}
public void setOrderDate(Date newOrderDate)
{
orderDate = newOrderDate;
}
public void setShipMode(String newShipMode)
{
shipMode = newShipMode;
}
public void setOrderTotal(double newOrderTotal)
{
orderTotal = newOrderTotal;
}
public void setStatus(String newStatus)
{
status = newStatus;
}
public Customer getCustomer()
{
return customer;
}
Order.java (continued)
public void setCustomer(Customer newCustomer)
{
customer = newCustomer;
}
public String toString()
{
/*
// For Les08 lab 4a.
return "Order: " + id +
" Date: " + Util.toDateString(orderDate) +
" Shipped: " + shipMode +
" (" + Util.toMoney(getOrderTotal()) + ")";
*/
Object[] msgVals = { new Integer(id),
Util.toDateString(orderDate),
shipMode, Util.toMoney(getOrderTotal()) };
return MessageFormat.format("Order: {0} Date: {1} Shipped: {2}
(Total: {3})",
msgVals);
}
public void addOrderItem(int productId)
{
OrderItem item = null;
boolean productFound = false;
for (int i = 0; i < items.size() && !productFound; i++)
{
item = (OrderItem) items.elementAt(i);
productFound = (item.getProduct().getId() == productId);
}
if (productFound)
{
item.setQuantity(item.getQuantity() + 1);
}
else
{
Order.java (continued)
try
{
Product p = DataMan.findProductById(productId);
item = new OrderItem(p);
items.addElement(item);
item.setLineNbr(items.size());
}
catch (NotFoundException e)
{
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
return;
}
}
orderTotal += item.getUnitPrice();
}
public void removeOrderItem(int productId)
{
OrderItem item = null;
int idx = 0;
for (int i = 0; i < items.size(); i++)
{
item = (OrderItem) items.elementAt(i);
idx = i;
if (item.getProduct().getId() == productId)
{
item.setQuantity(item.getQuantity() - 1);
if (item.getQuantity() == 0)
{
items.removeElementAt(idx);
for (; idx < items.size(); idx++)
{
item = (OrderItem) items.elementAt(idx);
item.setLineNbr(idx+1);
}
}
orderTotal -= item.getUnitPrice();
}
}
}
Order.java (continued)
public void showOrder()
{
double taxTotal = 0.0;
System.out.println(toString());
if (customer != null)
{
System.out.println("Customer: " + customer);
}
System.out.println("Items:");
for (Enumeration e = items.elements(); e.hasMoreElements(); )
{
OrderItem item = (OrderItem) e.nextElement();
taxTotal += item.getTax();
System.out.println(item.toString());
}
System.out.println("Total tax: " + Util.toMoney(taxTotal));
System.out.println("Order total including tax: " +
Util.toMoney(orderTotal + taxTotal));
System.out.println();
}
public DefaultListModel getModel()
{
return items;
}
public double getTax()
{
double totalTax = 0.0;
for (Enumeration e = items.elements(); e.hasMoreElements(); )
{
OrderItem item = (OrderItem) e.nextElement();
totalTax += item.getTax();
}
return totalTax;
}
}
OrderEntry.java
package oe;
import java.util.Date;
import javax.swing.UIManager;
public class OrderEntry
{
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
;
}
catch (Exception e) { }
OrderEntryMDIFrame frame = new OrderEntryMDIFrame();
frame.setVisible(true);
}
public static void test1(String[] args)
{
Order
order = new Order();
double orderTotal;
boolean exceedsLimit;
double taxRate = 0.0825;
double taxValue;
System.out.println("Order Entry Application");
orderTotal = order.getOrderTotal();
System.out.println("Order Total: " + orderTotal);
taxValue = orderTotal * taxRate;
System.out.println("Tax Value:
" + taxValue);
orderTotal += taxValue;
System.out.println("Final Total: " + orderTotal);
exceedsLimit = orderTotal > 10.00;
System.out.println("Total Exceeds $10.00: " + exceedsLimit);
OrderEntry.java (continued)
// order.setOrderDate(27, 1, 2001);
order.setOrderDate(27, 2, 2001);
char region = 'A';
String shipDate = order.getShipDate(region);
System.out.println("Order Date:
" +
order.getOrderDate());
System.out.println("Days till shipping: " +
Util.getDaysToShip(region));
System.out.println("Expected Ship Date: " + shipDate);
try
{
System.out.println("\nCustomers:");
System.out.println(DataMan.findCustomerById(1).toString());
System.out.println(DataMan.findCustomerById(2));
order.setCustomer(DataMan.findCustomerById(5));
order.addOrderItem(2001);
order.addOrderItem(2002);
order.addOrderItem(2001);
order.showOrder();
order.removeOrderItem(2001);
order.removeOrderItem(2002);
order.showOrder();
// Order order2 = new Order(new Date(), "overnight");
Order order2 = new Order(Util.getDate(7, 3, 2002),
"overnight");
order2.setCustomer(DataMan.findCustomerById(6));
order2.showOrder();
for (int i = 0; i < args.length; i++)
{
int custId = Integer.parseInt(args[i]);
System.out.println("Arg: " + custId + " is: " +
DataMan.findCustomerById(custId));
}
System.out.println("Product id: " +
DataMan.findProductById(2001));
}
catch (NotFoundException e)
{
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
Oracle10g: Java Programming C-19
OrderEntryFrame.java
package oe;
import javax.swing.JInternalFrame;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.border.BevelBorder;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import java.awt.Rectangle;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.JList;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
public class OrderEntryFrame extends JInternalFrame
{
BorderLayout borderLayout1 = new BorderLayout();
JPanel jPanel1 = new JPanel();
GridLayout gridLayout1 = new GridLayout();
JPanel jPanel2 = new JPanel();
JScrollPane jScrollPane1 = new JScrollPane();
JLabel jLabel1 = new JLabel();
JTextField orderIdTxt = new JTextField();
JLabel jLabel2 = new JLabel();
JLabel jLabel3 = new JLabel();
JLabel jLabel4 = new JLabel();
JLabel jLabel5 = new JLabel();
JTextField custIdTxt = new JTextField();
JTextField custNameTxt = new JTextField();
JTextField custAddressTxt = new JTextField();
JTextField custPhoneTxt = new JTextField();
JButton findBtn = new JButton();
JLabel jLabel6 = new JLabel();
JTextField prodIdTxt = new JTextField();
JButton addBtn = new JButton();
JButton removeBtn = new JButton();
JLabel jLabel7 = new JLabel();
OrderEntryFrame.java (continued)
JLabel orderDateLbl = new JLabel();
JLabel jLabel8 = new JLabel();
JLabel orderTotalLbl = new JLabel();
JList orderItemList = new JList();
Order order = null;
private static int x = 0;
private static int y = 0;
private static final int OFFSET = 20;
private static final int MAX_OFFSET = 200;
JLabel taxTextLbl = new JLabel();
JLabel totalTaxLbl = new JLabel();
public OrderEntryFrame()
{
try
{
jbInit();
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void jbInit() throws Exception
{
this.setTitle("Order");
this.setBounds(0, 0, 400, 300);
this.setMaximizable(true);
this.setIconifiable(true);
this.setClosable(true);
this.getContentPane().setLayout(borderLayout1);
jPanel1.setLayout(gridLayout1);
gridLayout1.setColumns(1);
gridLayout1.setRows(2);
OrderEntryFrame.java (continued)
jPanel2.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISE
D));
jPanel2.setLayout(null);
jLabel1.setText("Order Id");
jLabel1.setBounds(new Rectangle(5, 5, 59, 16));
orderIdTxt.setBounds(new Rectangle(75, 5, 59, 20));
jLabel2.setText("Customer Id");
jLabel2.setBounds(new Rectangle(3, 28, 71, 16));
jLabel3.setText("Name");
jLabel3.setBounds(new Rectangle(5, 50, 57, 16));
jLabel4.setText("Address");
jLabel4.setBounds(new Rectangle(5, 70, 59, 16));
jLabel5.setText("Phone");
jLabel5.setBounds(new Rectangle(5, 90, 34, 16));
custIdTxt.setBounds(new Rectangle(75, 30, 59, 20));
custNameTxt.setBounds(new Rectangle(75, 50, 140, 20));
custAddressTxt.setBounds(new Rectangle(75, 70, 140, 20));
custPhoneTxt.setBounds(new Rectangle(75, 90, 140, 20));
findBtn.setText("Find");
findBtn.setBounds(new Rectangle(137, 27, 73, 21));
findBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
findBtn_actionPerformed(e);
}
});
jLabel6.setText("Product Id");
jLabel6.setBounds(new Rectangle(230, 70, 59, 16));
prodIdTxt.setBounds(new Rectangle(295, 68, 85, 20));
addBtn.setText("Add");
addBtn.setBounds(new Rectangle(230, 90, 55, 23));
addBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
addBtn_actionPerformed(e);
}
});
OrderEntryFrame.java (continued)
removeBtn.setEnabled(false);
removeBtn.setText("Remove");
removeBtn.setBounds(new Rectangle(295, 90, 85, 23));
removeBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
removeBtn_actionPerformed(e);
}
});
jLabel7.setText("Order Date");
jLabel7.setBounds(new Rectangle(230, 5, 63, 16));
orderDateLbl.setBorder(BorderFactory.createLineBorder(Color.black,
1));
orderDateLbl.setBounds(new Rectangle(295, 5, 85, 16));
jLabel8.setText("Order Total");
jLabel8.setBounds(new Rectangle(230, 25, 61, 16));
orderTotalLbl.setBorder(BorderFactory.createLineBorder(Color.black,
1));
orderTotalLbl.setBounds(new Rectangle(295, 25, 85, 16));
orderItemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
;
orderItemList.addListSelectionListener(new
ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
orderItemList_valueChanged(e);
}
});
taxTextLbl.setText("Total Tax");
taxTextLbl.setBounds(new Rectangle(230, 45, 65, 16));
OrderEntryFrame.java (continued)
totalTaxLbl.setBorder(BorderFactory.createLineBorder(Color.black,
1));
totalTaxLbl.setBounds(new Rectangle(295, 45, 85, 16));
jPanel2.add(totalTaxLbl, null);
jPanel2.add(taxTextLbl, null);
jPanel2.add(orderTotalLbl, null);
jPanel2.add(jLabel8, null);
jPanel2.add(orderDateLbl, null);
jPanel2.add(jLabel7, null);
jPanel2.add(removeBtn, null);
jPanel2.add(addBtn, null);
jPanel2.add(prodIdTxt, null);
jPanel2.add(jLabel6, null);
jPanel2.add(findBtn, null);
jPanel2.add(custPhoneTxt, null);
jPanel2.add(custAddressTxt, null);
jPanel2.add(custNameTxt, null);
jPanel2.add(custIdTxt, null);
jPanel2.add(jLabel5, null);
jPanel2.add(jLabel4, null);
jPanel2.add(jLabel3, null);
jPanel2.add(jLabel2, null);
jPanel2.add(orderIdTxt, null);
jPanel2.add(jLabel1, null);
jPanel1.add(jPanel2, null);
jScrollPane1.getViewport().add(orderItemList, null);
jPanel1.add(jScrollPane1, null);
this.getContentPane().add(jPanel1, BorderLayout.CENTER);
initOrder();
setBounds();
taxTextLbl.setVisible(false);
totalTaxLbl.setVisible(false);
}
OrderEntryFrame.java (continued)
private void initOrder()
{
order = new Order();
orderIdTxt.setText(Integer.toString(order.getId()));
orderDateLbl.setText(Util.toDateString(order.getOrderDate()));
orderTotalLbl.setText(Util.toMoney(order.getOrderTotal()));
}
private void setBounds()
{
this.setResizable(true);
this.setBounds(x, y, this.getWidth(), this.getHeight());
x = (x + OFFSET) % MAX_OFFSET;
y = (y + OFFSET) % MAX_OFFSET;
}
public void setActive(boolean active)
{
try
{
this.setSelected(active);
}
catch (Exception e) {}
this.setVisible(active);
if (active)
{
this.toFront();
}
}
void findBtn_actionPerformed(ActionEvent e)
{
int custId = 0;
Customer customer = null;
OrderEntryFrame.java (continued)
if (custIdTxt.getText().length() > 0)
{
try
{
custId = Integer.parseInt(custIdTxt.getText());
customer = DataMan.findCustomerById(custId);
order.setCustomer(customer);
custNameTxt.setText(customer.getName());
custAddressTxt.setText(customer.getAddress());
custPhoneTxt.setText(customer.getPhone());
}
catch (NumberFormatException err)
{
JOptionPane.showMessageDialog(this,
"The Customer Id: " + err.getMessage() + " is not a valid
number",
"Error", JOptionPane.ERROR_MESSAGE);
custIdTxt.setText("");
}
catch (NotFoundException err)
{
JOptionPane.showMessageDialog(this, err.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
custIdTxt.setText("");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a Customer
Id", "Error", JOptionPane.ERROR_MESSAGE);
}
}
void addBtn_actionPerformed(ActionEvent e)
{
Product p = null;
int prodId = 0;
OrderEntryFrame.java (continued)
if (prodIdTxt.getText().length() > 0)
{
try
{
prodId = Integer.parseInt(prodIdTxt.getText());
p = DataMan.findProductById(prodId);
order.addOrderItem(prodId);
if (orderItemList.getModel().getSize() == 0)
{
orderItemList.setModel(order.getModel());
}
orderItemList.updateUI();
orderTotalLbl.setText(Util.toMoney(order.getOrderTotal()));
showTaxFields();
}
catch (Exception err)
{
String message = err.getMessage();
if (err instanceof NumberFormatException)
{
message = "Product Id '" + message + "' is not a valid
number";
}
JOptionPane.showMessageDialog(this, message, "Error",
JOptionPane.ERROR_MESSAGE);
prodIdTxt.setText("");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a Product
Id", "Error", JOptionPane.ERROR_MESSAGE);
}
}
OrderEntryFrame.java (continued)
void orderItemList_valueChanged(ListSelectionEvent e)
{
if (orderItemList.isSelectionEmpty())
{
removeBtn.setEnabled(false);
}
else
{
removeBtn.setEnabled(true);
}
}
void removeBtn_actionPerformed(ActionEvent e)
{
OrderItem item = (OrderItem) orderItemList.getSelectedValue();
order.removeOrderItem(item.getProduct().getId());
orderItemList.updateUI();
orderTotalLbl.setText(Util.toMoney(order.getOrderTotal()));
showTaxFields();
if (orderItemList.isSelectionEmpty())
{
removeBtn.setEnabled(false);
}
}
private void showTaxFields()
{
if (order.getTax() > 0.0)
{
totalTaxLbl.setText(Util.toMoney(order.getTax()));
orderTotalLbl.setText(Util.toMoney(order.getTax() +
order.getOrderTotal()));
taxTextLbl.setVisible(true);
totalTaxLbl.setVisible(true);
}
else
{
taxTextLbl.setVisible(false);
totalTaxLbl.setVisible(false);
}
}
}
OrderEntryMDIFrame.java
package oe;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDesktopPane;
public class OrderEntryMDIFrame extends JFrame
{
JLabel statusBar = new JLabel();
JMenuItem menuFileExit = new JMenuItem();
JMenu menuFile = new JMenu();
JMenuBar menuBar1 = new JMenuBar();
JDesktopPane desktopPane = new JDesktopPane();
BorderLayout borderLayout1 = new BorderLayout();
JMenu menuOrder = new JMenu();
JMenuItem newMenuItem = new JMenuItem();
JMenuItem openMenuItem = new JMenuItem();
JMenuItem saveMenuItem = new JMenuItem();
JMenuItem closeMenuItem = new JMenuItem();
JMenuItem printMenuItem = new JMenuItem();
public OrderEntryMDIFrame()
{
try
{
jbInit();
}
catch(Exception e)
{
e.printStackTrace();
}
}
OrderEntryMDIFrame.java (continued)
private void jbInit() throws Exception
{
this.setJMenuBar(menuBar1);
this.getContentPane().setLayout(borderLayout1);
desktopPane.setLayout(null);
menuOrder.setText("Order");
newMenuItem.setText("New");
newMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
newMenuItem_actionPerformed(e);
}
});
openMenuItem.setText("Open");
saveMenuItem.setText("Save");
closeMenuItem.setText("Close");
printMenuItem.setText("Print");
this.setSize(new Dimension(700, 500));
this.setTitle("Order Entry Application");
menuFile.setText("File");
menuFileExit.setText("Exit");
menuFileExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
fileExit_ActionPerformed(ae);
}
});
statusBar.setText("");
menuFile.add(menuFileExit);
menuBar1.add(menuFile);
menuOrder.add(newMenuItem);
menuOrder.add(openMenuItem);
menuOrder.add(saveMenuItem);
menuOrder.add(closeMenuItem);
menuOrder.addSeparator();
menuOrder.add(printMenuItem);
menuBar1.add(menuOrder);
this.getContentPane().add(statusBar, BorderLayout.SOUTH);
this.getContentPane().add(desktopPane, BorderLayout.CENTER);
}
OrderEntryMDIFrame.java (continued)
void fileExit_ActionPerformed(ActionEvent e)
{
System.exit(0);
}
void newMenuItem_actionPerformed(ActionEvent e)
{
OrderEntryFrame iFrame = new OrderEntryFrame();
//iFrame.setVisible(true);
desktopPane.add(iFrame);
iFrame.setActive(true);
}
}
OrderItem.java
package oe;
public class OrderItem
{
private int lineNbr;
private int quantity;
private double unitPrice;
private Product product;
public OrderItem(Product newProduct)
{
product = newProduct;
unitPrice = product.getRetailPrice();
quantity = 1;
}
public int getLineNbr()
{
return lineNbr;
}
public int getQuantity()
{
return quantity;
}
public double getUnitPrice()
{
return unitPrice;
}
public Product getProduct()
{
return product;
}
public double getItemTotal()
{
return quantity * unitPrice;
}
public void setLineNbr(int newLineNbr)
{
lineNbr = newLineNbr;
}
OrderItem.java (continued)
public void setQuantity(int newQuantity)
{
quantity = newQuantity;
}
public void setUnitPrice(double newUnitPrice)
{
unitPrice = newUnitPrice;
}
public void setProduct(Product newProduct)
{
product = newProduct;
}
public double getTax()
{
double itemTax = 0.0;
if (product instanceof Taxable)
{
itemTax =((Taxable) product).getTax(getItemTotal());
}
return itemTax;
}
public String toString()
{
String result = lineNbr + " product: " + product + " qty: " +
quantity;
if (product instanceof Taxable)
{
result += " tax: " + Util.toMoney(getTax());
}
result += " Item total: " + Util.toMoney(getItemTotal());
return result;
}
}
Product.java
package oe;
public abstract class Product
{
private static int nextProductId = 2000;
private int id;
private String name;
private String description;
private double retailPrice;
public Product()
{
id = nextProductId++;
}
public int getId()
{
return id;
}
public void setId(int newId)
{
id = newId;
}
public String getName()
{
return name;
}
public void setName(String newName)
{
name = newName;
}
public String getDescription()
{
return description;
}
public void setDescription(String newDescription)
{
description = newDescription;
}
Product.java (continued)
public double getRetailPrice()
{
return retailPrice;
}
public void setRetailPrice(double newRetailPrice)
{
retailPrice = newRetailPrice;
}
public String toString()
{
return "[" + Util.getClassName(this) + "] " + id + " " + name +
" " + Util.toMoney(retailPrice);
}
}
Software.java
package oe;
public class Software extends Product
{
private String license = "30 Day Trial";
public Software(String name, String desc, double price)
{
setName(name);
setDescription(desc);
setRetailPrice(price);
}
public String getLicense()
{
return license;
}
public void setLicense(String newLicense)
{
license = newLicense;
}
}
Taxable.java
package oe;
public interface Taxable
{
double TAX_RATE = 0.10;
double getTax(double amount);
}
Util.java
package oe;
import
import
import
import
java.text.DecimalFormat;
java.util.Date;
java.text.SimpleDateFormat;
java.util.GregorianCalendar;
Util.java (continued)
public static int getDaysToShip(char region)
{
int daysToShip = 1;
switch (region)
{
case 'A':
daysToShip = 3;
break;
case 'E':
daysToShip = 5;
break;
case 'P':
daysToShip = 7;
break;
}
return daysToShip;
}
public static void main(String[] args)
{
int year = 1900;
System.out.println("Year: " + year +
isLeapYear(year));
year = 1964;
System.out.println("Year: " + year +
isLeapYear(year));
year = 1967;
System.out.println("Year: " + year +
isLeapYear(year));
year = 1984;
System.out.println("Year: " + year +
isLeapYear(year));
year = 1996;
System.out.println("Year: " + year +
isLeapYear(year));
year = 1997;
System.out.println("Year: " + year +
isLeapYear(year));
year = 2000;
System.out.println("Year: " + year +
Util.java (continued)
isLeapYear(year));
year = 2001;
System.out.println("Year: " + year + " leap year? " +
isLeapYear(year));
int day = 27;
int month = 1;
year = 2002;
int daysInMonth = lastDayInMonth(month, year);
System.out.println("Date is: " + day + "/" + month + "/" + year
+
" (and has " + daysInMonth + " days in the
month)");
day = 20;
month = 2;
year = 2000;
daysInMonth = lastDayInMonth(month, year);
System.out.println("Date is: " + day + "/" + month + "/" + year
+
" (and has " + daysInMonth + " days in the
month)");
/*
** Remove comments to test with month 13.
**
month = 13;
daysInMonth = lastDayInMonth(month, year);
System.out.println("Date is: " + day + "/" + month + "/" + year
+
" (and has " + daysInMonth + " days in the
month)");
*/
int daysToShip = getDaysToShip('A');
System.out.println("It takes " + daysToShip + " days to ship to
Americas");
day = 27;
month = 1;
year = 2002;
daysInMonth = lastDayInMonth(month, year);
Util.java (continued)
**
/*
Solution to 4b.
for (int aDay = day; aDay <= daysInMonth; aDay++)
{
System.out.println(aDay + "/" + month + "/" + year);
}
*/
day = 10;
month = 2;
/*
**
*/
for (int aDay = day, j = 0; aDay <= daysInMonth && j <
daysToShip; aDay++, j++)
{
System.out.println(aDay + "/" + month + "/" + year);
}
}
public static String toMoney(double amount)
{
DecimalFormat df = new DecimalFormat("$##,###.00");
return df.format(amount);
}
public static String toDateString(Date d)
{
SimpleDateFormat df = new SimpleDateFormat("dd-MMMM-yyyy");
return df.format(d);
}
public static Date getDate(int day, int month, int year)
{
GregorianCalendar gc = new GregorianCalendar(year, --month,
day);
return gc.getTime();
}
public static String getClassName(Object o)
{
String className = o.getClass().getName();
return className.substring(className.lastIndexOf('.')+1,
className.length());
}
}
Oracle10g: Java Programming C-41
OrderEntryWS.jnlp
<?xml version = '1.0' encoding = 'windows-1252'?>
<jnlp spec="1.0+" codebase="http://localhost:8888"
href="/OrderEntryWorkspaceLesWS-Project1-contextroot/OrderEntryWS.jnlp">
<information>
<title>Order Entry WebStart Application</title>
<vendor>Curriculum Development</vendor>
<homepage href="OrderEntryWS.html"/>
<description>Oracel Java Programming
course</description>
<offline-allowed/>
</information>
<resources>
<j2se version="1.4+"/>
<jar href="/OrderEntryWorkspaceLesWS-Project1-contextroot/apps/archive1.jar" main="true" download="eager"/>
</resources>
<application-desc main-class="oe.OrderEntry"/>
</jnlp>
OrderEntryWS.html
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html;
charset=windows-1252"></META>
<TITLE>Title</TITLE>
<SCRIPT LANGUAGE="Javascript">
var javawsInstalled = 0;
isIE = "false";
if (navigator.mimeTypes && navigator.mimeTypes.length)
{
x = navigator.mimeTypes['application/x-java-jnlp-file'];
if (x) javawsInstalled = 1;
}
else
{
isIE = "true";
}
function insertLink(url, name)
{
if (javawsInstalled)
{
document.write("<a href=" + url + ">" + name +
"</a>");
}
else
{
document.write("Need to install Java Web Start");
}
}
</SCRIPT>
<SCRIPT LANGUAGE="VBScript">
on error resume next
If isIE = "true" Then
If Not(IsObject(CreateObject("JavaWebStart.IsInstalled")))
Then
javawsInstalled = 0
Else
javawsInstalled = 1
End If
OrderEntryWS.html (continued)
If Not(IsObject(CreateObject("JavaWebStart.isInstalled.2")))
Then
javaws12Installed = 0
Else
javaws12Installed = 1
End If
If
Not(IsObject(CreateObject("JavaWebStart.isInstalled.1.4.2.0"))
) Then
javaws142Installed = 0
Else
javaws142Installed = 1
End If
End If
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="Javascript">
insertLink("OrderEntryWS.jnlp", "Click here to start your Web
Start Application")
</SCRIPT>
</BODY>
</HTML>
Web.xml
<?xml version = '1.0' encoding = 'windows-1252'?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<description>Empty web.xml file for Web
Application</description>
<session-config>
<session-timeout>35</session-timeout>
</session-config>
<mime-mapping>
<extension>html</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>txt</extension>
<mime-type>text/plain</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jnlp</extension>
<mime-type>application/x-java-jnlp-file</mime-type>
</mime-mapping>
</web-app>