Sie sind auf Seite 1von 541

1

Introduction To

Java SE 7
Programming
(Series 1 – with Java EE Application JumpStart)

Copernicus P. Pepito

Available at Nationwide!
2

Dedication
This book is excitedly dedicated to
Queenie lyn Lenterna Tautjo for making me young again!
3

Acknowledgement

I would like to express my heartfelt gratitude to Ms. Letty Custodio and Ms.
Mildred Villapando of National Bookstore - Purchasing Department whose tandem
made this book possible.
I am very thankful also to Madam Zeny Alulod of Cacho Hermanos Publishing,
for the heart-to-heart talks and to Ms. Lyn Francisco of National Bookstore – Accounting
Department whose inspiring words (based on biblical wisdom) can never be forgotten .
If there is someone who motivated me to be brave in expressing myself through
written-words, she was no other than my beloved grandmother, Dr. Roberta Pepito. Her
editing-style made me feel very confident about my English-grammar proficiency
(eventhough, I’m not good at it - honestly speaking).
Most of the time, my book was written behind an inspiration coming from a “girl-
next-door”. But in the case of Queenie lyn Lenterna Tautjo, she is a “girl-next-jungle”,
literally speaking! Well, probably this makes her unbelievable! Until now, I cannot
believed in my experience that I had to pass-through a small jungle before reaching the
house where you lived. And to think of it that you lived in a faraway place right there at
the top of the mountain, made me feel a little bit eerie. I am sure that if I say again that
you are beautiful, you won’t believe it (as you usually do). But who cares? The most
important thing is that I said what I feel. And you know what? It makes me happy.
Lastly, I give thanks to our Almighty God who unceasingly poured out a lot of
blessings to me, and whose plan to my life and the lives of my loveones I cannot
questioned, and who answered my questions about life, trials, and death through the
books written by His servants.
4

Preface to the First Edition


This book is heavily influenced by the original work done by one of the world’s
most prolific authors, Dr. Steven Holzner of Massachussets Institute of Technology
(MIT) and Cornell University. Almost all of the examples presented here are but just
great imitations of his great work. Dr. Holzner wrote more than 100 books and most of
them are best-sellers, with over a millions of copies sold, worldwide. I am indebted so
much by his brilliant mind and creativity in presenting his ideas in the most simple as
possible manner. That is why I guarantee you that this book will in one way or another
help you to learn Java programming the easier way. So buy this book now!
Joke..joke…joke only. You can actually borrow this one from your library or from your
rich classmates. But if you happen to be rich, why not? Whatever you do or decide to do,
I am very pleased to serve your needs as a student or IT professional. Remember, that all
of us need something to believe in. To believe that there is always a brighter tomorrow
when we learned a lot by acquiring more knowledge from books that are easier to
understand and with a ready to apply knowledge in the real-world situations. So good
luck to you now, buddy.

Copernicus P. Pepito
Mapua IT Center – Makati Campus
5

Preface of the Second Edition


Writing and revising a book is a challenge to me. And believed me, I love challenges.
Maybe, because challenges make us strong (and mighty too?). However, in the case of
revising a book by including the Java EE (Enterprise Edition) application is truly a
monumental challenge for me. First, it makes me nervous – if I can really do it. Second,
it is exciting because I know when I can make it – it would be one of the best
accomplishment I achieved in my writing career.
But, what is really my intention of going that far? My intention is very simple – to share
with you what I learned about how we can use Java programming language to access and
modify data in Oracle Database. We can accomplish this goal by using Java Database
Connectivity (JDBC) application. Then we have to design and develop our Java EE
application system in Oracle JDeveloper - an integrated development environment (IDE).
That’s it! No more. No less.

Copernicus P. Pepito
Member, PSITE-NCR
Makati, Metro Manila
6

About the Author


Copernicus P. Pepito is formerly an Assistant Professor of AMA Computer University –
Quezon City Campus for 11 years and once a Training Consultant of Mapua IT Center –
Makati Campus. He holds 4 degrees: Bachelor of Science in Computer Science (BSCS),
Bachelor of Science in Computer Engineering (BSCoE), Master of Science in Computer
Science (MSCS), and Master in Business Administration (MBA). Professor Pepito earned
7 international certifications in Information Technology: Cisco Certified Network
Associate (CCNA), Cisco Certified Academy Instructor (CCAI), Microsoft Certified
Professional (MCP), Microsoft Certified Systems Administrator (MCSA), Microsoft
Certified Database Administrator (MCDBA), Microsoft Certified Solution Developer
(MCSD), and Microsoft Certified Systems Engineer (MCSE). He is an author of 14
computer books, all of which are published by National Bookstore.
7

Table of Contents

Chapte 1 Introduction
1

All Examples Will Run In Older Versions 1


Knowing More About My Other Written Books 1
Applet With Application Equivalent 2
Java Classes, Objects, and Methods Explained 2
Let Us Talk Overloading, Inheritance And Overriding 2
The new Operator, Constructor, and Destructor 3
How to Run the Java Program 4
Making a Batch File in MS-DOS 4
The Three Files Are Needed 5
Dissecting the HTML Script 7
The Arithmetic, Relational, and Logical Operators 9
The Simple If-Else Conditional Statement 10

Chapter 2 Command Button and Text Field 11

Example 1: An applet with a message string 11


Example 2: An applet with a text field 15
Example 3: An applet with Text field and Command button 19
Example 4: An applet with two Command buttons 24
Example 5: An applet with a Text area and Command button 28
Example 6: An applet with a text string entered and displayed both at the text
box and on applet 33
Example 7: An applet with a text string entered and displayed with increased
font size 36
Example 8: An applet with a text string entered and displayed after pressing
the Enter key 40
Example 9: An applet with a text string entered and displayed with font size
increased 44
Lab Activity Test 1 48

Chapter 3 Using Check Boxes and Option Buttons 51

Example 1: An applet with Check boxes and one Text field 51


Example 2: An applet with 3 Check boxes and 3 Text fields 56
Example 3: An applet with Text field at the top of the Check boxes 61
Example 4: An applet with Check boxes and Text fields in alternate position 65
Example 5: An applet with Check boxes and Text field in the same line 70
Example 6: An applet with Option buttons and Text field 75
Example 7: An applet with Text field and Option buttons 80
Example 8: An applet with 3 Option buttons and 3 Text fields 84
8

Example 9: An applet with Option buttons and Text fields in the same line 89
Example 10: Applet with Option buttons and Text fields in alternate order 95
Example 11: An applet with Option buttons, Check boxes and Text fields 100
Lab Activity Test 2 106

Chapter 4 Using Controls with Input/Output Functions 113

The ParseInt( ) and valueOf( ) Methods 113


Label Control 114
Basic Data Types of Java 114
Example 1: An applet that adds two numbers 116
Example 2: An applet that computes the area of a circle 120
Example 3: Applet that computes the average 125
Example 4: An applet that converts Celsius to Fahrenheit 130
Lab Activity Test 3 135

Chapter 5 Arranging and Organizing Controls 141

The GridLayout Manager 141


Example 1: Applet that multiplies two input numbers using GridLayout 142
Example 2: Applet that multiplies two input numbers using GridLayout Part 2 148
Example 3: An applet that converts Celsius to Fahrenheit using GridLayout 153
The Panel Class 159
Example 4: An applet with check boxes panels 159
Example 5: An applet with option buttons panels 162
Lab Activity Test 4 166

Chapter 6 Using Controls with Conditional Statements 171

if-else if Syntax 171


switch/case Syntax 172
Example 1: An applet that determines a magic number 173
Example 2: An applet that determines if a number is positive or negative 178
Example 3: An applet that displays a high school level 184
Example 4: An applet that converts a grade into a letter form 195
Example 5: An applet that determines if a number is positive or negative
without a button 207
Example 6: An applet that converts a grade into a letter form without a button 211
Example 7: An applet for Simple Burger Assessment program 217
Example 8: An applet for Simple Pizza Assessment program 224
Lab Activity Test 5 233

Chapter 7 Using Controls with Looping Statements 240

Incrementation, Decrementation, and Accumulator Formulas 241


Example 1: An applet that generates sequence numbers in vertical format 243
9

Example 2: An applet that generates sequence numbers in horizontal format 251


Example 3: An applet that generates an inverse sequence numbers 259
Example 4: Applet that generates an inverse sequence numbers horizontally 262
Example 5: An applet that generates sequence numbers incremented by 5 265
Example 6: An applet that generates sequence numbers decremented by 5 268
Example 7: An applet that generates an @ symbol 271
Some Famous Mathematical Programs 282
Example 8: An applet that calculates the factorial value 283
Example 9: An applet that calculates the power value 288
Using Scrolling List (List Box) Controls 293
Example 10: An applet that uses Scrolling list with preloaded items 294
Example 11: An applet that uses Scrolling list and Text field 297
Example 12: An applet that uses Scrolling list with Remove item capability 301
Example 13: An applet that uses Scrolling list with Remove command button 304
Example 14: An applet that uses Scrolling list with add item capability 309
Example15: An applet with two Scrolling lists 312
Example 16: An applet with two Scrolling lists with transfer of item capability 316
Example 17: An applet that can add, delete, or wipe out the items 320
Example 18: An applet that can copy an item from one scrolling list to another 326
Using Choice Control 331
Example 19: Applet that displays the selected item from the Choice control
to the text field 331
Example 20: An applet that displays the selected item from the Choice control to the
Scrolling list 335
Example 21: An applet that displays the selected item from the Scrolling list using the
GetParameter 339
Lab Activity Test 6 343

Chapter 8 Other Java Controls 353

Using Scroll bars 353


Example 1: An applet with a horizontal scroll bar 354
Example 2: An applet with a vertical scroll bar 357
Example 3: An applet with a scroll pane 360
Using the GridBagLayout Manager 362
Example 4: An applet with a GridBagLayout manager application 363
Lab Activity Test 7 368

Chapter 9 Designing Window and Simple Menu 371

Example 1: An applet with a window control 371


Example 2: An applet with a popup menu 375
Lab Activity Test 8 381

Chapter 10 Introduction to Java Enterprise Edition Application 409

Java Database Connectivity (JDBC) Explained 409


10

Connecting Java to Database 409


Software Requirements 410
So, What is Oracle JDeveloper? 411
The Graphical-User Interface of JDeveloper 411
About Oracle Database Server 413
What is a Web Server? 415
Connecting to Oracle Database 415
How to Create Database Connection? 415

Chapter 11 Learning JDBC Programming 418

Classes for Personnel System 418


Creating Database Tables and Primary Key Sequence 419
Managing Primary Key Sequences 421
Inputting Data into Database Tables 421
Creating the Java EE Application 423
Creating a Class in Java 425
Using Java Libraries 426
The Oracle JDBC Library Explained 427
The JSP Runtime Library Explained 427
Adding JDBC and JSP Libraries 427
Importing JDBC Packages and Creating Connection Method 429
Creating A Method For Querying Data 431
Creating TestClient Class 433
Creating the JSP Pages 435
Adding a JSP useBean Tag 436
Adding a Table Control into the JSP 439
Creating Methods for Search Filtering 439
How ResultSet Works? 443
Adding Filter Controls to the JSP Page 443
Displaying Filtered Data in the JSP Page 444
Creating a Method to Authenticate Users 444
Creating a Login Page 447
Preparing an Error Message for Failed Logins 447
Creating the Login Interface 450
Creating a JSP Web Page to Handle Login Action 451
Testing our JSP Web Page 453

Chapter 12 Updating Data in Java EE Application 464

Creating a JavaBean 464


Updating Data from Java Class 465
Creating a Method to Identify a Worker Record 466
Creating a Method to Update Worker Data 468
Adding a Link to Navigate to an Update Webpage 472
Creating a JSP Web Page to Change Worker Data 474
11

Creating a JSP Web Page to Handle a Change Action 476


Updating Data from Java Class 479
Creating a Method to Add Data 479
Adding a Link to Navigate to an Add Web Page 480
Creating a JSP Web Page to Input New Data 481
Creating a JSP Web Page to Handle an Add Action 484
Erasing a Worker Record 487
Creating a Method for Erasing Data 487
Creating a JSP Web Page to Handle an Erase Action 488
Exception Handling Explained 492
Creating a Method for Handling Any SQLException 492
Navigation in Java EE Application 493
Creating a Starting Web Page for Java EE Application 494

Chapter 13 Advanced JDBC Features 499

Applying Dynamic SQL 499


OraclePrepared Statement Explained 500
OracleCallableStatement Explained 501
Bind Variables Explained 501
Calling Stored Procedures Explained 501
Creating a PL/SQL Stored Procedure in JDeveloper 503
Creating a Method to Use the Stored Procedure 504
Allowing Users to Choose the Stored Procedures 506
Calling the Stored Procedure from the Java EE Application 507
Using Cursor Variables 512
Type Category of Oracle REF CURSOR 512
Accessing REF CURSOR Data 513
Creating a Package in the Database 514
Creating a Database Function 515
Calling a REF CURSOR from Java Method 516
Displaying a Dynamically Generated List 517
MINI-CASE STUDY 520
12

Chapter 1
Introduction

All Examples Will Run In Older Versions


( Such as: Java 1.3 or 1.4, 1.5 , and 1.6)

Originally, the main reference of this book is based on the book written by Dr.
Steven Holzner (Ph.D. in Computer Science) of the Massachussets Institute of
Technology (MIT) and Cornell University, which title is Java 2.0 in Record Time. Java
2.0 is technically has a Java version of 1.2. This means that all the examples of this book
are backward compatible with the older Java Software Development Kit (SDK) versions.
So, whatever Java compiler you used presently is enough to run all the examples in this
book without any compatibility problem. So be rest assured that all things will work out
right.

Applet With Application Equivalent


Java is an object-oriented programming language, designed by Dr. James Gosling
of Sun Microsystems in early 1990’s. By using Java, we can make Web pages interactive
and alive. We can display command buttons, text fields, check boxes, option buttons,
scrolling list, choice controls, and other controls that process the web surfer’s input and
output data.
In this book, we will focus more on the Graphical-User Interface (GUI)
programming, meaning, we will deal with graphics or objects in our program. We will
learn also the programming based on working examples with explanations on how they
work.
Java programs come in two ways. The first one is a stand-alone application and
the second one is an applet - a small program we can embed in Web pages. Since the
applet is the most popular and widely used, we will concentrate on its implementation. To
explain it further, an applet is a special program that we can embed in a Web page such
that it gains control over a certain part of the Web page. On that part of the page, the
applet can display command buttons, text boxes, scrolling list, choice control, images,
and more. With this applet, the Web page becomes “alive”. Each applet in the Web page
is given the amount of space, usually measured in pixels. This is the space that the applet
will use when it displays itself at the Web page.
This book also features how we can convert an applet into application in a way
that is so easy and fast. It’s unbelievable isn’t it? But it’s all true. Since we concentrate
more on applet than application, only two chapters contain an application, though no
supporting detailed explanation for each converted code or solution. Why? I believe that
in order to learn the Java application programming effectively and efficiently, we need to
study it as a separate special topic, due to its large coverage.
13

Figure 1.1 The Java Application Platform SDK Installation Wizard

Figure 1.2 The Java Runtime Environment Setup

Java Classes, Objects and Methods Explained


The classes and objects are two fundamental concepts in Object-Oriented
Programming (OOP) language like Java. A class is defined as a blueprint or schematic
diagram of an object. It is a programming construct that groups together the function and
data. This process is called encapsulation. The objects are encapsulated, meaning, they
contain both their code and their data, making them more easier to maintain. The Java
objects have properties, methods and events. We can manipulate an object through their
properties, events, and methods. Each object recognizes and can respond to certain
actions called events. An event is a specific and predetermined activity, activated by
either a user or the system. Events, in most cases, are generated by user-interaction. In
14

Java, user actions that trigger events include mouse clicks, mouse moves, and key-
presses.
Methods are functions that are members of the class. They are also procedures
associated with an object. Events can have methods associated with them. For example, if
we write a method code for the Click event, that code is executed when the Click event
occurs. All of the properties, events, and methods for an object are specified in the class
definition.
Properties can be considered as an object’s attributes, methods as its actions, and events
as its responses. For example, a command button’s attributes are its caption, color, and
size. An object such as a command button can perform methods and respond to events.
This event can be a click by the mouse or a key-press from the keyboard. The performed
method could be to show a window object or hide it instead. In summary, properties are
data that describe an object; methods are things we can tell the object what to do; and
events are things the object does.
The most important to remember about Object-Oriented Programming (OOP) is that the
object itself is what holds the data we want to work with, while the class itself holds no
data, but just describes how the object should be setup.

Let Us Talk Overloading, Inheritance And Overriding

In function overloading, you can assign a name to your two or more methods with
the same function name, provided it has different data types to receive in passing
parameters or different number of parameters listed.
Inheritance is one of the most important concepts of Object-Oriented
Programming (OOP). In inheritance, a derived class inherits the functionality, features,
and capabilities of its base class, plus you can extend its unique or advance capabilities.
This further means that our derived class can use the methods declared at the base class,
then it can also construct its own method which is unique or advance from the base class.
Remember that if the methods found in our base class have the same name with our
methods in the derived class, this is still okay even if they are exactly the same; meaning
the same data type, the same number of parameters. This technique is called overriding,
which is one of the most important techniques in inheritance. The difference between
overloading and overriding is that in overriding we connect the function or method name
to the new derived class. This connection or relation of the two is used by the compiler on
which to call. Meaning, the compiler prioritizes to search first all the methods within the
derived class before it goes to the base class’s methods. Therefore, even if they have
similar names and similar parameters, there is no conflict, because of this prioritization of
method to search and execute. This means also that the methods declared at the derived
class overrides the methods declared at the base class. This is in the case where they have
both the same method names. To discuss shortly the difference between an overloading
from overriding is that in overloading - a function can be called with different parameter
lists, while overriding means a function redefines the version of the function that appears
in the class’s base class.
15

The new Operator, Constructor and Destructor

The Java programming language new operator works like the C++ programming
language new operator. Its purspose is to allocate memory space for objects, arrays, or
variables. A constructor is a special method that is automatically run when we create an
object of a particular class. It is used to initialize objects. Since a constructor is a method,
we can pass data to a constructor. A constructor has the same name with its respective
class. The destructor is just an opposite to the constructor. It destroys an object’s
initialization after it is being used.

How to Run the Java Program

You need a word processor such as Microsoft NotePad to type your Java program
and save as a file for you to compile and run it. Next, you’ll need to install the Java
Development Kit (JDK) 1.7 (or later version) in your computer. You can get a free copy
of this JDK from this website: http://www.sun.com. Just download it and follow the
instructions for proper installation.

Making a Batch File in MS-DOS

We need to create a batch file in the MS-DOS (Disk Operating System) mode to
automate the compilation of our Java programs. We can do this by typing the word cmd
right at the Run menu item of the Start menu of the Windows operating system to create
this batch file. Here are the complete steps:
1. First, type the word cmd at the Run menu item of the Start menu.
2. Then, at the C:\> prompt, create a subdirectory named javaprog by typing the
following syntax:

C:\> md javaprog (then press the Enter key)

The md here means make directory.


3. Now type the command edit. This command will open the text-mode editor of
MS-DOS. Next, type the following batch file code below:
rem This is a java path configuration.
rem Activate this batch file before you create java programs.
@echo Java path is now activated!
@echo off
cls
path=c:\winnt;d:\winnt32;c:\Program
Files\Java\jdk1.7.0_01\bin;c:\Program
Files\Java\jdk1.7.0_01\lib;c:\Program Files\Java\jdk1.7.0_01\jre;
@echo off
16

4. Make sure that the entire path=c:\ should be in one line only to prevent a syntax
error in batch file processing. Because of the limitation of the space here in this book,
our path=c:\ is displayed in 4 lines of code, which will probably cause a syntax error
in jpath file batch processing.
5. Then save it with the filename called jpath.bat. The filename extension .bat
means it is a batch file. The rem is a batch file command which means “ a code
remark”, while the command echo means to display the message on the screen. The
cls stands for clear screen. And finally the path command in our batch file is to
simply instruct the computer to look for the Java compiler and its associated libraries
(which are needed in the compilation of our programs) in the listed directories.

To check if the jpath batch file is working properly, you can issue the MS-DOS
command such as the following syntax:

C:\JAVAPROG>path (then press the Enter key)

You need to see that the directory path looks like the following line:

C:\JAVAPROG>path

path=c:\winnt;d:\winnt32;c:\Program
Files\Java\jdk1.7.0_01\bin;c:\Program
Files\Java\jdk1.7.0_01\lib;c:\Program
Files\Java\jdk1.7.0_01\jre;

In case the jpath batch file will not work as it is intended, you have to manually type the
path command at the MS-DOS prompt like the following:

C:\JAVAPROG> path=c:\winnt;d:\winnt32;c:\Program
Files\Java\jdk1.7.0_01\bin;c:\Program
Files\Java\jdk1.7.0_01\lib;c:\Program Files\Java\jdk1.7.0_01\jre;

(then press the Enter key)

Then you can check again if the manual way works; by issuing the path command again
with the following syntax:
C:\JAVAPROG>path

The Three Files Are Needed


To successfully run our Java applet program, we need the three files. The first
one is the source code which filename extension is .java then the second one is the
compiled code which filename extension is .class. And the last one is the HTML (Hyper-
Text Markup Language) file which filename extension is .htm (where our applet runs).
For example, we want to write an applet that will display a simple message on the applet.
17

The message is “Hello Bianca!”. First we have to open the Microsoft NotePad and type
the following:
import java.awt.Graphics;
public class hello1 extends java.applet.Applet
{
public void paint(Graphics g)
{
g.drawString("Hello Bianca!",60,30);
}
}

Then save it with a filename: hello1.java. After saving it, we are now ready to compile
our java program. What we have to do is to execute the batch file we created to automate
the compilation of our Java programs. Here is the syntax:

C:\>cd javaprog (then press the Enter key)

The cd here means change directory.


At the javaprog directory, we have to execute the jpath batch file using the following
syntax:

C:\JAVAPROG>jpath (then press the Enter key)

You will notice the high-speed execution of our batch file in just a matter of a few
seconds.
This time we are ready to compile our Java program using the following syntax:

C:\JAVAPROG>javac hello1.java (then press the Enter key)

The javac is the filename of our Java compiler, while the hello1.java is our Java program
source code. If there are no errors encountered during the compilation process, we can
now proceed to create the HTML file for our Java program. So we have to type the
following at the Microsoft NotePad:
<html>
<!- Web page written with Java Applet>
<head>
<title>hello1</title>
</head>
<body>
<hr>
<applet
code=hello1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>
18

Then, we will save the HTML file with this filename: hello1.htm to simply correspond to
the name of our Java program which is hello1.java and to the compiled version of it
which is the hello1.class file. The hello1.class file can only be generated if our Java
program which in this case is the hello1.java is successfully compiled, that is, if there is
no error encountered during compilation.
Here in our HTML script, we specify that the name of the compiled code of our Java
program is hello1.class as we can see on the script above and its corresponding width and
height is 200. This is the size of our applet.
Now to finally see it in action, we have to type the following syntax at the web browser:
C:\javaprog\hello1.htm

Or alternatively, we can directly type it at the Command Prompt (DOS Prompt or


Console) like this one:
C:\javaprog>hello1.htm

Note:
You need to type only the hello1.htm , because the C:\javaprog> is an operating system directory (o.s.
prompt) that is already generated for you.

Note:
Because of the security implemented in the web browser such as Internet Explorer (IE) or the Mozilla
FireFox, we need to (allow) Allow the Blocked Content warning message, to successfully run or test our
applet.

Or, our third alternative is to use the Java Appletviewer to run and test your Java applet
by issuing this command:
C:\javaprog>appletviewer hello1.htm

Note:
You need to type only the appletviewer hello1.htm , because the C:\javaprog> is an operating system
directory (o.s. prompt) that is already generated for you.

And presto, the running applet is now displayed!

Dissecting The HTML Script


This time, let us dissect the HTML script above. Remember, that every time we
program an applet in Java, we need to come up with similar HTML script above to be
able to connect our Java program to the HTML script in order to produce the applet we
needed.
Let us start with the <html> tag:
<html> tag
19

<!- Written for IE Web browser comment


<head>
<title>hello1</title>
</head>
.
.
.

Instructions in HTML pages are placed into tags surrounded by angle brackets: <and>.
The tags hold directions to the Internet Web browser and are not displayed on the screen.
Here, the <html> tag indicates to the Internet Web browse that this .html file is written in
HTML.
We write here a comment using the ! (exclamation) symbol. Next comes the header
portion of the Web page, which we declare with the <head> tag, ending the header
section with corresponding end header tag, </head>. In this case, the .html file gets the
title set up tag hello1, to match our applet. The title is the name given to a Web page, and
it is usually displayed in the Internet Web browser’s title bar.

<html>
<!- Web page written with Java Applet>
<head>
<title>hello1</title>
</head>
<body>
<hr> ruler line
<applet
code=hello1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

Finally we come to the body of the Web page. Here is where all the actual items
for display will go. We start the page off with a ruler line using the <hr> tag.
Now we come to the applet portion. Applets are embedded with the <applet> tag, and
here we use the code keyword to indicate that this applet is supported by the hello1.class
file. We indicate also the applet size as 200 x 200 pixels (200 wide and 200 high in
pixel). We indicate to the Internet Web browser here how much space we will need (or to
occupy in a web page) for our applet using the width and height keywords.
By using the <applet> tag, we can embed applets in the Internet Web pages.

The Arithmetic, Relational, and Logical Operators

We usually use the arithmetic operators in our equation or formula for calculation
purposes, while the relational operators are used in evaluating a particular conditional
expression or expressions in a program whether it is true or false. Based on the result of
the evaluation, the computer will decide what to do or to execute. Logical operators are
20

applied to evaluate two or more conditional expressions, and determine if they are true or
false, true or true, false and false or true and true and other possibilities. In other words,
the logical operators will evaluate a group of complex conditional expressions, and based
its action on the final outcome of the evaluation. With this final outcome, the computer
will decide how to perform the program code. Here are now its symbols and command
syntax used.

Arithmetic Operators

+ Addition
_ Subtraction
* Multiplication
/ Division
^ Exponentiation

Relational Operators

< Less than


> Greater than
<= Less than or Equal to
>= Greater than or Equal to
== Equal to
!= Not Equal to

Logical Operators

Operators Rules

&& (and) If both or all expressions are evaluated to True, then the result is True.

|| (or) When either or any (or just one) of the expressions is True, the result is
True.

! (not) If the expression is True, then the result is the opposite of the expression.

The Simple If-Else Conditional Statement

The simple if-else conditional statement allows the computer to choose one and
only one of the given two alternatives. Its general syntax is:

if condition {
Statement1;
<other Statement(s)>
}
else {
Statement2;
21

<other Statement(s)>
}

If the condition is evaluated to True, then Statement1 (and together with other
statement(s) that follow ) is executed, otherwise Statement2 (and together with other
statement(s) that follow) is executed instead. In other words, this if-else conditional
statement says, “if the condition is true, then execute its associated statements, otherwise
skip this code”.

Java Application Program


Although in this book, we focus in Java applet programming, I offer you a
glimpse on how to write Java application based on graphical-user-interface (GUI) design
and development which is very very similar to the Java applet implementation.
Unbelievable??? Isn’t it! But this is true. This is a demonstration to you in an actual basis,
that if you learn how to program Java in applet, you can easily convert it to a Java
application program. You just simply follow the rules of its syntax implementation.
Actually, I haven’t present any detailed discussion to this Java application program,
because I believe that an exhaustive treatment to this very wide topic of Java application
can consume another book. That is why, the second volume (Volume 2) of this book is all
about a GUI-based Java Application programming in action. No more, no less.
Now to easily convert a Java applet program to Java application program, you
have to use the following suggested Java application template:

// This is just a Java Application program template for you to easily convert your applet
// progam right within this template, using copy and paste.

import java.awt.*;
import java.awt.event.*;
public class aHello1 extends Frame {
Label lblHello = new Label("Hello Bianca!");
public aHello1() {
super("Label Example");
setLayout(new FlowLayout());
add(lblHello);
setSize(200,200);
setVisible(true);
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aHello1


22

public static void main (String [] args) {


aHello1 LabelApp = new aHello1();
}
} // End of public class aHello1

Now, you have to simply analyze the differences of syntax implementation of Java
applet program against Java application program. Like for example, in Java applet, we
use the

public class button1 extends Applet implements ActionListener {

at the top of our program, while in Java application program, we use the following syntax
implementation:

public class aButton2 extends Frame implements ActionListener{

If you analyze these two codes, they are almost hundred percent similar. You know how
they differ from each other? They differ only by one word! In Java applet, we use the
word Applet, while in Java application, we use the word Frame. Well, with the exception
of the name of the class which is a requirement that they should be different, so that class
name should be unique to each other. Otherwise, an old class with the same name of a
new class can be overwritten by the new one (when you save them as a filename in the
OS directory or Folder).
Now what is the other noticeable syntax that we can find in Java Application program
that are different from Java applet program? Here they are:

addWindowListener(new WindowAdapter() { public void


windowClosing(WindowEvent e) {
System.exit(0);
.
.
.
public static void main (String [] args) {
aHello1 LabelApp = new aHello1();

We need the addWindowListener method so that when the user closes the window (or
the user clicks the close icon usually expressed with big red X), we can shutdown the
Java application program.
Now how about the public static void main ( )? This is a special method in Java
application program which served as the entry point that the Java Runtime Environment
(JRE) processes when it starts. This is just like telling the JRE to open the class file
aHello1.class and process the main( ) method .
Let us dissect more the Java application program to know the other details such as the
following code below:
23

.
.
.
Label lblHello = new Label("Hello Bianca!");
public aHello1( ) {
super("Label Example");
setLayout(new FlowLayout());
add(lblHello);
setSize(200,200);
setVisible(true);
.
.
.
The Label lblHello here simply create a new object of type Label. The creation and
initialization of a new class can come in one step or in two lines of sytax such as the
following:

Label lblHello = new Label( “Hello Bianca!”);

Or

Label lblHello;
lblHello = new Label(“Hello Bianca!” );

The public aHello( ) here defines the constructor for the Label class. It is declared public
and has the same name as the class itself, and returns no value. Since this constructor
does not accept parameters (listed usually inside the parentheses), it is the default
constructor for the Label class. The super keyword used in a subclass calls the original
method of the superclass. By using the super keyword in the constructor of the Label
class, we are asking the compiler to call the constructor of the Frame class and pass it the
string “Label Example”.
The Frame class method called setLayout( ) here in our Java application program creates
a new FlowLayout class object.
The add(lblHello) code here created a label to the window by calling the Frame class’s
add method. The add method can be found under the Container of the Frame’s extended
class (Frames extends Window syntax).
The setSize method resizes the window to the specified dimension which in our example
is set to 200,200 which means 200 pixels by 200 pixels. This size we set is large enough
for us to see the label we want to display.
Lastly, the setVisible method is set to true so that we can see the Frame . By default, the
Frame class is set to false, which means it is hidden.
I think, we had dissected the Java application program in its entirety. Now this is very
important, just because what you learned here in this discussion will not be repeated in
the succeeding Java application program solution ahead which we name as Solution 2.
Meaning, there is no Explanation whatsoever for the Java Application program Solution.
24

The Difference Between Applet and Application


Maybe you are so curious enough to know the difference between the two types
of basic Java programs. Or maybe, you just want to know what they are capable of doing.
Let us start discussing first the Applet capabilities. The applet can run in the context of a
Web browser (such as Internet Explorer or Mozilla FireFox), making them accessible
from anywhere in the world through the Internet. Moreover, the integration of the applet
with the Web browser allows it to take a certain amount of control and provide a truly
powerful front-end and navigator for our website. Inspite of these immense power of
applet, it has its own limitations or drawbacks, not in terms of technical aspect but of a
system security. Because of applet’s public accessibility in the context of a web page,
certain limitations are imposed on it. As a defense against potential malicious applets that
may perform such actions as harming or retrieving files or confidential information from
the user’s computer, Java has defined some strict system security restrictions on applets.
Like for example, an applet cannot read or write files from or to a user’s PC or laptop. An
applet cannot communicate with any web site other than the ones they are running on,
and cannot launch any programs on the user’s computer.
Now how about the Java application program? What it is capable of doing about? The
Java application program is not bound by the system security issues that are enforced
against the applet. In short, the Java application program has all the complete control
with the user’s PC or laptop. Like for example, your Java application program can read
and write files on your PC or laptop, it can launch other application programs, and it can
do anything on a computer that it has priveleges to do. The limitation of Java application
program is that it cannot be embedded to a web page so that it can be run by a browser on
the Internet.
I think we are ready now for a serious programming task. So let us now begin at
once, amigo!
25

Chapter 2
Using Command Button and Text Field

The command button control is used to begin, interrupt or end a process. When clicked, it
invokes a command that has been written into its Click event method. Most Java
applications have command buttons that allow the user to simply click them to perform
actions. When the user clicks the button, it is not only carries out the appropriate action, it
looks also like as if it’s being pushed in and released and is therefore sometimes referred
to as push button.
The text field control is used to display information entered by the user or assigned to the
Text property of the control at design time. Without further ado, let us now have our first
example.
Before jumping right away with command button and text field program development, let
us try to run the example above which simply display a message in our applet.

Example 1:

Design and develop a Java applet that will display the message, “Hello Bianca!” on the
applet. Follow the design specification below:

Hello Bianca!

Figure 1.1 An applet with a message string

Solution 1: Using Applet

1. At the Microsoft NotePad, write the following code:

import java.awt.Graphics;
public class hello1 extends java.applet.Applet
{
public void paint(Graphics g)
{
g.drawString("Hello Bianca!",60,30);
}
}

2. Then save the Java applet with the filename: hello1.java.


26

3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:

<html>
<!- Web page written with Java Applet>
<head>
<title>hello1</title>
</head>
<body>
<hr>
<applet
code=hello1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: hello1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac hello1.java (then press the Enter key)

7.When no error is encountered during the compilation process, you can now type the
following at your Web browser:
C:\javaprog\hello1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>hello1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer hello1.htm (then press the Enter key)


27

Sample Output:

Figure 1.1a An applet with a message string output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.awt.event.*;
public class aHello1 extends Frame {
Label lblHello = new Label("Hello Bianca!");
public aHello1() {
super("Label Example");
setLayout(new FlowLayout());
add(lblHello);
setSize(300,60);
setVisible(true);
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

}
public static void main (String [] args) {
aHello1 LabelApp = new aHello1();
}
}
28

2. Then save the Java applet with the filename: aHello1.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aHello1.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aHello1 (then press the Enter key)

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>hello1.htm (then press the Enter key)

Sample Output:

Figure 1.1b Java application program with a message string output

Solution 3: Using Console-Based Application

1. At the Microsoft NotePad, write the following code:


public class cHello1 {
public static void main( String [] args ) {
System.out.println("Hello Bianca!");
}
}

2. Then save the Java applet with the filename: cHello1.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


29

C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac cHello1.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java cHello1 (then press the Enter key)

Sample Output:

Figure 1.1b Java Console Application with a message string output

Explanation:

import java.awt.Graphics;
public class hello1 extends java.applet.Applet
{
.
.
.
The import java.awt.Graphics means that we want to include the Java Graphics class and
make use of it in our program. Furthermore, we have added support for graphics-handling
by including the java.awt.Graphics class. In Java programming language, displaying the
text string “Hello Bianca!” is considered a graphics handling.
Next, it is time to set up our hello1 applet itself. To accomplish it, we have to define a
new class named hello1. This is the standard way of setting up applet in Java
programming. The Java applet has the filename extension .class. It is because each class
defined in a .java file ends up being exported to a .class file (after compilation), where
we can make use of it.
We can customize the java.applet.Applet class by deriving the hello1 class from the
java.applet.Applet class. This makes java.applet.Applet the base class of the hello1 class,
and it makes hello1 a class derived from java.applet.Applet. This gives us all the power
of the Java.applet.Applet . This technique is called inheritance in Object-Oriented
30

Programming (OOP) paradigm. In inheritance, a derived class inherits the functionality


of its base class and adds more on top of it. For example, we may have a base class
called, say, vehicle. We can derive various classes from this base class called, say, bus,
motorcycle, or truck. In this way, three derived classes can share the same base class,
saving time and effort programmatically. Although the bus, motorcycle, and truck classes
share the same base class, vehicle, they added different items to the base class, ending up
as three quite different classes, bus, motorcycle, and truck. In using inheritance, we can
extend the base class java.applet.Applet by creating our own class hello1 and adding onto
the base class.
The keyword class indicates that we are defining a new class in our code.

public void paint(Graphics g)


{
g.drawString("Hello Bianca!",60,30);
}
} (x,y)

One of the functions in the java.applet.Applet class is paint( ). This function is called
when the Web browser tells the applet to create its display on the screen. This happens
when the applet first begins and every time it has to be re-displayed later. Like for
example, if the Web browser was minimized and then maximized, or if some window
was moved and the applet’s display area was uncovered after having been covered.
Our goal in the hello1 class is to display the text string “Hello Bianca!” on the screen.
To accomplish this goal, we have to override the java.applet.Applet class’s paint( )
function. This built-in paint( ) function of a class is called method in OOP term. A
method is simply a function that is a member of the class.
Take note that we indicate that the paint( ) method is automatically passed one parameter
- an object of the Graphics class called g. This Graphics object represents the physical
display of the applet. This further means that we can use the built-in methods of this
object such as drawLine( ), drawImage( ), drawOval( ), drawString( ) and others, to draw
on the screen. In our case, we want to place the string “Hello Bianca!” on the screen. To
accomplish this task, we apply the drawString( ) method. The question is “How can we
reach the methods of an object like the Graphics object named g? We can accomplish that
with a dot operator (.) like this syntax:

g.drawString( )

where here we are invoking g’s drawString( ) method to draw a string of text on the
screen. We supply the three parameters to the drawString ( ) method - first is the string of
text we want to display, then the (x,y) location of that string in our applet which is
measured in pixel. The coordinate system in Java program is set up with the origin (0,0)
at the upper-left, with x increasing horizontally to the right, and y increasing vertically
downwards. The Java programming convention is like in C and C++ where a semicolon (
; ) indicates the end of a program statement.
At last, we have completed the code necessary for this applet, which in turn generated the
new class - hello1. When the Java compiler creates hello1.class, the entire specification
of the new class will be in that file. This is the actual binary file that we upload to the
31

Internet Service Provider (ISP) so that it will be included in our Web page. A Java-
enabled Web browser such as Internet Explorer (IE) or Netscape Navigator takes this
Java class specification and creates an object of that class and then gives it control to
display itself, and in some cases, handles user’s input and output tasks.

Note:
Since, our focus in this Volume 1 is on Java applet programming, you cannot find here a detailed per
example Explanation part for Java application program. As I have promised, I will release the Volume 2
of this book as a GUI-based Java Application program focused presentation. So, just wait. For he who
waits patiently wins the game of life. They call it, high EQ (Emotional Quotient). So, be a high EQ
yourself. I know that you can do it!

Example 2:

Design and develop a Java applet that will display the message, “You are welcome
Bianca!” at the text field on the applet. Follow the design specification below:

Text field
You are welcome Bianca!

Figure 1.2 An applet with a text field

Solution 1: Using Applet

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
public class text1 extends java.applet.Applet
{
TextField txtText1;
public void init()
{
txtText1 = new TextField(20);
add(txtText1);
txtText1.setText("You are welcome Bianca!");
}
}

2. Then save the Java applet with the filename: text1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
32

<html>
<!- Web page written with Java Applet>
<head>
<title>text1</title>
</head>
<body>
<hr>
<applet
code=text1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: text1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac text1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\text1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>hello1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer hello1.htm (then press the Enter key)

Sample Output:
33

Figure 1.2a An applet with a text field output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:

import java.awt.*;
import java.awt.event.*;
public class aText1 extends Frame {
TextField txtText1;
public aText1() {
super("Text Box Example");
setLayout(new FlowLayout());
txtText1 = new TextField(20);
add(txtText1);
txtText1.setText("You are welcome Bianca!");
setSize(200,200);
setVisible(true);
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

}
public static void main (String [] args) {
aText1 TextBoxApp = new aText1();
}
}

2. Then save the Java applet with the filename: aText1.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


34

C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aText1.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aText1 (then press the Enter key)

Sample Output:

Figure 1.2 b Java application program with a text field output

Explanation:

Here, we import all the classes in the Java AWT (Abstract Windowing Toolkit) package
by using the import java.awt.* statement declaration at the top of our program.

import java.awt.*;
public class text1 extends java.applet.Applet
{
TextField txtText1;
.
.
.
These are the classes that will let us add the command buttons and text fields to our
applet. For example, two of the classes in this package that we will use are Button and
TextField.
You will notice that we declared a new public class named text1 as our applet’s main
class, which is derived from the java.applet.Applet base class.
Next, we created the text field object txtText1 of the TextField class by using the
declaration TextField txtText1 statement.

public void init( )


{
txtText1 = new TextField(20);
add(txtText1);
35

txtText1.setText("You are welcome Bianca!");


}

When we want to initialize A program, for example, adding a text field to it, we can
accomplish that in the init( ) method. All kinds of object initialization take place at this
method. This method runs automatically when the applet starts. This is the reason why
we have to place all the code we want to run first in the init( ) method. To develop this
method, we simply construct it using the public void init ( ) statement such as the
following:

public void init( )


{
// Place all your initialization code here:
}

Remember that a method is simply a function that is a member of the class. The init( )
function (method) is like any other function or method, except that it doesn’t return a
value. This is the reason why we have the return type void in our program statement. Our
task in the init( ) function is to create the new text field and design it in our applet.
Creating controls or objects in Java programming is a two-step process. The first one is to
declare the new object and secondly, create the new object in the init( ) method using the
Java programming language’s new operator. This operator is used to allocate memory for
objects, variables, and arrays.
We make the text field a 20 characters wide, so we pass a value of 20 to the TextField
class’s constructor. The purpose of the constructor is to initialize the object we want. A
class constructor is called in our program when a new object is being created of that
class, and we can set the object up as we like it. Since a constructor is a method, we can
pass data to a constructor. In this example, we pass a value of 20 to our new text field’s
constructor.
We add the text field to the applet’s display by using the add( ) method, wherein we add
the new control txtText1 to the applet’s default layout. Finally, we will add the text string
to the text field object using the setText( ) method of the TextField class.

Note:
This // (symbol) is a program comment. Meaning, it is ignored by the Java compiler during program
compilation. Comments or comment will make our program clearer to understand and easier to debug and
maintain once we go back over it for some months that passed.

Example 3:

Design and develop a Java applet that when the user clicks the Click Me button, the
message “Click Me button clicked!” will be displayed at the text field. Follow the design
specification below:
36

Click Me button clicked! Text field

Click Me! Command button

Figure 1.3 An applet with Text field and Command button

Solution 1: Using Applet

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class button1 extends Applet implements ActionListener {
TextField txtText1;
Button cmdButton1;
public void init() {
txtText1 = new TextField(20);
add(txtText1);
cmdButton1= new Button("Click Me!");
add(cmdButton1);
cmdButton1.addActionListener(this);
}
public void actionPerformed(ActionEvent objEvent) {
String strMessage = new String ("Click Me button clicked!");
if (objEvent.getSource() == cmdButton1) {
txtText1.setText(strMessage);
}
}
}

2. Then save the Java applet with the filename: button1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>button1</title>
</head>
<body>
<hr>
<applet
code=button1.class
width=200
37

height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: button1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac button1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\button1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>button1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer button1.htm (then press the Enter key)

Sample Output:
38

Figure 1.3a An applet with Text field and Command button output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.awt.event.*;
public class aButton2 extends Frame implements ActionListener{
TextField txtText1;
Button cmdButton1;
public aButton2() {
super("Button Example");
setLayout(new FlowLayout());
txtText1 = new TextField(20);
add(txtText1);
cmdButton1= new Button("Click Me!");
add(cmdButton1);
cmdButton1.addActionListener(this);
setSize(300,60);
setVisible(true);

addWindowListener(new WindowAdapter() { public void


windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aButton2


public void actionPerformed(ActionEvent objEvent) {
String strMessage = new String ("Click Me button clicked!");
if (objEvent.getSource() == cmdButton1) {
txtText1.setText(strMessage);
}
}
public static void main (String [] args) {
aButton2 Button2App = new aButton2();
}
} // End of public class aButton2

2. Then save the Java applet with the filename: aButton2.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aButton2.java (then press the Enter key)


39

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aButton2 (then press the Enter key)

Sample Output:

Figure 1.3b Java application with Text field and Command button output

Explanation:

We import here the java.awt.event.* package that contains the ActionListener interface,
as you can see its declaration below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
.
.
.
We created the text field object txtText1 of the TextField class by using the declaration
TextField txtText1 statement and the command button object cmdButton1 of the Button
class by using the declaration Button cmdButton1 statement.
Events such as click event of the command button are passed from source controls to
listener objects. This is the reason why we connect a listener to the command button -
cmdButton1.
We can find out what events occur such as button clicks or mouse movements, using the
ActionListener interface. To use the delegation-based event model technique, we specify
that the applet will implement the ActionListener interface in our program as what you
can observe in our code.
When an event occurs, the listener object can hear it, so we will make the listener object
the applet object itself by connecting the applet to cmdButton1 as a listener. We can
accomplish that with the command button’s addActionListener( ) method, as what you
can see in our syntax implementation below:

import java.applet.Applet;
40

import java.awt.*;
import java.awt.event.*;
public class button1 extends Applet implements ActionListener {
TextField txtText1;
Button cmdButton1;
public void init( ) {
txtText1 = new TextField(20);
add(txtText1);
cmdButton1= new Button("Click Me!");
add(cmdButton1);
cmdButton1.addActionListener(this);
}

Now to indicate that we want the applet itself to be the button’s listener, we need to be
able to pass the applet itself as an argument to the addActionListener( ) method. To
accomplish that, we pass the this parameter into it. When there are command button
events (such as a click from the mouse or a key-press from the keyboard) that will
happen, they will be sent to the applet, because we have already set up the
ActionListener( ) method in our program. To make use of the command button events,
we will catch the events sent to us by overriding the ActionListener interface’s
actionPerformed( ) method and adding our own version, such as the following:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class button1 extends Applet implements ActionListener {
TextField txtText1;
Button cmdButton1;
public void init() {
txtText1 = new TextField(20);
add(txtText1);
cmdButton1= new Button("Click Me!");
add(cmdButton1);
cmdButton1.addActionListener(this);
}
public void actionPerformed(ActionEvent objEvent) {
.
.
.
The actionPerformed( ) method is the method that will be called when the user
clicks the command button in the applet. The ActionEvent object that is passed as a
parameter here holds information about the event that occurred. This is important if we
have two or more command buttons in our applet. How can we make sure that command
button 1 or command button 2 was clicked? We can check which command button was
clicked with the getSource( ) method of the ActionEvent class. The getSource( ) method
returns the control that caused the event. We can check to see if that control is a
command button1 with the help of if conditional statement, like this:

import java.applet.Applet;
41

import java.awt.*;
import java.awt.event.*;
public class button1 extends Applet implements ActionListener {
TextField txtText1;
Button cmdButton1;
public void init() {
txtText1 = new TextField(20);
add(txtText1);
cmdButton1= new Button("Click Me!");
add(cmdButton1);
cmdButton1.addActionListener(this);
}
public void actionPerformed(ActionEvent objEvent) {
String strMessage = new String ("Click Me button clicked!");
if (objEvent.getSource( ) == cmdButton1) {
txtText1.setText(strMessage);
}
}
}

If the control that created the Java event is button1, then the code that follows the
if conditional statement will be executed when the conditional expression is evaluated to
true. In this case, the message “Click Me button clicked!” will be displayed at the text
field. You will notice here that we set up the Java string object named strMessage as a
local variable under the actionPerformed method and will only be available within this
method (function). This is a good programming practice, since the locally declared
strMessage variable will in no way interfere or in conflict with other variable in other
methods or functions. Finally, the text string value that the strMessage variable holds will
be displayed in the text field using the setText( ) method of the TextField class.

Example 4:

Design and develop a Java applet that if the user clicks the command button Button1, the
message “Button1 clicked!” will be displayed at the text field or if the user clicks the
command button Button2, the message “Button2 clicked!” will be displayed instead.
Follow the design specification below:

Button1 clicked!
Text Field

Button1 Button2 Buttons


42

Figure 1.4 An applet with two Command buttons

Solution 1: Using Applet

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class button2 extends Applet implements ActionListener {
TextField txtText1;
Button cmdButton1, cmdButton2;
public void init() {
txtText1 = new TextField(20);
add(txtText1);
cmdButton1= new Button("Button1");
add(cmdButton1);
cmdButton1.addActionListener(this);
cmdButton2 = new Button("Button2");
add(cmdButton2);
cmdButton2.addActionListener(this);
}
public void actionPerformed(ActionEvent objEvent) {
if (objEvent.getSource() == cmdButton1) {
txtText1.setText("Button1 clicked!");
}
if (objEvent.getSource() ==cmdButton2) {
txtText1.setText("Button2 clicked!");
}
}
}

2. Then save the Java applet with the filename: button2.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>button2</title>
</head>
<body>
<hr>
<applet
code=button2.class
width=200
height=200>
</applet>
<hr>
</body>
</html>
43

4. Now save the HTML script with the filename: button2.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac button2.java (then press the Enter key)

7.When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\button2.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>button2.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer button2.htm (then press the Enter key)

Sample Output:

Figure 1.4a An applet with two Command buttons output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


44

import java.awt.*;
import java.awt.event.*;
public class aButton3 extends Frame implements ActionListener{
TextField txtText1;
Button cmdButton1, cmdButton2;
public aButton3() {
super("Button 2 Example");
setLayout(new FlowLayout());
txtText1 = new TextField(20);
add(txtText1);
cmdButton1= new Button("Button1");
add(cmdButton1);
cmdButton1.addActionListener(this);
cmdButton2 = new Button("Button2");
add(cmdButton2);
cmdButton2.addActionListener(this);
setSize(200,200);
setVisible(true);

addWindowListener(new WindowAdapter() { public void


windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aButton2


public void actionPerformed(ActionEvent objEvent) {
if (objEvent.getSource() == cmdButton1) {
txtText1.setText("Button1 clicked!");
}
if (objEvent.getSource() ==cmdButton2) {
txtText1.setText("Button2 clicked!");
}
}
public static void main (String [] args) {
aButton3 Button3App = new aButton3();
}
} // End of public class aButton3

2. Then save the Java applet with the filename: aButton3.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aButton3.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:
45

C:\JAVAPROG>java aButton3 (then press the Enter key)

Sample Output:

Figure 1.4b Java Application with two Command buttons output

Explanation:

Again, we import here the java.awt.event.* package that contains the ActionListener
interface, as you can see its declaration below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
.
.
.
We created the text field object txtText1 of the TextField class by using the declaration
TextField txtText1 statement and the command button objects cmdButton1 and
cmdButton2 of the Button class by using the declaration Button cmdButton1, cmdButton2
statement.
We can find out what events occur such as button clicks or mouse movements, using the
ActionListener interface. To use the delegation-based event model technique, we specify
that the applet will implement the ActionListener interface in our program as what you
can observe in our code.
When an event occurs, the listener object can hear it, so we will make the listener object
the applet object itself by connecting the applet to cmdButton1 and cmdButton2 as the
listeners. We can accomplish that with the command button’s addActionListener( )
method, as what you can see in our syntax implementation below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
46

public class button2 extends Applet implements ActionListener {


TextField txtText1;
Button cmdButton1, cmdButton2;
public void init( ) {
txtText1 = new TextField(20);
add(txtText1);
cmdButton1= new Button("Button1");
add(cmdButton1);
cmdButton1.addActionListener(this);
cmdButton2 = new Button("Button2");
add(cmdButton2);
cmdButton2.addActionListener(this);
}

The actionPerformed( ) method is the method that will be called when the user clicks the
command button in the applet. The ActionEvent object that is passed as a parameter here
holds information about the event that occurred. This is important if we have two or
more command buttons in our applet. How can we make sure that command button 1 or
command button 2 was clicked? We can check which command button was clicked with
the getSource( ) method of the ActionEvent class. The getSource( ) method returns the
control that caused the event. We can check to see if that control is a command button 1
(cmdButton1) or command button 2 (cmdButton2) with the help of if conditional
statement, like this:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class button2 extends Applet implements ActionListener {
TextField txtText1;
Button cmdButton1, cmdButton2;
public void init() {
txtText1 = new TextField(20);
add(txtText1);
cmdButton1= new Button("Button1");
add(cmdButton1);
cmdButton1.addActionListener(this);
cmdButton2 = new Button("Button2");
add(cmdButton2);
cmdButton2.addActionListener(this);
}
public void actionPerformed(ActionEvent objEvent) {
if (objEvent.getSource( ) == cmdButton1) {
txtText1.setText("Button1 clicked!");
}
if (objEvent.getSource( ) ==cmdButton2) {
txtText1.setText("Button2 clicked!");
}
}
}
47

If the control that created the Java event is command button 1 (cmdButton1), then the
code that follows its corresponding if conditional statement will be executed when the
conditional expression is evaluated to true. In this case, the message “Button1 clicked!”
will be displayed at the text field. Now if the Java event is command button 2
(cmdButton2), then the code that follows its corresponding if conditional statement will
be executed when the conditional expression is evaluated to true. So the message
“Button2 clicked!” will be displayed instead. The message can be displayed in the text
field using the setText( ) method of the TextField class.

Example 5:

Design and develop a Java applet that when the user clicks the Click Me button, the
message “I love you very much, Bianca! Promise.” will be displayed at the text area.
Follow the design specification below:

I love you very much, Bianca!


Promise.

Text Area

Click Me! Button

Figure 1.5 An applet with a Text area and a Command button

Solution: Using Applet

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class textarea1 extends Applet implements ActionListener {
TextArea txtTextArea1;
Button cmdButton1;
public void init() {
txtTextArea1 = new TextArea(" ",5,25);
add(txtTextArea1);
cmdButton1= new Button("Click Me!");
add(cmdButton1);
cmdButton1.addActionListener(this);
}
48

public void actionPerformed(ActionEvent objEvent) {


String strMessage="I love you very much, Bianca! Promise.";
if (objEvent.getSource() == cmdButton1) {
txtTextArea1.insert(strMessage,0);
}
}
}

2. Then save the Java applet with the filename: textarea1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>textarea1</title>
</head>
<body>
<hr>
<applet
code=textarea1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: textarea1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac textarea1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\textarea1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>textarea1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer textarea11.htm (then press the Enter key)


49

Sample Output:

Figure 1.5a An applet with a Text area and a Command button output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.awt.event.*;
public class aTextArea2 extends Frame implements ActionListener{
TextArea txtTextArea1;
Button cmdButton1;
public aTextArea2() {
super("Text Area Example");
setLayout(new FlowLayout());
txtTextArea1 = new TextArea(" ",5,25);
add(txtTextArea1);
cmdButton1= new Button("Click Me!");
add(cmdButton1);
cmdButton1.addActionListener(this);
setSize(200,200);
setVisible(true);

addWindowListener(new WindowAdapter() { public void


windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
} // End of public aTextArea1
public void actionPerformed(ActionEvent objEvent) {
String strMessage="I love you very much, Bianca! Promise.";
if (objEvent.getSource() == cmdButton1) {
txtTextArea1.insert(strMessage,0);
}
50

}
public static void main (String [] args) {
aTextArea2 aTextArea1App = new aTextArea2();
}
} // End of public class aTextArea1

2. Then save the Java applet with the filename: aTextArea2.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aTextArea2.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aTextArea2 (then press the Enter key)

Sample Output:

Figure 1.5b Java Application with a Text area and a Command button output

Explanation:

The text area control is preferably used when we have multiple lines of text to display
such as a group of sentences or one paragraph of information. The text area object can be
set up using the TextArea class of the Java programming language as you will observe
later in our discussion.
51

Again, we import here the java.awt.event.* package that contains the ActionListener
interface, as you can see its declaration below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
.
.
.
We created the text area object txtTextArea1 of the TextArea class by using the
declaration TextArea txtTextArea1 statement and the command button object
cmdButton1 of the Button class by using the declaration Button cmdButton1 statement.
Events such as click event of the command button are passed from source controls to
listener objects. This is the reason why we connect a listener to the command button -
cmdButton1.
We can find out what events occur such as button clicks or mouse movements, using the
ActionListener interface. To use the delegation-based event model technique, we specify
that the applet will implement the ActionListener interface in our program as what you
can observe in our code.
When an event occurs, the listener object can hear it, so we will make the listener object
the applet object itself by connecting the applet to cmdButton1 as a listener. We can
accomplish that with the command button’s addActionListener( ) method, as what you
can see in our syntax implementation below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class textarea1 extends Applet implements ActionListener {
TextArea txtTextArea1;
Button cmdButton1;
public void init( ) {
txtTextArea1 = new TextArea(" ",5,25);
add(txtTextArea1);
cmdButton1= new Button("Click Me!");
add(cmdButton1);
cmdButton1.addActionListener(this);
}

We handle text area the same way we handle text field. However, we specify three
parameters to the TextArea constructor. The first parameter we specify is an empty
string, so that initially the text area will appear blank, then the last two numeric
parameters specified the 5 rows and 25 columns text area’s height and width in the applet
portion.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class textarea1 extends Applet implements ActionListener {
TextArea txtTextArea1;
52

Button cmdButton1;
public void init( ) {
txtTextArea1 = new TextArea(" ",5,25);
add(txtTextArea1);
cmdButton1= new Button("Click Me!");
add(cmdButton1);
cmdButton1.addActionListener(this);
}
public void actionPerformed(ActionEvent objEvent) {
String strMessage="I love you very much, Bianca! Promise.";
if (objEvent.getSource() == cmdButton1) {
txtTextArea1.insert(strMessage,0);
}
}
}

The actionPerformed( ) is the method that will be called when the user clicks the
command button in the applet. The ActionEvent object that is passed as a parameter here
holds information about the event that occurred. This is important if we have two or
more command buttons in our applet. How can we make sure that command button 1 or
command button 2 was clicked? We can check which command button was clicked with
the getSource( ) method of the ActionEvent class. The getSource( ) method returns the
control that caused the event. We can check to see if that control is a command button1
with the help of if conditional statement.
If the control that created the Java event is button1, then the code that follows the if
conditional statement will be executed when the conditional expression is evaluated to
true. In this case, the message “I love you very much, Bianca! Promise.” will be
displayed at the text area. You will notice here that we set up the Java string object
named strMessage as a local variable under the actionPerformed method and will only
be available within this method (function). This is a good programming practice, since
the locally declared strMessage variable will be in no way can interfere or in conflict
with other variable in other methods or functions. Instead of using setText( ) to set the
text string of our text area as we did for text field, we will use insert( ) method of the
TextArea class. In this way, we can insert the text string at a specified location in the text
area. Here in our example, we place the “I love you very much, Bianca!. Promise.”
message at the beginning of the text area since we pass a location of 0 parameter value as
you will notice at the code above.

Example 6:

Design and develop a Java applet that allows you to both enter text string into a text box
and display the text string on the applet. Follow the design specification below:

Enter some words: Hhe


Hello buddy? Are you in, or out?
Text field

Hello buddy? Are you in, or out?


53

Figure 1.6 An applet with a text string entered and displayed both at the text box and on applet

Solution 1: Using Applet

1. At the Microsoft NotePad, write the following code:

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class string3 extends Applet implements TextListener {


Label lblMessage;
TextField txtText1;
String strString1 = "";

public void init() {


lblMessage = new Label("Enter some words: ");
add(lblMessage);
txtText1 = new TextField(20);
add(txtText1);
txtText1.addTextListener(this);
}
public void paint(Graphics objG) {
objG.drawString(strString1,202,42);
}
public void textValueChanged(TextEvent objE) {
strString1 = txtText1.getText();
repaint();
}
}

2. Then save the Java applet with the filename: string3.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>string3</title>
</head>
<body>
<hr>
<applet
code=string3.class
width=600
height=100>
</applet>
<hr>
54

</body>
</html>

4. Now save the HTML script with the filename: string3.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac string3.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\string3.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>string3.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer string3.htm (then press the Enter key)

Sample Output:

Figure 1.6a An applet with a text string entered and displayed both at
the text box and on applet output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


55

import java.awt.*;
import java.awt.event.*;
public class aString3 extends Frame implements TextListener{
Label lblMessage;
TextField txtText1;
String strString1 = "";
public aString3() {
super("Text Area Example");
setLayout(new FlowLayout());
lblMessage = new Label("Enter some words: ");
add(lblMessage);
txtText1 = new TextField(20);
add(txtText1);
txtText1.addTextListener(this);
setSize(600,100);
setVisible(true);

addWindowListener(new WindowAdapter() { public void


windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aTextArea1

public void paint(Graphics objG) {


objG.drawString(strString1,275,82);
}
public void textValueChanged(TextEvent objE) {
strString1 = txtText1.getText();
repaint();
}

public static void main (String [] args) {


aString3 aString3App = new aString3();
}
} // End of public class aString3

2. Then save the Java applet with the filename: aString3.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aString3.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:
56

C:\JAVAPROG>java aString3 (then press the Enter key)

Sample Output:

Figure 1.6b Java Application program with a text string entered and displayed
both at the text box and on applet output

Tip:
We call the repaint( ) method to force the paint event to reoccur so that the user can see the result or effect
of the event that happened right away. Like for example, a button click result or a text that was typed or
keyed into a textfield must be echoed to other controls in an instant.

Explanation:

Again, we import here the java.awt.event.* package that contains the TextListener
interface, as you can see its declaration below:

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class string3 extends Applet implements TextListener {


Label lblMessage;
TextField txtText1;
String strString1 = "";
.
.
.
We created the text field object txtText1 of the TextField class by using the declaration
TextField txtText1 statement and label object lblMessage of the Label class by using the
declaration Label lblMessage1 statement. We also add here our declaration of the
variable string strString1 to handle the entered text string as our data to be displayed to
the applet. We initially declared it as an empty string.
.
.
.
public void init( ) {
lblMessage = new Label("Enter some words: ");
add(lblMessage);
txtText1 = new TextField(20);
add(txtText1);
txtText1.addTextListener(this);
57

}
.
.
.

The lines above simply add the label “Enter some words:” to the applet, as well as a new
text-entry field of 20 characters. We use the TextListener interface so that whatever text
string is entered by the user at the text field, it will be displayed right away at the applet
(as you will observe while running the applet).
.
.
.
public void paint(Graphics objG) {
objG.drawString(strString1,202,42);
}
public void textValueChanged(TextEvent objE) {
strString1 = txtText1.getText( );
repaint( );
}
}

You will notice in our code above that in the event there is a change in value at the text
field , the value (text string) entered will be stored right at the strString1 variable which
in turn is displayed at the applet using the drawString( ) method.

Example 7:

Design and develop a Java applet that allows you to both enter text string into a text box
and display the text string on the applet. This time, the font size of the displayed text
string on the applet is changed to 20 and its font is Georgia. Follow the design
specification below:

Enter some words: Hello


Hhe buddy? Are you in, or out? Text field

Hello buddy? Are you in, or out?


Figure 1.7 An applet with a text string entered and displayed with increased font size

Figure 1.7 An applet with a text string entered and displayed both at the text box and on applet 2

Solution 1: Using Applet

1.At the Microsoft NotePad, write the following code:


58

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class string4 extends Applet implements TextListener {


Label lblMessage;
TextField txtText1;
String strString1 = "";
Font fntFont = new Font("Georgia",Font.BOLD,20);

public void init() {


lblMessage = new Label("Enter some words: ");
add(lblMessage);
txtText1 = new TextField(20);
add(txtText1);
txtText1.addTextListener(this);
}

public void paint(Graphics objG) {


objG.setFont(fntFont);
objG.drawString(strString1,202,62);
}

public void textValueChanged(TextEvent objE) {


strString1 = txtText1.getText();
repaint();
}
}

2. Then save the Java applet with the filename: string4.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>string4</title>
</head>
<body>
<hr>
<applet
code=string4.class
width=600
height=100>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: string4.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


59

C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac string4.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\string4.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>string4.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer string4.htm (then press the Enter key)

Sample Output:

Figure 1.7a An applet with a text string entered and displayed


both at the text box and on applet 2 output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.awt.event.*;
public class aString4 extends Frame implements TextListener{
Label lblMessage;
TextField txtText1;
String strString1 = "";
Font fntFont = new Font("Georgia",Font.BOLD,20);
public aString4() {
super("Text Area Example");
setLayout(new FlowLayout());
lblMessage = new Label("Enter some words: ");
add(lblMessage);
txtText1 = new TextField(20);
60

add(txtText1);
txtText1.addTextListener(this);
setSize(600,100);
setVisible(true);

addWindowListener(new WindowAdapter() { public void


windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aTextArea1


public void paint(Graphics objG) {
objG.setFont(fntFont);
objG.drawString(strString1,275,82);
}

public void textValueChanged(TextEvent objE) {


strString1 = txtText1.getText();
repaint();
}

public static void main (String [] args) {


aString4 aString4App = new aString4();
}
} // End of public class aString4

2. Then save the Java applet with the filename: aString4.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aString4.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aString4 (then press the Enter key)

Sample Output:
61

Figure 1.7b Java Application program with a text string entered and displayed
both at the text box and on applet 2 output

Explanation:

As usual, we import here the java.awt.event.* package that contains the TextListener
interface, as you can see its declaration below:

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class string4 extends Applet implements TextListener {


Label lblMessage;
TextField txtText1;
String strString1 = "";
Font fntFont = new Font("Georgia",Font.BOLD,20);
.
.
.
We created the text box object txtText1 of the TextField class by using the declaration
TextField txtText1 statement and label object lblMessage of the Label class by using the
declaration Label lblMessage1 statement. We also add here our declaration of the
variable string strString1 to handle the entered text string as our data to be displayed to
the applet. We initially declared it as an empty string. What is noticeable here in this
example is our declaration of the font object using the Font class, wherein the parameters
we specify are the new font’s font style (Georgia), its font size (20), and the font must be
written in bold (BOLD).
.
.
.
public void init( ) {
lblMessage = new Label("Enter some words: ");
add(lblMessage);
txtText1 = new TextField(20);
add(txtText1);
txtText1.addTextListener(this);
}
.
.
.
62

The lines above simply add the label “Enter some words:” to the applet, as well as a new
text-entry field of 20 characters. We use the TextListener interface so that whatever text
string is entered by the user at the text field, it will be displayed right away at the applet
(as you will observe while running the applet).
.
.
.
public void paint(Graphics objG) {
objG.setFont(fntFont);
objG.drawString(strString1,202,62);
}

public void textValueChanged(TextEvent objE) {


strString1 = txtText1.getText( );
repaint( );
}
}

You will notice in our code above that in the event there is a change in value at the text
field , the value (text string) entered will be stored right at the strString1 variable which
in turn is displayed at the applet using the drawString( ) method. Setting the font style to
format the displayed text string is so easy by using the setFont( ) method. We simply pass
the object name to that method.

Example 8:

Design and develop a Java applet that allows you to both enter text string into a text box
and display the text string on the applet. The text string will be displayed only after the
Enter key is pressed. Follow the design specification below:

Input some words, then press the Enter key:

Hello buddy? Are you in, or out?


Text Field

Hello buddy? Are you in, or out?

Figure 1.8 An applet with a text string entered and displayed


after pressing the Enter key

Solution 1: Using Applet

1. At the Microsoft NotePad, write the following code:


63

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class string1 extends Applet implements ActionListener {


Label lblMessage;
TextField txtText1;
String strString1 = "";

public void init() {


lblMessage = new Label("Input some words, then
press the Enter key:");
add(lblMessage);
txtText1 = new TextField(15);
txtText1.addActionListener(this);
add(txtText1);
}
public void paint(Graphics objG) {
if (strString1 !="") {
objG.drawString("You entered: "+strString1,21,71);
}
}
public void actionPerformed(ActionEvent objE) {
strString1 = txtText1.getText();
repaint();
}
}

2. Then save the Java applet with the filename: string1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>string1</title>
</head>
<body>
<hr>
<applet
code=string1.class
width=300
height=100>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: string1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


64

C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac string1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\string1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>string1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer string1.htm (then press the Enter key)

Sample Output:

Figure 1.8a An applet with a text string entered and displayed


after pressing the Enter key output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.awt.event.*;
public class aString1 extends Frame implements ActionListener{
Label lblMessage;
TextField txtText1;
String strString1 = "";
public aString1() {
super("String Manipulation Example");
setLayout(new FlowLayout());
lblMessage = new Label("Input some words, then press the Enter
key:");
65

add(lblMessage);
txtText1 = new TextField(15);
txtText1.addActionListener(this);
add(txtText1);
setSize(600,100);
setVisible(true);

addWindowListener(new WindowAdapter() { public void


windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aTextArea1

public void paint(Graphics objG) {


if (strString1 !="") {
objG.drawString("You entered: "+strString1,275,71);
}
}
public void actionPerformed(ActionEvent objE) {
strString1 = txtText1.getText();
repaint();
}

public static void main (String [] args) {


aString1 aString1App = new aString1();
}
} // End of public class aString1

2. Then save the Java applet with the filename: aString1.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aString1.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aString1 (then press the Enter key)

Sample Output:
66

Figure 1.8b Java Application program with a text string entered and displayed
after pressing the Enter key output

Explanation:

We created the text field object txtText1 of the TextField class by using the declaration
TextField txtText1 statement and label object lblMessage of the Label class by using the
declaration Label lblMessage1 statement. We also add here our declaration of the
variable string strString1 to handle the entered text string as our data to be displayed to
the applet. We initially declared it as an empty string, as you can see in our code below:

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class string1 extends Applet implements ActionListener {


Label lblMessage;
TextField txtText1;
String strString1 = " ";
.
.
.
We can find out what events occur such as key-presses, button-clicks or mouse-
movements, using the ActionListener interface. To use the delegation-based event model
technique, we specify that the applet will implement the ActionListener interface in our
program. When an event occurs, the listener object can hear it, so we will make the
listener object the applet object itself by connecting the applet to txtText1 as a listener.
We can accomplish that with the text field’s addActionListener( ) method, as what you
can see in our syntax implementation below:
.
.
.
public void init( ) {
lblMessage = new Label("Input some words, then
press the Enter key:");
add(lblMessage);
txtText1 = new TextField(15);
txtText1.addActionListener(this);
add(txtText1);
}
.
67

.
.

You will notice in our code below that in the event there is a change in value at the text
field , the value (text string) entered will be stored right at the strString1 variable which
in turn is displayed at the applet using the drawString( ) method:
.
.
.
public void paint(Graphics objG) {
if (strString1 !=" ") {
objG.drawString("You entered: "+strString1,21,71);
}
}
public void actionPerformed(ActionEvent objE) {
strString1 = txtText1.getText( );
repaint( );
}
}

What is noticeable here in our code is that the text string will be displayed only if
strString1 variable is not equal to an empty string. The plus (+) sign in our drawString( )
method means to cancatenate the string “You entered:” to whatever string value the
strString1 variable is containing.

Example 9:

Design and develop a Java applet that allows you to both enter text string into a text box
and display the text string on the applet. The text string will be displayed only after the
Enter key is pressed. This time, the font size of the displayed text string on the applet is
changed to 20 and its font is Georgia. Follow the design specification below:

Input some words, then press the Enter key:

Hello buddy? Are you in, or out?


Text field

Hello buddy? Are you in, or out?

Figure 1.9 An applet with a text string entered and displayed with font size increased

Solution 1: Using Applet

1. At the Microsoft NotePad, write the following code:


68

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class string2 extends Applet implements ActionListener {


Label lblMessage;
TextField txtText1;
String strString1 = "";
Font fntFont= new Font("Georgia",Font.BOLD,20);

public void init() {


lblMessage = new Label("Input some words, then
press the Enter key:");
add(lblMessage);
txtText1 = new TextField(20);
txtText1.addActionListener(this);
add(txtText1);
}

public void paint(Graphics objG) {


if (strString1 !="") {
objG.setFont(fntFont);
objG.drawString("You entered: "+strString1,21,61);
}
}
public void actionPerformed(ActionEvent objE) {
strString1 = txtText1.getText();
repaint();
}
}

2. Then save the Java applet with the filename: string2.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>string2</title>
</head>
<body>
<hr>
<applet
code=string2.class
width=600
height=100>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: string2.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
69

then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac string2.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\string2.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>string2.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer string2.htm (then press the Enter key)

Sample Output:

Figure 1.9a An applet with a text string entered and displayed with
font size increased output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.awt.event.*;
public class aString2 extends Frame implements ActionListener{
Label lblMessage;
TextField txtText1;
String strString1 = "";
Font fntFont= new Font("Georgia",Font.BOLD,20);
70

public aString2() {
super("String Manipulation 2 Example");
setLayout(new FlowLayout());
lblMessage = new Label("Input some words, then press the Enter
key:");
add(lblMessage);
txtText1 = new TextField(20);
txtText1.addActionListener(this);
add(txtText1);
setSize(600,100);
setVisible(true);

addWindowListener(new WindowAdapter() { public void


windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aTextArea1

public void paint(Graphics objG) {


if (strString1 !="") {
objG.setFont(fntFont);
objG.drawString("You entered: "+strString1,21,75);
}
}
public void actionPerformed(ActionEvent objE) {
strString1 = txtText1.getText();
repaint();
}

public static void main (String [] args) {


aString2 aString2App = new aString2();
}
} // End of public class aString2

2. Then save the Java applet with the filename: aString2.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aString2.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aString2 (then press the Enter key)


71

Sample Output:

Figure 1.9b Java Application program with a text string entered and displayed with
font size increased output

Explanation:

We created the text field object txtText1 of the TextField class by using the declaration
TextField txtText1 statement and label object lblMessage of the Label class by using the
declaration Label lblMessage1 statement. We also add here our declaration of the
variable string strString1 to handle the entered text string as our data to be displayed to
the applet. We initially declared it as an empty string. What is noticeable here in this
example is our declaration of the font object using the Font class, wherein the parameters
we specify are the new font’s font style (Georgia), its font size (20), and the font must be
written in bold (BOLD) as you can see in our code below:

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class string2 extends Applet implements ActionListener {


Label lblMessage;
TextField txtText1;
String strString1 = " ";
Font fntFont= new Font("Georgia",Font.BOLD,20);
.
.
.
We can find out what events occur such as key-presses, button-clicks or mouse-
movements, using the ActionListener interface. To use the delegation-based event model
technique, we specify that the applet will implement the ActionListener interface in our
program. When an event occurs, the listener object can hear it, so we will make the
listener object the applet object itself by connecting the applet to txtText1 as a listener.
We can accomplish that with the text field’s addActionListener( ) method, as what you
can see in our syntax implementation below:
.
.
.
public void init( ) {
lblMessage = new Label("Input some words, then
press the Enter key:");
72

add(lblMessage);
txtText1 = new TextField(20);
txtText1.addActionListener(this);
add(txtText1);
}
.
.
.
You will notice in our code below that in the event there is a change in value at the text
field , the value (text string) entered will be stored right at the strString1 variable which
in turn is displayed at the applet using the drawString( ) method:
.
.
.
public void paint(Graphics objG) {
if (strString1 !=" ") {
objG.setFont(fntFont);
objG.drawString("You entered: "+strString1,21,61);
}
}
public void actionPerformed(ActionEvent objE) {
strString1 = txtText1.getText();
repaint();
}
}

Setting the font style to format the displayed text string is so easy by using the setFont( )
method. We simply pass the object name to that method.
73

LAB ACTIVITY
TEST 1

1. Design and develop a Java applet that will display the message, “Hello World!” on the
applet. Follow the design specification below:

Hello World!

2. Design and develop a Java applet that will display the message, “Hello World!” at
the text field on the applet. Follow the design specification below:

Hello World! Text field

3. Design and develop a Java applet that when the user clicks the Hello World
button, the message “Hello World button clicked!” will be displayed at the text
field. Follow the design specification below:

Text field
Hello World button clicked!

Hello World! Button


74

4.Design and develop a Java applet that if the user clicks the command button Btn1, the
message “Button1 clicked!” will be displayed at the text field or if the user clicks the
command button Btn2, the message “Button2 clicked!” will be displayed instead. Now if
the user clicks the command button Btn3, the message “Button 3 clicked!” will be
displayed at the text field. Follow the design specification below:

Button1 clicked! Text field

Btn1 Btn2 Btn3 Buttons

5.Design and develop a Java applet that when the user clicks the Blaise Pascal command
button, the quote “ If God does not exist, one stands to lose nothing by believing in him
anyway, while if he does exist, one stands to lose everything by not believing.” will be
displayed at the text area. Follow the design specification below:

If God does not exist, one stands to Text area


lose nothing by believing in him
anyway, while if he does exist, one
stands to lose everything by not
believing.

Blaise Pascal Button

6. Design and develop a Java applet that if the user clicks the command button
Button1, the message “Button1 clicked!” will be displayed at the text field 1, or if
the user clicks the command button Button2, the message “Button2 clicked!” will
be displayed at text fieldFollow the design specification below:
75

Button 1 clicked! Text field

Button 1
Button

Button 2 clicked!
Text field

Button 2 Button

7. Design and develop a Java applet that allows you to both enter text string into a
text box and display the text string on the applet. The text string will be displayed
only after the Enter key is pressed. This time, the font size of the displayed text
string on the applet is changed to 16 and its font is Courier and must be written in
bold-face. Follow the design specification below:

Input some words, then press the Enter key:


Text field
Hello Sandara? Are you in, or out?

Hello Sandara? Are you in, or out?


76

Chapter 3
Using Check Boxes and Option Buttons

Check boxes are valid as single controls, however they are not mutually
exclusive. Meaning, the users can check as many check boxes as they want, unlike in
Option buttons, the user can only select one option at a time. Check boxes are applicable
to the situation where you can select a lot of items because you want them all, such as
ordering a pizza and choose all the ingredients you want to put on it as long as you can
afford to pay. While an option buttons, you can only choose one and only one. The option
buttons are applicable to this situation - marrying a girl. In the Christian world, no matter
how many girlfriends you have at the same time and even in the same place, you can
choose only one among them to marry.
Let us now have an example that deals with these controls to learn them in action.

Example 1:

Design and develop a Java applet that when the user clicks one of the three check boxes,
it will indicate in the text field on which check box the user had clicked. For example, if
Check box 2 was clicked by the user, it will display “Check box 2 selected!” at the text
field. It will do the same with Check box 1 and Check box 3. Follow the design
specification below:

Check 1 Check 2 Check 3 Check boxes

Check box 2 selected! Text Field

Figure 2.1 An applet with Check boxes and one Text field

Solution 1: Using Applet

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class checkbox1 extends Applet implements ItemListener {
77

Checkbox chkBox1, chkBox2, chkBox3;


TextField txtText1;
public void init() {
chkBox1 = new Checkbox("Check 1");
add(chkBox1);
chkBox1.addItemListener(this);
chkBox2 = new Checkbox("Check 2");
add(chkBox2);
chkBox2.addItemListener(this);
chkBox3 = new Checkbox("Check 3");
add(chkBox3);
chkBox3.addItemListener(this);
txtText1 = new TextField(19);
add(txtText1);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText1.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable()==chkBox3) {
txtText1.setText("Check box 3 selected!");
}
}
}

2. Then save the Java applet with the filename: checkbox1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>checkbox1</title>
</head>
<body>
<hr>
<applet
code=checkbox1.class
width=300
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: checkbox1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


78

C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac checkbox1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\checkbox1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>checkbox1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer checkbox1.htm (then press the Enter key)

Sample Output:

Figure 2.1a An applet with Check boxes and one Text field output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:

import java.awt.*;
import java.awt.event.*;
public class aCheckBox2 extends Frame implements ItemListener{
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1;
public aCheckBox2() {
super("Check Box 1");
setLayout(new FlowLayout());
chkBox1 = new Checkbox("Check 1");
79

add(chkBox1);
chkBox1.addItemListener(this);
chkBox2 = new Checkbox("Check 2");
add(chkBox2);
chkBox2.addItemListener(this);
chkBox3 = new Checkbox("Check 3");
add(chkBox3);
chkBox3.addItemListener(this);
txtText1 = new TextField(19);
add(txtText1);
setSize(300,200);
setVisible(true);
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aCheckBox2


public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText1.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable()==chkBox3) {
txtText1.setText("Check box 3 selected!");
}
}

public static void main (String [] args) {


aCheckBox2 CheckBox1App = new aCheckBox2();
}
} // End of public class aCheckBox2

2. Then save the Java applet with the filename: aCheckBox2.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system,
then at the C:\> prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aCheckBox2.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aCheckBox2 (then press the Enter key)


80

Sample Output:

Figure 2.1b Java Application with Check boxes and one Text field output

Tip:
This is a power-user technique to compile your two or more Java applet or application programs
simultaneously in just one line of command using the wildcard way. For example, you can compile the
following Java applet or application at the same time:

button1.java button2.java button3.java button4.java button5.java


button6.java button7.java button8.java

with this one line of compilation syntax:

C:\JAVAPROG>javac button?.java (then press the Enter key)

Wherein the ? (question mark) is the wildcard we used to denote it for the last character of the filename of
our Java applet or application program. In this case, this last character of the filename is the number we
assigned from 1 to 8.
Honestly, I discovered this power-user technique accidentally when I compile the optionbutton list of Java
program in this chapter. I didn’t expect that wildcards are also applicable in the compilation of Java
programs. This wildcard use is famous in the DOS era. I am a DOS-era guy, that is why I knew it well. So
why not try it yourself, buddy?

Explanation:

We created a new class named checkbox1 as shown below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class checkbox1 extends Applet implements ItemListener {
.
.
.
81

Now we can declare the three check boxes and named them, chkBox 1, chkBox 2, and
chkBox 3 and text field called txtText1. The txtText1 object is used to display which
check box is being currently clicked by the user. The check boxes are created with the
Java Checkbox class, while the text field is created with the Java TextField class as
follows:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class checkbox1 extends Applet implements ItemListener {
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1;
.
.
.
You will notice that we actually created and add the new check boxes to the applet in the
init( ) method as you can see below:
.
.
.
public class checkbox1 extends Applet implements ItemListener {
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1;
public void init( ) {
chkBox1 = new Checkbox("Check 1");
add(chkBox1); label
chkBox1.addItemListener(this);
chkBox2 = new Checkbox("Check 2");
add(chkBox2);
chkBox2.addItemListener(this);
chkBox3 = new Checkbox("Check 3");
add(chkBox3);
chkBox3.addItemListener(this);
txtText1 = new TextField(19);
add(txtText1);
}
.
.
.
Take note that we gave a label to each and every check box by passing a string to the
constructor of the Checkbox class, as we did above. To connect the code of the check
boxes controls, we use the ItemListener instead of the ActionListener which we used
previously with the command button control. The check box need the ItemListener since
it can be either checked or unchecked.
We can make our applet into the listener for the check boxes with the check box
addItemListener( ) method as what we can see at the above code. The addItemListener( )
method adds the given item listener to receive item events from the check box.
The method to override when using the ItemListener interface is the itemStateChange( )
method. This method is called when the user clicks one of our check boxes and we are
82

passing an object of the class ItemEvent in that method. We can examine which check
box was clicked by the user through the getItemSelectable( ) method of the ItemEvent
class as what you can see in our code below:
.
.
.
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable( )==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable( )==chkBox2) {
txtText1.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable( )==chkBox3) {
txtText1.setText("Check box 3 selected!");
}
}
}

If chkBox1 is clicked, we can place a message in the text field that says: “ Check box 1
selected!” using the setText( ) method of the TextField class. We do the same thing with
other check boxes too.
You will notice that we increase the width of our applet here in this example (300 wide
and 200 high in pixel) to simply accommodate the three check boxes, as you can see in
our HTML script below:
.
.
.
<applet
code=checkbox1.class
width=300
height=200>
</applet>

.
.
.

By doing so, we can properly display the check boxes and text field in our applet.

Example 2:

Design and develop a Java applet that when the user clicks one of the three check boxes,
it will indicate in the text field on which check box the user had clicked. For example, if
Check box 1 was clicked by the user, it will display “Check box 1 selected!” at the text
field 1. If Check box 2 was clicked by the user, it will display “Check box 2 selected!” at
83

the text field 2, and if Check box 3 was clicked by the user, it will display “Check box 3
selected!” at the text field 3. Follow the design specification below:

Chk1 Chk2 Chk3


Check boxes

Check box 1 selected!

Check box 2 selected ! Text fields

Check box 3 selected!

Figure 2.2 An applet with 3 Check boxes and 3 Text fields

Solution 1: Using Applet

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class checkbox2 extends Applet implements ItemListener {
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1, txtText2, txtText3;
public void init() {
chkBox1 = new Checkbox("Chk1");
add(chkBox1);
chkBox1.addItemListener(this);
chkBox2 = new Checkbox("Chk2");
add(chkBox2);
chkBox2.addItemListener(this);
chkBox3 = new Checkbox("Chk3");
add(chkBox3);
chkBox3.addItemListener(this);
txtText1 = new TextField(19);
add(txtText1);
txtText2 = new TextField(19);
add(txtText2);
txtText3 = new TextField(19);
add(txtText3);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText2.setText("Check box 2 selected!");
84

}
if (objEvent.getItemSelectable()==chkBox3) {
txtText3.setText("Check box 3 selected!");
}
}
}

2. Then save the Java applet with the filename: checkbox2.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>checkbox2</title>
</head>
<body>
<hr>
<applet
code=checkbox2.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: checkbox2.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac checkbox2.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\checkbox2.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>checkbox2.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer checkbox2.htm (then press the Enter key)


85

Sample Output:

Figure 2.2a An applet with 3 Check boxes and 3 Text fields output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.awt.event.*;
public class aCheckBox3 extends Frame implements ItemListener{
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1, txtText2, txtText3;
public aCheckBox3() {
super("Check Box 3");
setLayout(new FlowLayout());
chkBox1 = new Checkbox("Chk1");
add(chkBox1);
chkBox1.addItemListener(this);
chkBox2 = new Checkbox("Chk2");
add(chkBox2);
chkBox2.addItemListener(this);
chkBox3 = new Checkbox("Chk3");
add(chkBox3);
chkBox3.addItemListener(this);
txtText1 = new TextField(19);
add(txtText1);
txtText2 = new TextField(19);
add(txtText2);
txtText3 = new TextField(19);
add(txtText3);
setSize(300,200);
setVisible(true);
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) {
86

System.exit(0);
}
}
);

} // End of public aCheckBox3


public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText2.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable()==chkBox3) {
txtText3.setText("Check box 3 selected!");
}
}

public static void main (String [] args) {


aCheckBox3 CheckBox3App = new aCheckBox3();
}
} // End of public class aCheckBox3

2. Then save the Java applet with the filename: aCheckBox3.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)

C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aCheckBox3.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aCheckBox3 (then press the Enter key)

Sample Output:
87

Figure 2.2b Application with 3 Check boxes and 3 Text fields output

Explanation:

Here in our example, we created a new class named checkbox2 and declared three check
boxes and named them, chkBox1, chkBox2, and chkBox3. Then we declared three text
fields called txtText1, txtText2, and txtText3. The txtText1, txtText2, and txtText3
objects are used to report which of the check boxes is currently clicked by the user. The
check boxes are created with the Java Checkbox class, while the text fields are created
with the Java TextField class as you can observe in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class checkbox2 extends Applet implements ItemListener {
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1, txtText2, txtText3;
.
.
.
You will notice that we actually created and add the new check boxes and text fields to
the applet in the init( ) method as you can see below:
.
.
.
public class checkbox2 extends Applet implements ItemListener {
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1, txtText2, txtText3; label
public void init( ) {
chkBox1 = new Checkbox("Chk1");
add(chkBox1);
chkBox1.addItemListener(this);
chkBox2 = new Checkbox("Chk2");
add(chkBox2);
chkBox2.addItemListener(this);
chkBox3 = new Checkbox("Chk3");
88

add(chkBox3);
chkBox3.addItemListener(this);
txtText1 = new TextField(19);
add(txtText1);
txtText2 = new TextField(19);
add(txtText2);
txtText3 = new TextField(19);
add(txtText3);
}
.
.
.
Take note that we gave a label to each and every check box by passing a string to the
constructor of the Checkbox class, as we did above. To connect the code of the check
boxes controls, we use the ItemListener instead of the ActionListener which we used
previously with the command button control. The check box need the ItemListener since
it can be either checked or unchecked.
We can make our applet into the listener for the check boxes with the check box
addItemListener( ) method as what we can see at the above code. The addItemListener( )
method adds the given item listener to receive item events from the check box.
The method to override when using the ItemListener interface is the itemStateChange( )
method. This method is called when the user clicks one of our check boxes and we are
passed an object of the class ItemEvent in that method. We can examine which check box
was clicked by the user through the getItemSelectable( ) method of the ItemEvent class
as what you can see in our code below:
.
.
.
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable( )==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable( )==chkBox2) {
txtText2.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable( )==chkBox3) {
txtText3.setText("Check box 3 selected!");
}
}
}

If chkBox1 is clicked, we can place a message in the text field that says: “ Check box 1
selected!” using the setText( ) method of the TextField class. We do the same thing with
other check boxes too.
89

Example 3:

Design and develop a Java applet that when the user clicks one of the three check boxes,
it will indicate in the text field on which check box the user had clicked. For example, if
Check box 2 was clicked by the user, it will display “Check box 2 selected!” at the text
field. It will do the same with Check box 1 and Check box 3. This example is similar to
Example 1, however, the text field is now position at the top of the three check boxes.
Follow the design specification below:

Check box 2 selected! Text field

Chk1 Chk2 Chk3

Figure 2.3 An applet with Text field at the top of the Check boxes

Solution: Using Applet

1. At the Microsoft NotePad, write the following code:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class checkbox3 extends Applet implements ItemListener {
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1;
public void init() {
txtText1 = new TextField(19);
add(txtText1);
chkBox1 = new Checkbox("Chk1");
add(chkBox1);
chkBox1.addItemListener(this);
chkBox2 = new Checkbox("Chk2");
add(chkBox2);
chkBox2.addItemListener(this);
chkBox3 = new Checkbox("Chk3");
add(chkBox3);
chkBox3.addItemListener(this);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText1.setText("Check box 2 selected!");
}
90

if (objEvent.getItemSelectable()==chkBox3) {
txtText1.setText("Check box 3 selected!");
}
}
}

2. Then save the Java applet with the filename: checkbox3.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:

<html>
<!- Web page written with Java Applet>
<head>
<title>checkbox3</title>
</head>
<body>
<hr>
<applet
code=checkbox3.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: checkbox3.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)

C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac checkbox3.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\checkbox3.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>checkbox3.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer checkbox3.htm (then press the Enter key)


91

Sample Output:

Figure 2.3a Applet with Text field at the top of the Check boxes output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:

import java.awt.*;
import java.awt.event.*;
public class aCheckBox4 extends Frame implements ItemListener{
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1;
public aCheckBox4() {
super("Check Box 4");
setLayout(new FlowLayout());
txtText1 = new TextField(19);
add(txtText1);
chkBox1 = new Checkbox("Chk1");
add(chkBox1);
chkBox1.addItemListener(this);
chkBox2 = new Checkbox("Chk2");
add(chkBox2);
chkBox2.addItemListener(this);
chkBox3 = new Checkbox("Chk3");
add(chkBox3);
chkBox3.addItemListener(this);
setSize(200,200);
setVisible(true);
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) {
System.exit(0);
}
92

}
);

} // End of public aCheckBox4


public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText1.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable()==chkBox3) {
txtText1.setText("Check box 3 selected!");
}
}

public static void main (String [] args) {


aCheckBox4 CheckBox4App = new aCheckBox4();
}
} // End of public class aCheckBox4

2. Then save the Java applet with the filename: aCheckBox4.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aCheckBox4.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aCheckBox4 (then press the Enter key)

Sample Output:
93

Figure 2.3b Application with Text field at the top of the Check boxes output

Explanation:

Here in our example, we created a new class named checkbox3 and declared three check
boxes and named them, chkBox1, chkBox2, and chkBox3. Then we declared one text
field called txtText1. The txtText1 object is used to report which of the check boxes is
currently clicked by the user. The check boxes are created with the Java Checkbox class,
while the text field is created with the Java TextField class as you can observe in our
code below:
.
.
.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class checkbox3 extends Applet implements ItemListener {
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1;

You will notice that we actually created and added the new check boxes and text field to
the applet in the init( ) method as you can see below:
.
.
.
public void init( ) {
txtText1 = new TextField(19); label
add(txtText1);
chkBox1 = new Checkbox("Chk1");
add(chkBox1);
chkBox1.addItemListener(this);
chkBox2 = new Checkbox("Chk2");
add(chkBox2);
chkBox2.addItemListener(this);
94

chkBox3 = new Checkbox("Chk3");


add(chkBox3);
chkBox3.addItemListener(this);
}
.
.
.

What is noticeable here in this example is that we first declare the text field object before
declaring the three check boxes. This is the reason why the text field is displayed at the
top location in our applet, while the three check boxes are displayed below it.
Take note that we gave a label to each and every check box by passing a string to the
constructor of the Checkbox class, as we did above. To connect the code of the check
boxes controls, we use the ItemListener instead of the ActionListener which we used
previously with the command button control. The check box need the ItemListener since
it can be either checked or unchecked.
We can make our applet into the listener for the check boxes with the check box
addItemListener( ) method as what we can see at the above code. The addItemListener( )
method adds the given item listener to receive item events from the check box.
The method to override when using the ItemListener interface is the itemStateChange( )
method. This method is called when the user clicks one of our check boxes and we are
passed an object of the class ItemEvent in that method. We can examine which check box
was clicked by the user through the getItemSelectable( ) method of the ItemEvent class
as what you can see in our code below:
.
.
.
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText1.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable()==chkBox3) {
txtText1.setText("Check box 3 selected!");
}
}
}

If chkBox1 is clicked, we can place a message in the text field that says: “ Check box 1
selected!” using the setText( ) method of the TextField class. We do the same thing with
other check boxes too.
95

Example 4:

Design and develop a Java applet that when the user clicks one of the three check boxes,
it will indicate in the text field on which check box the user had clicked. For example, if
Check box 1 was clicked by the user, it will display “Check box 1 selected!” at the text
field 1. I Check box 2 was clicked by the user, it will display “Check box 2 selected!” at
the text field 2, and if Check box 3 was clicked by the user, it will display “Check box 3
selected!” at the text field 3. This is the same with Example 2, however the check boxes
and text fields here are positioned at the applet in an alternate position. Follow the design
specification below:

Check 1
Text fields
Check box 1 selected!

Check 2

Check box 2 selected !

Check 3

Check box 3 selected!

Figure 2.4 An applet with Check boxes and Text fields in alternate position

Solution: Using Applet

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class checkbox4 extends Applet implements ItemListener {
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1, txtText2, txtText3;
public void init() {
chkBox1 = new Checkbox("Check 1");
add(chkBox1);
chkBox1.addItemListener(this);
txtText1 = new TextField(19);
add(txtText1);
chkBox2 = new Checkbox("Check 2");
add(chkBox2);
chkBox2.addItemListener(this);
txtText2 = new TextField(19);
add(txtText2);
chkBox3 = new Checkbox("Check 3");
add(chkBox3);
96

chkBox3.addItemListener(this);
txtText3 = new TextField(19);
add(txtText3);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText2.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable()==chkBox3) {
txtText3.setText("Check box 3 selected!");
}
}
}

2. Then save the Java applet with the filename: checkbox4.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:

<html>
<!- Web page written with Java Applet>
<head>
<title>checkbox4</title>
</head>
<body>
<hr>
<applet
code=checkbox4.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: checkbox4.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac checkbox4.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\checkbox4.htm
97

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>checkbox4.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer checkbox4.htm (then press the Enter key)

Sample Output:

Figure 2.4a Applet with Check boxes and Text fields in alternate position output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:

import java.awt.*;
import java.awt.event.*;
public class aCheckBox5 extends Frame implements ItemListener{
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1, txtText2, txtText3;
public aCheckBox5() {
super("Check Box 5");
setLayout(new FlowLayout());
chkBox1 = new Checkbox("Check 1");
add(chkBox1);
chkBox1.addItemListener(this);
txtText1 = new TextField(19);
add(txtText1);
chkBox2 = new Checkbox("Check 2");
add(chkBox2);
98

chkBox2.addItemListener(this);
txtText2 = new TextField(19);
add(txtText2);
chkBox3 = new Checkbox("Check 3");
add(chkBox3);
chkBox3.addItemListener(this);
txtText3 = new TextField(19);
add(txtText3);
setSize(200,250);
setVisible(true);
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aCheckBox5


public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText2.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable()==chkBox3) {
txtText3.setText("Check box 3 selected!");
}
}
public static void main (String [] args) {
aCheckBox5 CheckBox5App = new aCheckBox5();
}
} // End of public class aCheckBox5

2. Then save the Java applet with the filename: aCheckBox5.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aCheckBox5.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aCheckBox5 (then press the Enter key)


99

Sample Output:

Figure 2.4b Apllication with Check boxes and Text fields in alternate position output

Explanation:

Here in our example, we created a new class named checkbox4 and declared three check
boxes and named them, chkBox1, chkBox2, and chkBox3. Then we declared three text
fields called txtText1, txtText2, and txtText3. The txtText1, txtText2, and txtText3
objects are used to report which of the check boxes is currently clicked by the user. The
check boxes are created with the Java Checkbox class, while the text fields are created
with the Java TextField class as you can observe in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class checkbox4 extends Applet implements ItemListener {
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1, txtText2, txtText3;
.
.
.

You will notice that we actually created and add the new check boxes and text fields to
the applet in the init( ) method as you can see below:
.
.
.
public void init( ) {
chkBox1 = new Checkbox("Check 1");
100

add(chkBox1);
chkBox1.addItemListener(this);
txtText1 = new TextField(19);
add(txtText1);
chkBox2 = new Checkbox("Check 2");
add(chkBox2);
chkBox2.addItemListener(this);
txtText2 = new TextField(19); label
add(txtText2);
chkBox3 = new Checkbox("Check 3");
add(chkBox3);
chkBox3.addItemListener(this);
txtText3 = new TextField(19);
add(txtText3);
}
.
.
.
What is noticeable here in this example is that we declare the check box object and text
field alternately. This is the reason why the check box and text field are displayed at the
applet alternately.
Take note that we gave a label to each and every check box by passing a string to the
constructor of the Checkbox class, as we did above. To connect the code of the check
boxes controls, we use the ItemListener instead of the ActionListener which we used
previously with the command button control. The check box need the ItemListener since
it can be either checked or unchecked.
We can make our applet into the listener for the check boxes with the check box
addItemListener( ) method as what we can see at the above code. The addItemListener( )
method adds the given item listener to receive item events from the check box.
The method to override when using the ItemListener interface is the itemStateChange( )
method. This method is called when the user clicks one of our check boxes and we are
passed an object of the class ItemEvent in that method. We can examine which check box
was clicked by the user through the getItemSelectable( ) method of the ItemEvent class
as what you can see in our code below:
.
.
.
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable( )==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable( )==chkBox2) {
txtText2.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable( )==chkBox3) {
txtText3.setText("Check box 3 selected!");
}
}
}
101

If chkBox1 is clicked, we can place a message in the text field that says: “ Check box 1
selected!” using the setText( ) method of the TextField class. We do the same thing with
other check boxes too.

Example 5:

Design and develop a Java applet that when the user clicks one of the three check boxes,
it will indicate in the text field on which check box the user had clicked. For example, if
Check box 1 was clicked by the user, it will display “Check box 1 selected!” at the text
field 1. If Check box 2 was clicked by the user, it will display “Check box 2 selected!” at
the text field 2, and if Check box 3 was clicked by the user, it will display “Check box 3
selected!” at the text field 3.
This is the same with Example 4, however the check boxes and text fields here are
positioned in the same line with each other. Follow the design specification below:

Chk1 Check box 1 selected! Text fields

Chk 2 Check box 2 selected!

Chk 3 Check box 3 selected!

Figure 2.5 An applet with Check box and Text field in the same line

Solution: Using an Applet

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class checkbox5 extends Applet implements ItemListener {
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1, txtText2, txtText3;
public void init() {
chkBox1 = new Checkbox("Chk1");
add(chkBox1);
chkBox1.addItemListener(this);
txtText1 = new TextField(19);
add(txtText1);
chkBox2 = new Checkbox("Chk2");
102

add(chkBox2);
chkBox2.addItemListener(this);
txtText2 = new TextField(19);
add(txtText2);
chkBox3 = new Checkbox("Chk3");
add(chkBox3);
chkBox3.addItemListener(this);
txtText3 = new TextField(19);
add(txtText3);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText2.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable()==chkBox3) {
txtText3.setText("Check box 3 selected!");
}
}
}

2. Then save the Java applet with the filename: checkbox5.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>checkbox5</title>
</head>
<body>
<hr>
<applet
code=checkbox5.class
width=250
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: checkbox5.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac checkbox5.java (then press the Enter key)


103

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\checkbox5.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>checkbox5.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer checkbox5.htm (then press the Enter key)

Sample Output:

Figure 2.5a Applet with Check box and Text field in the same line output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.awt.event.*;
public class aCheckBox6 extends Frame implements ItemListener{
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1, txtText2, txtText3;
public aCheckBox6() {
super("Check Box 6");
setLayout(new FlowLayout());
chkBox1 = new Checkbox("Chk1");
add(chkBox1);
chkBox1.addItemListener(this);
104

txtText1 = new TextField(19);


add(txtText1);
chkBox2 = new Checkbox("Chk2");
add(chkBox2);
chkBox2.addItemListener(this);
txtText2 = new TextField(19);
add(txtText2);
chkBox3 = new Checkbox("Chk3");
add(chkBox3);
chkBox3.addItemListener(this);
txtText3 = new TextField(19);
add(txtText3);
setSize(250,200);
setVisible(true);
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aCheckBox6


public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==chkBox1) {
txtText1.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText2.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable()==chkBox3) {
txtText3.setText("Check box 3 selected!");
}
}
public static void main (String [] args) {
aCheckBox6 CheckBox6App = new aCheckBox6();
}
} // End of public class aCheckBox6

2. Then save the Java applet with the filename: aCheckBox6.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aCheckBox6.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aCheckBox6 (then press the Enter key)


105

Sample Output:

Figure 2.5b Application with Check box and Text field in the same line output

Explanation:

Here in our example, we created a new class named checkbox5 and declared three check
boxes and named them, chkBox1, chkBox2, and chkBox3. Then we declared three text
fields called txtText1, txtText2, and txtText3. The txtText1, txtText2, and txtText3
objects are used to report which of the check boxes is currently clicked by the user. The
check boxes are created with the Java Checkbox class, while the text fields are created
with the Java TextField class as you can observe in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class checkbox5 extends Applet implements ItemListener {
Checkbox chkBox1, chkBox2, chkBox3;
TextField txtText1, txtText2, txtText3;
.
.
.
You will notice that we actually created and add the new check boxes and text fields to
the applet in the init( ) method as you can see below:
.
.
.
public void init( ) {
chkBox1 = new Checkbox("Chk1");
add(chkBox1);
chkBox1.addItemListener(this);
txtText1 = new TextField(19);
106

add(txtText1);
chkBox2 = new Checkbox("Chk2");
add(chkBox2);
chkBox2.addItemListener(this);
txtText2 = new TextField(19);
add(txtText2) ; label
chkBox3 = new Checkbox("Chk3");
add(chkBox3);
chkBox3.addItemListener(this);
txtText3 = new TextField(19);
add(txtText3);
}
.
.
.
What is noticeable here in this example is that we declare the check box object and text
field alternately. This is the reason why the check box and text field are displayed at the
applet alternately. Now to make the check box and text field to be displayed in the same
line in our applet, we have to adjust the width of the applet into 250 wide and 200 high in
pixel as you will notice here in our HTML script below:
.
.
.
<applet
code=checkbox5.class
width=250
height=200>
</applet>
.
.
.
Take note that we gave a label to each and every check box by passing a string to the
constructor of the Checkbox class, as we did above. To connect the code of the check
boxes controls, we use the ItemListener instead of the ActionListener which we used
previously with the command button control. The check box need the ItemListener since
it can be either checked or unchecked.
We can make our applet into the listener for the check boxes with the check box
addItemListener( ) method as what we can see at the above code. The addItemListener( )
method adds the given item listener to receive item events from the check box.
The method to override when using the ItemListener interface is the itemStateChange( )
method. This method is called when the user clicks one of our check boxes and we
passed an object of
the class ItemEvent in that method. We can examine which check box was clicked by the
user through the getItemSelectable( ) method of the ItemEvent class as what you can see
in our code below:

public void itemStateChanged(ItemEvent objEvent) {


if (objEvent.getItemSelectable( )==chkBox1) {
txtText1.setText("Check box 1 selected!");
107

}
if (objEvent.getItemSelectable( )==chkBox2) {
txtText2.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable( )==chkBox3) {
txtText3.setText("Check box 3 selected!");
}
}
}

If chkBox1 is clicked, we can place a message in the text field that says: “ Check box 1
selected!” using the setText( ) method of the TextField class. We do the same thing with
other check boxes too.

Example 6:

Design and develop a Java applet that when the user clicks one of the three option
buttons, it will indicate in the text field on which option button the user had clicked. For
example, if Option button 2 was clicked by the user, it will display “Option button 2
selected!” at the text field. It will do the same with Option button 1 and Option button 3.
Follow the design specification below:

Option 1 Option 2 Option 3

Option button 2 selected! Text field

Figure 2.6 An applet with Option buttons and Text field

Solution: Using Applet

1. At the Microsoft NotePad, write the following code:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class optionbutton1 extends Applet implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1;
108

public void init() {


optButtonGroup1 = new CheckboxGroup();
optButton1 = new Checkbox("Option 1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
optButton2 = new Checkbox("Option 2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
optButton3 = new Checkbox("Option 3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==optButton1) {
txtText1.setText("Option button 1 selected!");
}
if (objEvent.getItemSelectable()==optButton2) {
txtText1.setText("Option button 2 selected!");
}
if (objEvent.getItemSelectable()==optButton3) {
txtText1.setText("Option button 3 selected!");
}
}
}

2. Then save the Java applet with the filename: optionbutton1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>optionbutton1</title>
</head>
<body>
<hr>
<applet
code=optionbutton1.class
width=300
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: optionbutton1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)
109

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac optionbutton1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\optionbutton1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>optionbutton1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer optionbutton1.htm (then press the Enter key)

Sample Output:

Figure 2.6a Applet with Option buttons and Text field output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.awt.event.*;
public class aRadio1 extends Frame implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1;
public aRadio1() {
super("Radio Button 1");
setLayout(new FlowLayout());
optButtonGroup1 = new CheckboxGroup();
110

optButton1 = new Checkbox("Option 1",false,optButtonGroup1);


add(optButton1);
optButton1.addItemListener(this);
optButton2 = new Checkbox("Option 2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
optButton3 = new Checkbox("Option 3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
setSize(300,200);
setVisible(true);
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aRadio1

public void itemStateChanged(ItemEvent objEvent) {


if (objEvent.getItemSelectable()==optButton1) {
txtText1.setText("Option button 1 selected!");
}
if (objEvent.getItemSelectable()==optButton2) {
txtText1.setText("Option button 2 selected!");
}
if (objEvent.getItemSelectable()==optButton3) {
txtText1.setText("Option button 3 selected!");
}
} // End of public void itemStateChanged()

public static void main (String [] args) {


aRadio1 Radio1App = new aRadio1();
}
} // End of the public class aRadio1

2. Then save the Java applet with the filename: aRadio1.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aRadio1.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:
111

C:\JAVAPROG>java aRadio1 (then press the Enter key)

Sample Output:

Figure 2.6b Application with Option buttons and Text field output

Explanation:

The option buttons act like the check boxes controls, however, unlike in check boxes
where you can check them at the same time, in option buttons, you can only click one at a
time. Using the CheckboxGroup object, we can associate option buttons with each other.
Since option buttons are considered similar to check boxes in Java programming,
therefore, the Checkbox class is used to declare the three option buttons we have created
as you can see in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class optionbutton1 extends Applet implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1;
.
.
.

When we add the option buttons to a check box group, they change their appearance
automatically to option buttons.
Now, we are ready to add the option buttons to the new check box group,
CheckboxGroup and initialize them at the init( ) method. We can accomplish that when
we create each option button, passing our CheckboxGroup object to the constructor of the
Checkbox class as we can see here in our code below:
.
.
.
public void init( ) {
optButtonGroup1 = new CheckboxGroup( );
112

optButton1 = new Checkbox("Option 1",false,optButtonGroup1);


add(optButton1);
optButton1.addItemListener(this);
optButton2 = new Checkbox("Option 2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
optButton3 = new Checkbox("Option 3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
}
.
.
.
This attaches the new option button to the check box group. The addItemListener( )
method adds the given item listener to receive item events from the Checkbox group.
This time we will add the itemStateChange( ) method to be used to report back to the
user in our text field, indicating which option button was currently clicked. Here is its
code below:
.
.
.

public void itemStateChanged(ItemEvent objEvent) {


if (objEvent.getItemSelectable( )==optButton1) {
txtText1.setText("Option button 1 selected!");
}
if (objEvent.getItemSelectable( )==optButton2) {
txtText1.setText("Option button 2 selected!");
}
if (objEvent.getItemSelectable( )==optButton3) {
txtText1.setText("Option button 3 selected!");
}
}
}

We can examine which check box was clicked by the user through the
getItemSelectable( ) method of the ItemEvent class, as what you can see in our code
above.
If optButton1 is clicked, we can place a message in the text field that says: “ Option
button 1 selected!” using the setText( ) method of the TextField class. We do the same
thing with other check boxes too.
You will notice here that we increase the applet’s width to 300 (as you can see the HTML
script below), because we want to accommodate the three option buttons at the top
position. With this adjustment, the option buttons and the text field will be displayed in
the applet properly.
.
.
113

.
<applet
code=optionbutton1.class
width=300
height=200>
</applet>
.
.
.
That’s the end of our discussion of this example about option buttons control.

Example 7:

Design and develop a Java applet that when the user clicks one of the three option
buttons, it will indicate in the text field on which option button the user had clicked. For
example, if Option button 2 was clicked by the user, it will display “Option button 2
selected!” at the text field. It will do the same with Option button 1 and Option button 3.
This time, the position of the option buttons and text field are in reverse order. Follow the
design specification below:

Option button 2 selected! Text field

Opt1 Opt2 Opt3

Figure 2.7 An applet with Text field and Option buttons

Solution: Using Applet

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class optionbutton2 extends Applet implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1;
public void init() {
txtText1 = new TextField(20);
add(txtText1);
114

optButtonGroup1 = new CheckboxGroup();


optButton1 = new Checkbox("Opt1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
optButton2 = new Checkbox("Opt2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
optButton3 = new Checkbox("Opt3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==optButton1) {
txtText1.setText("Option button 1 selected!");
}
if (objEvent.getItemSelectable()==optButton2) {
txtText1.setText("Option button 2 selected!");
}
if (objEvent.getItemSelectable()==optButton3) {
txtText1.setText("Option button 3 selected!");
}
}
}

2. Then save the Java applet with the filename: optionbutton2.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>optionbutton2</title>
</head>
<body>
<hr>
<applet
code=optionbutton2.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: optionbutton2.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:
115

C:\JAVAPROG>javac optionbutton2.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\optionbutton2.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>optionbutton2.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer optionbutton2.htm (then press the Enter key)

Figure 2.7a Applet with Text field and Option buttons output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.awt.event.*;
public class aRadio2 extends Frame implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1;
public aRadio2() {
super("Radio Button 2");
setLayout(new FlowLayout());
txtText1 = new TextField(20);
add(txtText1);
optButtonGroup1 = new CheckboxGroup();
optButton1 = new Checkbox("Opt1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
optButton2 = new Checkbox("Opt2",false,optButtonGroup1);
116

add(optButton2);
optButton2.addItemListener(this);
optButton3 = new Checkbox("Opt3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
setSize(200,200);
setVisible(true);
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of class aRadio2

public void itemStateChanged(ItemEvent objEvent) {


if (objEvent.getItemSelectable()==optButton1) {
txtText1.setText("Option button 1 selected!");
}
if (objEvent.getItemSelectable()==optButton2) {
txtText1.setText("Option button 2 selected!");
}
if (objEvent.getItemSelectable()==optButton3) {
txtText1.setText("Option button 3 selected!");
}
}
public static void main (String [] args) {
aRadio2 Radio2App = new aRadio2();
}
} // End of public class aRadio2

2. Then save the Java applet with the filename: aRadio2.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aRadio2.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aRadio2 (then press the Enter key)

Sample Output:
117

Figure 2.7b Application with Text field and Option buttons output

Explanation:

The option buttons act like the check boxes controls, however, unlike in check boxes
where you can check them at the same time, in option buttons, you can only click one at a
time. Using the CheckboxGroup object, we can associate option buttons with each other.
Since option buttons are considered similar to check boxes in Java programming,
therefore, the Checkbox class is used to declare the three option buttons we have created
as you can see in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class optionbutton2 extends Applet implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1;
.
.
.
When we add the option buttons to a check box group, they change their appearance
automatically to option buttons.
Now, we are ready to add the option buttons to the new check box group,
CheckboxGroup and initialize them at the init( ) method. We can accomplish that when
we create each option button, passing our CheckboxGroup object to the constructor of the
Checkbox class as we can see here in our code below:
.
.
.
public void init( ) {
txtText1 = new TextField(20);
add(txtText1);
optButtonGroup1 = new CheckboxGroup( );
optButton1 = new Checkbox("Opt1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
118

optButton2 = new Checkbox("Opt2",false,optButtonGroup1);


add(optButton2);
optButton2.addItemListener(this);
optButton3 = new Checkbox("Opt3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
}
.
.
.
This attaches the new option button to the check box group. The addItemListener( )
method adds the given item listener to receive item events from the Checkbox group.
This time we will add the itemStateChange( ) method to be used to report back to the
user in our text field, indicating which option button was currently clicked. Here is its
code below:
.
.
.
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable( )==optButton1) {
txtText1.setText("Option button 1 selected!");
}
if (objEvent.getItemSelectable( )==optButton2) {
txtText1.setText("Option button 2 selected!");
}
if (objEvent.getItemSelectable( )==optButton3) {
txtText1.setText("Option button 3 selected!");
}
}
}

That’s the end of our discussion of this example about option buttons control.

Example 8:

Design and develop a Java applet that when the user clicks one of the three option
buttons, it will indicate in the text field on which option button the user had clicked. For
example, if Option button 1 was clicked by the user, it will display “Option button 1
selected!” at the text field 1. If Option button 2 was clicked by the user, it will display
“Option button 2 selected!” at the text field 2. And if Option button 3 was clicked by the
user, it will display “Option button 3 selected!” at the text field 3. Follow the design
specification below:
119

Opt1 Opt2 Opt3


Text field

Option button 2 selected!

Figure 2.8 An applet with 3 Option buttons and 3 Text fields

Solution: Using Applet

1. At the Microsoft NotePad, write the following code:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class optionbutton3 extends Applet implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1,txtText2,txtText3;
public void init() {
optButtonGroup1 = new CheckboxGroup();
optButton1 = new Checkbox("Opt1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
optButton2 = new Checkbox("Opt2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
optButton3 = new Checkbox("Opt3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
txtText2 = new TextField(20);
add(txtText2);
txtText3 = new TextField(20);
add(txtText3);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==optButton1) {
txtText1.setText("Option button 1 selected!");
txtText2.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable()==optButton2) {
120

txtText2.setText("Option button 2 selected!");


txtText1.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable()==optButton3) {
txtText3.setText("Option button 3 selected!");
txtText1.setText(" ");
txtText2.setText(" ");
}
}
}

2. Then save the Java applet with the filename: optionbutton3.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>optionbutton3</title>
</head>
<body>
<hr>
<applet
code=optionbutton3.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: optionbutton3.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac optionbutton3.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\optionbutton3.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>optionbutton3.htm (then press the Enter key)


121

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer optionbutton3.htm (then press the Enter key)

Sample Ouput:

Figure 2.8a Applet with 3 Option buttons and 3 Text fields output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:

import java.awt.*;
import java.awt.event.*;
public class aRadio3 extends Frame implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1,txtText2,txtText3;
public aRadio3() {
super("Radio Button 3");
setLayout(new FlowLayout());
optButtonGroup1 = new CheckboxGroup();
optButton1 = new Checkbox("Opt1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
optButton2 = new Checkbox("Opt2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
optButton3 = new Checkbox("Opt3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
txtText2 = new TextField(20);
add(txtText2);
txtText3 = new TextField(20);
add(txtText3);
122

setSize(200,200);
setVisible(true);
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aRadio3


public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==optButton1) {
txtText1.setText("Option button 1 selected!");
txtText2.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable()==optButton2) {
txtText2.setText("Option button 2 selected!");
txtText1.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable()==optButton3) {
txtText3.setText("Option button 3 selected!");
txtText1.setText(" ");
txtText2.setText(" ");
}
}

public static void main (String [] args) {


aRadio3 Radio3App = new aRadio3();
}
} // End of public class aRadio3

2. Then save the Java applet with the filename: aRadio3.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aRadio3.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aRadio3 (then press the Enter key)

Sample Ouput:
123

Figure 2.8b Application with 3 Option buttons and 3 Text fields output

Explanation:

The option buttons act like the check boxes controls, however, unlike in check boxes
where you can check them at the same time, in option buttons, you can only click one at a
time. Using the CheckboxGroup object, we can associate option buttons with each other.
Since option buttons are considered similar to check boxes in Java programming,
therefore, the Checkbox class is used to declare the three option buttons we have created
as you can see in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class optionbutton3 extends Applet implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1,txtText2,txtText3;
.
.
.
When we add the option buttons to a check box group, they change their appearance
automatically to option buttons.
Now, we are ready to add the option buttons to the new check box group,
CheckboxGroup and initialize them at the init( ) method. We can accomplish that when
we create each option button, passing our CheckboxGroup object to the constructor of the
Checkbox class as we can see here in our code below:
.
.
.
public void init( ) {
optButtonGroup1 = new CheckboxGroup( );
optButton1 = new Checkbox("Opt1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
optButton2 = new Checkbox("Opt2",false,optButtonGroup1);
add(optButton2);
124

optButton2.addItemListener(this);
optButton3 = new Checkbox("Opt3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
txtText2 = new TextField(20);
add(txtText2);
txtText3 = new TextField(20);
add(txtText3);
}
.
.
.
This attaches the new option button to the check box group.
You will notice here in the code above that we first initialize and add the three option
buttons control then followed by the three text fields. In this way, the three option buttons
are the first to be displayed in our applet, followed by the three text fields. Remember
that these arrangement of control initialization in the init( ) method plays an important
role in how the controls will be displayed at the applet. The first control to be initialized
and added will be the first control also to be displayed at the applet. Meaning, the
controls will be positioned at the top portion of the applet.
The addItemListener( ) method adds the given item listener to receive item events from
the Checkbox group. This time we will add the itemStateChange( ) method to be used to
report back to the user in our text field, indicating which option button was currently
clicked. Here is its code below:
.
.
.
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable( )==optButton1) {
txtText1.setText("Option button 1 selected!");
txtText2.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable( )==optButton2) {
txtText2.setText("Option button 2 selected!");
txtText1.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable( )==optButton3) {
txtText3.setText("Option button 3 selected!");
txtText1.setText(" ");
txtText2.setText(" ");
}
}
}

You will notice also in our code above that if the optButton1 is clicked by the user, the
125

if (objEvent.getItemSelectable( )==optButton1) {

conditional expression is evaluated to true, thus, executing its associated statement


below:

txtText1.setText("Option button 1 selected!");


txtText2.setText(" ");
txtText3.setText(" ");

The purpose why we set the txtText2 and txtText3 objects with an empty string is to
display a blank to text field 2 and text field 3. We do the same thing with the other option
buttons (the optButton2 and optButton3).

Example 9:

Design and develop a Java applet that when the user clicks one of the three option
buttons, it will indicate in the text field on which option button the user had clicked. For
example, if Option button 1 was clicked by the user, it will display “Option button 1
selected!” at the text field 1. If Option button 2 was clicked by the user, it will display
“Option button 2 selected!” at the text field 2. And if Option button 3 was clicked by the
user, it will display “Option button 3 selected!” at the text field 3. This time, option
button and text field are in the same line with each other. Follow the design specification
below:

Text fields
Opt1

Opt2 Option button 2 selected!

Opt3

Figure 2.9 Applet with Option buttons and Text fields in the same line

Solution: Using Applet

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class optionbutton4 extends Applet implements ItemListener {
CheckboxGroup optButtonGroup1;
126

Checkbox optButton1, optButton2, optButton3;


TextField txtText1,txtText2,txtText3;
public void init() {
optButtonGroup1 = new CheckboxGroup();
optButton1 = new Checkbox("Opt1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
optButton2 = new Checkbox("Opt2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
txtText2 = new TextField(20);
add(txtText2);
optButton3 = new Checkbox("Opt3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText3 = new TextField(20);
add(txtText3);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==optButton1) {
txtText1.setText("Option button 1 selected!");
txtText2.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable()==optButton2) {
txtText2.setText("Option button 2 selected!");
txtText1.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable()==optButton3) {
txtText3.setText("Option button 3 selected!");
txtText1.setText(" ");
txtText2.setText(" ");
}
}
}

2. Then save the Java applet with the filename: optionbutton4.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>optionbutton4</title>
</head>
<body>
<hr>
<applet
code=optionbutton4.class
width=250
height=200>
</applet>
<hr>
127

</body>
</html>

4. Now save the HTML script with the filename: optionbutton4.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac optionbutton4.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\optionbutton4.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>optionbutton4.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer optionbutton4.htm (then press the Enter key)

Sample Output:

Figure 2.9a Applet with Option buttons and Text fields in the same line output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


128

import java.awt.*;
import java.awt.event.*;
public class aRadio4 extends Frame implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1,txtText2,txtText3;
public aRadio4() {
super("Radio Button 4 Example");
setLayout(new FlowLayout());
optButtonGroup1 = new CheckboxGroup();
optButton1 = new Checkbox("Opt1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
optButton2 = new Checkbox("Opt2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
txtText2 = new TextField(20);
add(txtText2);
optButton3 = new Checkbox("Opt3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText3 = new TextField(20);
add(txtText3);
setSize(250,200);
setVisible(true);
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aRadio4


public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==optButton1) {
txtText1.setText("Option button 1 selected!");
txtText2.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable()==optButton2) {
txtText2.setText("Option button 2 selected!");
txtText1.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable()==optButton3) {
txtText3.setText("Option button 3 selected!");
txtText1.setText(" ");
txtText2.setText(" ");
}
}

public static void main (String [] args) {


aRadio4 Radio4App = new aRadio4();
}
129

} // End of public class aRadio4

2. Then save the Java applet with the filename: aRadio4.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)

C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aRadio4.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aRadio4 (then press the Enter key)

Sample Output:

Figure 2.9b Application with Option buttons and Text fields in the same line output

Explanation:

The option buttons act like the check boxes controls, however, unlike in check boxes
where you can check them at the same time, in option buttons, you can only click one at a
time. Using the CheckboxGroup object, we can associate option buttons with each other.
Since option buttons are considered similar to check boxes in Java programming,
therefore, the Checkbox class is used to declare the three option buttons we have created
as you can see in our code below:

import java.applet.Applet;
import java.awt.*;
130

import java.awt.event.*;
public class optionbutton4 extends Applet implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1,txtText2,txtText3;
.
.
.
When we add the option buttons to a check box group, they change their appearance
automatically to option buttons.
Now, we are ready to add the option buttons to the new check box group,
CheckboxGroup and initialize them at the init( ) method. We can accomplish that when
we create each option button, passing our CheckboxGroup object to the constructor of the
Checkbox class as we can see here in our code below:
.
.
.
public void init( ) {
optButtonGroup1 = new CheckboxGroup( );
optButton1 = new Checkbox("Opt1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
optButton2 = new Checkbox("Opt2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
txtText2 = new TextField(20);
add(txtText2);
optButton3 = new Checkbox("Opt3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText3 = new TextField(20);
add(txtText3);
}
.
.
.
This attaches the new option button to the check box group.
You will notice here in the code above that we initialize and add the Option button 1
control then followed by the Text field 1.The same goes with other option buttons and
text fields. Remember that these arrangement of control initialization in the init( ) method
plays an important role in how the controls will be displayed at the applet. The first
control to be initialized and added will be the first control also to be displayed at the
applet, followed by the other controls.
The addItemListener( ) method adds the given item listener to receive item events from
the Checkbox group. This time we will add the itemStateChange( ) method to be used to
report back to the user in our text field, indicating which option button was currently
clicked. Here is its code below:
131

.
.
.
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable( )==optButton1) {
txtText1.setText("Option button 1 selected!");
txtText2.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable( )==optButton2) {
txtText2.setText("Option button 2 selected!");
txtText1.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable( )==optButton3) {
txtText3.setText("Option button 3 selected!");
txtText1.setText(" ");
txtText2.setText(" ");
}
}
}
.
.
.
You will notice also in our code above that if the optButton1 is clicked by the user, the

if (objEvent.getItemSelectable( )==optButton1) {

conditional expression is evaluated to true, thus, executing its associated statement


below:

txtText1.setText("Option button 1 selected!");


txtText2.setText(" ");
txtText3.setText(" ");

The purpose why we set the txtText2 and txtText3 objects with an empty string is to
display a blank to text field 2 and text field 3. We do the same thing with the other option
buttons (the optButton2 and optButton3).
You will notice here that we increase the applet’s width to 250 (as you can see the HTML
script below), because we want to accommodate the option button and the text field to be
displayed in the applet within the same line. With this adjustment, the option buttons and
the text fields will be displayed in the applet properly.
.
.
.
<applet
code=optionbutton4.class
width=250
height=200>
</applet>
132

.
.
.
That’s the end of our discussion of the fourth example of our option buttons control.

Example 10:

Design and develop a Java applet that when the user clicks one of the three option
buttons, it will indicate in the text field on which option button the user had clicked. For
example, if Option button 1 was clicked by the user, it will display “Option button 1
selected!” at the text field 1. If Option button 2 was clicked by the user, it will display
“Option button 2 selected!” at the text field 2. And if Option button 3 was clicked by the
user, it will display “Option button 3 selected!” at the text field 3. This time, option
button and text field are in alternate order. Follow the design specification below:

Option 1
Text fields

Option 2

Option button 2 selected!

Option 3

Figure 2.10 Applet with Option buttons and Text fields in alternate order

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class optionbutton5 extends Applet implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1,txtText2,txtText3;
public void init() {
optButtonGroup1 = new CheckboxGroup();
optButton1 = new Checkbox("Option 1",false,optButtonGroup1);
add(optButton1);
133

optButton1.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
optButton2 = new Checkbox("Option 2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
txtText2 = new TextField(20);
add(txtText2);
optButton3 = new Checkbox("Option 3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText3 = new TextField(20);
add(txtText3);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==optButton1) {
txtText1.setText("Option button 1 selected!");
txtText2.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable()==optButton2) {
txtText2.setText("Option button 2 selected!");
txtText1.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable()==optButton3) {
txtText3.setText("Option button 3 selected!");
txtText1.setText(" ");
txtText2.setText(" ");
}
}
}

2. Then save the Java applet with the filename: optionbutton5.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:

<html>
<!- Web page written with Java Applet>
<head>
<title>optionbutton5</title>
</head>
<body>
<hr>
<applet
code=optionbutton5.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: optionbutton5.htm.


5. This time, activate the Java compiler batch file with the following steps:
134

Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac optionbutton5.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\optionbutton5.htm

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer optionbutton5.htm (then press the Enter key)

Sample Output:

Figure 2.10a Applet with Option buttons and Text fields in alternate order output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.awt.event.*;
public class aRadio5 extends Frame implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1,txtText2,txtText3;
public aRadio5() {
135

super("Radio Button 5 Example");


setLayout(new FlowLayout());
optButtonGroup1 = new CheckboxGroup();
optButton1 = new Checkbox("Option 1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
optButton2 = new Checkbox("Option 2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
txtText2 = new TextField(20);
add(txtText2);
optButton3 = new Checkbox("Option 3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText3 = new TextField(20);
add(txtText3);
setSize(200,250);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aRadio5


public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==optButton1) {
txtText1.setText("Option button 1 selected!");
txtText2.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable()==optButton2) {
txtText2.setText("Option button 2 selected!");
txtText1.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable()==optButton3) {
txtText3.setText("Option button 3 selected!");
txtText1.setText(" ");
txtText2.setText(" ");
}
}

public static void main (String [] args) {


aRadio5 Radio5App = new aRadio5();
}
} // End of public class aRadio5

2. Then save the Java applet with the filename: aRadio5.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:
136

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aRadio5.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aRadio5 (then press the Enter key)

Sample Output:

Figure 2.10b Application with Option buttons and Text fields in alternate order output

Explanation:

The option buttons act like the check boxes controls, however, unlike in check boxes
where you can check them at the same time, in option buttons, you can only click one at a
time. Using the CheckboxGroup object, we can associate option buttons with each other.
Since option buttons are considered similar to check boxes in Java programming,
therefore, the Checkbox class is used to declare the three option buttons we have created
as you can see in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class optionbutton5 extends Applet implements ItemListener
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
TextField txtText1,txtText2,txtText3;
.
.
137

When we add the option buttons to a check box group, they change their appearance
automatically to option buttons.
Now, we are ready to add the option buttons to the new check box group,
CheckboxGroup and initialize them at the init( ) method. We can accomplish that when
we create each option button, passing our CheckboxGroup object to the constructor of the
Checkbox class as we can see here in our code below:
.
.
.
public void init( ) {
optButtonGroup1 = new CheckboxGroup( );
optButton1 = new Checkbox("Option 1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
optButton2 = new Checkbox("Option 2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
txtText2 = new TextField(20);
add(txtText2);
optButton3 = new Checkbox("Option 3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText3 = new TextField(20);
add(txtText3);
}
.
.
.
This attaches the new option button to the check box group.
You will notice here in the code above that we initialize and add the Option button 1
control then followed by the Text field 1.The same goes with other option buttons and
text fields. Remember that these arrangement of control initialization in the init( ) method
plays an important role in how the controls will be displayed at the applet. The first
control to be initialized and added will be the first control also to be displayed at the
applet, followed by the other controls.
The addItemListener( ) method adds the given item listener to receive item events from
the Checkbox group. This time we will add the itemStateChange( ) method to be used to
report back to the user in our text field, indicating which option button was currently
clicked. Here is its code below:
.
.
.
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable( )==optButton1) {
txtText1.setText("Option button 1 selected!");
138

txtText2.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable( )==optButton2) {
txtText2.setText("Option button 2 selected!");
txtText1.setText(" ");
txtText3.setText(" ");
}
if (objEvent.getItemSelectable( )==optButton3) {
txtText3.setText("Option button 3 selected!");
txtText1.setText(" ");
txtText2.setText(" ");
}
}
}

You will notice also in our code above that if the optButton1 is clicked by the user, the

if (objEvent.getItemSelectable()==optButton1) {

conditional expression is evaluated to true, thus, executing its associated statement


below:

txtText1.setText("Option button 1 selected!");


txtText2.setText(" ");
txtText3.setText(" ");

The purpose why we set the txtText2 and txtText3 objects with an empty string is to
display a blank to text field 2 and text field 3. We do the same thing with the other option
buttons (the optButton2 and optButton3).

Example 11:

Design and develop a Java applet that when the user clicks one of the three option
buttons, it will indicate in the text field on which option button the user had clicked. The
same thing also happened for the check boxes. For example, if Option button 1 was
clicked by the user, it will display “Option button 1 selected!” at the text field 1. If
Option button 2 was clicked by the user, it will display “Option button 2 selected!” at the
text field 1. And if Option button 3 was clicked by the user, it will display “Option button
3 selected!” at the text field 1. In the case of the check boxes, if Check box 1 was clicked
by the user, it will display “Check box 1 selected!” at the text field 2. If Check box 2 was
clicked by the user, it will display “Check box 2 selected!” at the text field 2. And if
Check box 3 was clicked by the user, it will display “Check box 3 selected!” at the text
field 2. Follow the design specification below:
139

Opt1 Opt2 Opt3

Option button 2 selected! Text field 1

Chk1 Chk2 Chk3

Check box 3 selected!


Text field 2

Figure 2.11 An applet with Option buttons, Check boxes and Text fields

Solution: Using Applet

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class optchk1 extends Applet implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
Checkbox chkBox1, chkBox2,chkBox3;
TextField txtText1,txtText2;
public void init() {
optButtonGroup1 = new CheckboxGroup();
optButton1 = new Checkbox("Opt1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
optButton2 = new Checkbox("Opt2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
optButton3 = new Checkbox("Opt3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
chkBox1 = new Checkbox("Chk1");
add(chkBox1);
chkBox1.addItemListener(this);
chkBox2 = new Checkbox("Chk2");
add(chkBox2);
chkBox2.addItemListener(this);
chkBox3 = new Checkbox("Chk3");
add(chkBox3);
chkBox3.addItemListener(this);
txtText2 = new TextField(20);
add(txtText2);
140

}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==optButton1) {
txtText1.setText("Option button 1 selected!");
}
if (objEvent.getItemSelectable()==optButton2) {
txtText1.setText("Option button 2 selected!");
}
if (objEvent.getItemSelectable()==optButton3) {
txtText1.setText("Option button 3 selected!");
}
if (objEvent.getItemSelectable()==chkBox1) {
txtText2.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText2.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable()==chkBox3) {
txtText2.setText("Check box 3 selected!");
}
}
}

2. Then save the Java applet with the filename: optchk1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:

<html>
<!- Web page written with Java Applet>
<head>
<title>optchk1</title>
</head>
<body>
<hr>
<applet
code=optchk1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: optchk1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)

C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:
141

C:\JAVAPROG>javac optchk1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\optchk1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>optchk1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer optchk1.htm (then press the Enter key)

Sample Output:

Figure 2.11a Applet with Option buttons, Check boxes and Text fields output

Solution 2: Using GUI-Based Application

1. At the Microsoft NotePad, write the following code:

import java.awt.*;
import java.awt.event.*;
public class aCheckRadio1 extends Frame implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
Checkbox chkBox1, chkBox2,chkBox3;
TextField txtText1,txtText2;
public aCheckRadio1() {
142

super("Check Box & Radio 1 Example");


setLayout(new FlowLayout());
optButtonGroup1 = new CheckboxGroup();
optButton1 = new Checkbox("Opt1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
optButton2 = new Checkbox("Opt2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
optButton3 = new Checkbox("Opt3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
chkBox1 = new Checkbox("Chk1");
add(chkBox1);
chkBox1.addItemListener(this);
chkBox2 = new Checkbox("Chk2");
add(chkBox2);
chkBox2.addItemListener(this);
chkBox3 = new Checkbox("Chk3");
add(chkBox3);
chkBox3.addItemListener(this);
txtText2 = new TextField(20);
add(txtText2);
setSize(200,200);
setVisible(true);
addWindowListener(new WindowAdapter() { public void
windowClosing(WindowEvent e) {
System.exit(0);
}
}
);

} // End of public aCheckRadio1


public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==optButton1) {
txtText1.setText("Option button 1 selected!");
}
if (objEvent.getItemSelectable()==optButton2) {
txtText1.setText("Option button 2 selected!");
}
if (objEvent.getItemSelectable()==optButton3) {
txtText1.setText("Option button 3 selected!");
}
if (objEvent.getItemSelectable()==chkBox1) {
txtText2.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText2.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable()==chkBox3) {
txtText2.setText("Check box 3 selected!");
}
}

public static void main (String [] args) {


143

aCheckRadio1 CheckRadio1App = new aCheckRadio1();


}
} // End of public class aCheckRadio1

2. Then save the Java applet with the filename: aCheckRadio1.java.


3. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

4.Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac aCheckRadio1.java (then press the Enter key)

5.When no error is encountered during the compilation process, you can now type the
following line at the Command Prompt to run it:

C:\JAVAPROG>java aCheckRadio1 (then press the Enter key)

Sample Output:

Figure 2.11b Application with Option buttons, Check boxes and Text fields output

Explanation:

The option buttons act like the check boxes controls, however, unlike in check boxes
where you can check them at the same time, in option buttons, you can only click one at a
time. Using the CheckboxGroup object, we can associate option buttons with each other.
Since option buttons are considered similar to check boxes in Java programming,
therefore, the Checkbox class is used to declare the three option buttons we have created
as you can see in our code below:

import java.applet.Applet;
144

import java.awt.*;
import java.awt.event.*;
public class optchk1 extends Applet implements ItemListener {
CheckboxGroup optButtonGroup1;
Checkbox optButton1, optButton2, optButton3;
Checkbox chkBox1, chkBox2,chkBox3;
TextField txtText1,txtText2;
.
.
.
When we add the option buttons to a check box group, they change their appearance
automatically to option buttons.
Now, we are ready to add the option buttons to the new check box group,
CheckboxGroup and initialize them at the init( ) method. We can accomplish that when
we create each option button, passing our CheckboxGroup object to the constructor of the
Checkbox class as we can see here in our code below:
.
.
.
public void init( ) {
optButtonGroup1 = new CheckboxGroup( );
optButton1 = new Checkbox("Opt1",false,optButtonGroup1);
add(optButton1);
optButton1.addItemListener(this);
optButton2 = new Checkbox("Opt2",false,optButtonGroup1);
add(optButton2);
optButton2.addItemListener(this);
optButton3 = new Checkbox("Opt3",false,optButtonGroup1);
add(optButton3);
optButton3.addItemListener(this);
txtText1 = new TextField(20);
add(txtText1);
chkBox1 = new Checkbox("Chk1");
add(chkBox1);
chkBox1.addItemListener(this);
chkBox2 = new Checkbox("Chk2");
chkBox2.addItemListener(this);
chkBox3 = new Checkbox("Chk3");
add(chkBox3);
chkBox3.addItemListener(this);
txtText2 = new TextField(20);
add(txtText2);
}
.
.
.
This attaches the new option button to the check box group. Since we want to initialize
and add three Check boxes in our applet, you will also notice that they appeared here in
the init( ) method too.
145

As you will observe here in the code above that we initialize and add first the three
Option buttons control then followed by the Text field 1, and we also do the same thing
with the three Check boxes which we first initialize and add before the Text field 2. The
arrangement of control initialization in the init( ) method plays an important role in how
the controls will be displayed at the applet. The first control to be initialized and added
will be the first control also to be displayed at the applet, followed by the other controls.
The addItemListener( ) method adds the given item listener to receive item events from
the Checkbox group. This time we will add the itemStateChange( ) method to be used to
report back to the user in our text field, indicating which option button or check box was
currently clicked. Here is its code below:
.
.
.
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==optButton1) {
txtText1.setText("Option button 1 selected!");
}
if (objEvent.getItemSelectable()==optButton2) {
txtText1.setText("Option button 2 selected!");
}
if (objEvent.getItemSelectable()==optButton3) {
txtText1.setText("Option button 3 selected!");
}
if (objEvent.getItemSelectable()==chkBox1) {
txtText2.setText("Check box 1 selected!");
}
if (objEvent.getItemSelectable()==chkBox2) {
txtText2.setText("Check box 2 selected!");
}
if (objEvent.getItemSelectable()==chkBox3) {
txtText2.setText("Check box 3 selected!");
}
}

This is the end of our discussion to the last example we have for option buttons and check
boxes controls. I hope you enjoyed working with the preceding examples and having fun
coding and debugging your programs.
146

LAB ACTIVITY
TEST 2

1. Design and develop a Java applet that when the user clicks one of the three check
boxes, it will indicate in the text field on which check box the user had clicked.
For example, if Check box 2 was clicked by the user, it will display “Check box 2
selected!” at the text field. It will do the same with Check box 1, Check box 3,
and Check box 4. Follow the design specification below:

Chk1 Chk2 Chk3 Chk4

Text field
Check box 2 selected!

2. Design and develop a Java applet that when the user clicks one of the three check
boxes, it will indicate in the text field on which check box the user had clicked. For
example, if Check box 2 was clicked by the user, it will display “Check box 2 selected!”
at the text field. It will do the same with Check box 1, Check box 3, and Check box 4.
This time, the text field is displayed at the top of the applet followed by the four check
boxes below it. Follow the design specification below:

Check box 2 selected! Text field

Chk1 Chk2 Chk3 Chk4

3.Design and develop a Java applet that when the user clicks one of the three check
boxes, it will indicate in the text field on which check box the user had clicked. For
example, if Check box 1 was clicked by the user, it will display “Check box 1 selected!”
147

at the text field 1. If Check box 2 was clicked by the user, it will display “Check box 2
selected!” at the text field 2, and if Check box 3 was clicked by the user, it will display
“Check box 3 selected!” at the text field 3. Now if Check box 4 was clicked by the user,
it will display “Check box 4 selected!” at the text field 4. Follow the design specification
below:

Chk1 Chk2 Chk3 Chk4

Text fields
Check box 1 selected!

Check box 2 selected !

Check box 3 selected!

Check box 4 selected!

4. Design and develop a Java applet that when the user clicks one of the three check
boxes, it will indicate in the text field on which check box the user had clicked. For
example, if Check box 1 was clicked by the user, it will display “Check box 1 selected!”
at the text field 1. If Check box 2 was clicked by the user, it will display “Check box 2
selected!” at the text field 2, and if Check box 3 was clicked by the user, it will display
“Check box 3 selected!” at the text field 3. Now if Check box 4 was clicked by the user,
it will display “Check box 4 selected!” at the text field 4. Follow the design specification
below:

Check 1

Check box 1 selected!

Check 2

Text fields
Check box 2 selected !

Check 3

Check box 3 selected!

Check 4

Check box 4 selected!


148

5. Design and develop a Java applet that when the user clicks one of the three check
boxes, it will indicate in the text field on which check box the user had clicked. For
example, if Check box 1 was clicked by the user, it will display “Check box 1 selected!”
at the text field 1. If Check box 2 was clicked by the user, it will display “Check box 2
selected!” at the text field 2, and if Check box 3 was clicked by the user, it will display
“Check box 3 selected!” at the text field 3.
Now if the Check box 4 was clicked by the user, it will display “Check box 4 selected!”
at the text field. Follow the design specification below:

Chk1 Check box 1 selected! Text fields

Chk2 Check box 2 selected!

Chk3 Check box 3 selected!

Chk4 Check box 4 selected!

6. Design and develop a Java applet that when the user clicks one of the three option
buttons, it will indicate in the text field on which option button the user had clicked. For
example, if Option button 2 was clicked by the user, it will display “Option button 2
selected!” at the text field. It will do the same with Option button 1, Option button 3 and
Option button 4. Follow the design specification below:

Opt 1 Opt2 Opt3 Opt4

Option button 2 selected! Text field


149

7. Design and develop a Java applet that when the user clicks one of the three option
buttons, it will indicate in the text field on which option button the user had clicked. For
example, if Option button 2 was clicked by the user, it will display “Option button 2
selected!” at the text field. It will do the same with Option button 1, Option button 3 and
Option button 4. This time, the text field is displayed first at the top of the applet
followed by the option buttons below it. Follow the design specification below:

Option button 2 selected!


Text field

Opt 1 Opt2 Opt3 Opt4

8. Design and develop a Java applet that when the user clicks one of the three option
buttons, it will indicate in the text field on which option button the user had
clicked. For example, if Option button 1 was clicked by the user, it will display
“Option button 1 selected!” at the text field 1. If Option button 2 was clicked by
the user, it will display “Option button 2 selected!” at the text field 2. And if
Option button 3 was clicked by the user, it will display “Option button 3
selected!” at the text field 3. Now if Option 4 was clicked by the user, it will
display “Option button 4 selected!” at text field 4. Follow the design specification
below:

Opt1 Opt2 Opt3 Opt4

Option button 2 selected! Text field

9. Design and develop a Java applet that when the user clicks one of the three
option buttons, it will indicate in the text field on which option button the user
150

had clicked. For example, if Option button 1 was clicked by the user, it will
display “Option button 1 selected!” at the text field 1. If Option button 2 was
clicked by the user, it will display “Option button 2 selected!” at the text field 2.
If Option button 3 was clicked by the user, it will display “Option button 3
selected!” at the text field 3. Now if Option button 4 was clicked by the user, it
will display “Option button 4 selected!” at the text field 4. This time, option
button and text field are in the same line with each other. Follow the design
specification below:

Opt1

Opt2 Option button 2 selected!


Text field

Opt3

Opt4

10.Design and develop a Java applet that when the user clicks one of the three option
buttons, it will indicate in the text field on which option button the user had clicked. For
example, if Option button 1 was clicked by the user, it will display “Option button 1
selected!” at the text field 1. If Option button 2 was clicked by the user, it will display
“Option button 2 selected!” at the text field 2. And if Option button 3 was clicked by the
user, it will display “Option button 3 selected!” at the text field 3. Now if Option button 4
was clicked by the user, it will display “Option button 4 selected!”. This time, option
button and text field are in alternate order. Follow the design specification below:
151

Option 1

Option 2

Option button 2 selected!


Text field
Option 3

Option 4

11.Design and develop a Java applet that when the user clicks one of the three option
buttons, it will indicate in the text field on which option button the user had clicked. The
same thing also happened for the check boxes. For example, if Option button 1 was
clicked by the user, it will display “Option button 1 selected!” at the text field 2. If
Option button 2 was clicked by the user, it will display “Option button 2 selected!” at the
text field 2. And if Option button 3 was clicked by the user, it will display “Option button
3 selected!” at the text field 2. In the case of the check boxes, if Check box 1 was clicked
by the user, it will display “Check box 1 selected!” at the text field 1. If Check box 2 was
clicked by the user, it will display “Check box 2 selected!” at the text field 1. And if
Check box 3 was clicked by the user, it will display “Check box 3 selected!” at the text
field 1. Follow the design specification below:

Chk1 Chk2 Chk3

Check box 3 selected! Text field 1

Opt1 Opt2 Opt3

Option button 2 selected! Text field 2


152

The Java SE Application programming has Ended Here!

This is an official announcement that the Java SE Application programming task


(Solution 2) has ended here, permanently. All the examples in the next chapter will cover
entirely the Java Applet programming only. This is our focus right now. So, enjoy!
153

Chapter 4
Using Controls with Input/Output Functions

The ParseInt( ) and valueOf( ) Methods


In calculating and displaying data in our applet, we need to know how they can be
manipulated using the most important methods : ParseInt( ) and valueOf( ). These two
methods simply convert our data from numeric to string data or vise versa. The ParseInt(
) method converts the displayed data into numeric, while the valueOf( ) method converts
the displayed data into string data. The ParseInt( ) method is under the Java Integer class
that takes text string and returns a numeric integer value. For example, we can get the text
string in the text field txtText1 this way:

txtText1.getText( )

And we can convert that text string to a numeric integer value this way:

Integer.parseInt(txtText1.getText( ))

Now to convert a numeric value into a text string so that we can display it in the text
field, we need to apply the valueOf( ) method under the Java String class too. For
example, we can display the numeric value from the variable varArea this way:

varArea = 3.1416 * (varRadius*varRadius);


txtArea.setText(String.valueOf(varArea));

To explain it further, the parseInt ( ) method is applied when we want to calculate the
numeric integer data displayed in text field. Now if we want to display the computed data
into the text field, we need to convert it into a string using the valueOf( ) method. We
need to apply the parseInt ( ) method so that the numbers that are being entered in the text
field can be converted to numeric integer data for computation purposes in our equation
or formula, otherwise these numbers are treated as text string which cannot be calculated
or processed in the equation. We need also to convert the numeric data into its equivalent
text string data representation using the valueOf( ) method for the proper display of the
numbers into the text field control. Without doing so, it will result to an undesired output.
Let us have an example for this application, sooner.

Label control

In this chapter, I will introduce another useful and handy control which we will
use extensively in our upcoming programs. It is the Label control that displays read-only
text which main function is to provide information to the user. This can be in the form of
a message shown on the applet or a prompt. A message such as labeling an output data
154

of what it is, or telling the user what kind of data to input. This Label application is
usually with the conjunction of a text field that holds the input or output data. Like for
example, that the numeric output in the text box is the Area of a circle or a Fahrenheit
degree. Or simply telling the user to enter a numeric data for calculation or a character to
process. The Label as a prompt is usually combined with a a text field, scrolling list,
choice control, or other controls. It provides the user an idea of that nature of the
referenced control. For instance, if we had a scrolling list that contains the abbreviated
different states in America. We can put a label at the top of the scrolling list that tells
about the abbreviations.

Basic Data Types of Java

I’m also introducing here another important elements of our program. And it is
how to use variables and assigned a data type on it. A data type simply defines what type
of data a particular variable should hold or contain. Each piece of data is assigned a data
type. When we are designing and developing programs, we think about the name of
variables to use and decide what data type to assign to them. To explain it further, a data
type is a category of data. Each variable can only hold one type of data at a time. So
what is a variable? Variables are memory location (address) which we can assign a
specific name. For example we can name our variables as varNo, varSum or varArea.
We can assign or store a value(data) to the variable. Here are the basic data types of Java
programming language:

Data Type Meaning

int An integer data type is a whole number. This number could be positive or
negative. Examples: 9 -67 +978 3008

long Just a long integer data type that can accommodate more digits of data.

float A floating point data type is a number with fractional part or a number
with decimal point. Examples: 1.0 99.99 +2.54 -100

Double A double precision floating point value and can accommodate more digits
of data.

char A character data type is a single letter, a special symbol or digit that is
enclosed within a single quotation marks. Examples: ‘a’ ‘Z’ ‘*’ ‘%’
‘5’, ‘1’

String A string data type is a sequence of two or more characters that are
enclosed within a double quotation marks. Examples: “Ms” “I love you,
Bianca!” “PS”
155

Boolean A Boolean data type takes a true or false values. Examples:


Obj.setState(true)
new Obj(“Label 1”, GroupA, false)

byte Can only hold a byte of data or a tiny data.

Example 1:

Design and develop a Java applet that calculates the sum of two input numbers. Follow
the design specification below:

+ Command button
5 2 =

Text fields
Figure 3.1 An applet that adds two numbers

Text fields
Figure 3.1 An applet that adds two numbers

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class sum1 extends Applet implements ActionListener {
TextField txtNum1, txtNum2, txtSum;
Label lblPlus;
Button cmdEqual;
public void init() {
txtNum1 = new TextField(7);
add(txtNum1);
lblPlus = new Label("+");
add(lblPlus);
txtNum2 = new TextField(7);
add(txtNum2);
cmdEqual= new Button("=");
add(cmdEqual);
cmdEqual.addActionListener(this);
txtSum = new TextField(7);
add(txtSum);
}
156

public void actionPerformed(ActionEvent objEvent) {


int varSum=0;
if (objEvent.getSource() == cmdEqual) {
varSum = Integer.parseInt(txtNum1.getText()) +
Integer.parseInt(txtNum2.getText());
txtSum.setText(String.valueOf(varSum));
}
}
}

2. Then save the Java applet with the filename: sum1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>sum1</title>
</head>
<body>
<hr>
<applet
code=sum1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: sum1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac sum1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\sum1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>sum1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:
157

C:\javaprog>appletviewer sum1.htm (then press the Enter key)

Sample Output:

Figure 3.1a Applet that adds two numbers output

Explanation:

We place the plus sign (+) on the applet using the Label control as you can see in our
code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class sum1 extends Applet implements ActionListener {
TextField txtNum1, txtNum2, txtSum;
Label lblPlus;
Button cmdEqual;
.
.
.
The next thing we do is to initialize this label control in the init ( ) method, like the way
we do with other controls as you can observe in our code below:
.
.
.
public void init( ) {
txtNum1 = new TextField(7);
add(txtNum1);
lblPlus = new Label("+");
add(lblPlus);
158

txtNum2 = new TextField(7);


add(txtNum2);
cmdEqual= new Button("=");
add(cmdEqual);
cmdEqual.addActionListener(this);
txtSum = new TextField(7);
add(txtSum);
}
.
.
.
The label control will simply display text on the applet and nothing else. We can set the
text string of a label control the same way we do with the text field. And it is by using the
setText( ) method.
We can make the program to compute the sum of two input numbers by implementing
the ActionListener interface, and connect our command button (cmdEqual) to it. Then
finally add the actionPerformed ( ) method to complete the process:
.
.
.
public void actionPerformed(ActionEvent objEvent) {
int varSum=0;
if (objEvent.getSource() == cmdEqual) {
varSum = Integer.parseInt(txtNum1.getText( )) +
Integer.parseInt(txtNum2.getText( ));
txtSum.setText(String.valueOf(varSum));
}
}
}
.
.
.
When the command button (cmdEqual) is clicked, we instruct the computer to read the
numeric data entered by the user in the two text fields, txtNum1 and txtNum2. To read
the numeric data from the text field, we apply the getText( ) method such as the
following syntax:

txtNum1.getText( )

This syntax returns the text string in the text field, txtNum1. For example, if the user
inputs the data “5” in txtNum1 text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtNum1.getText( ))

In this way, we can now add the two numeric data entered by the user from text field 1
txtNum1 and text field txtNum2 and store the result to variable varSum. Now we need to
159

convert back the numeric value stored in the varSum into text string so that we can
display it to the text field
txtSum, using the valueOf( ) method under the String class of the Java language such as
the following syntax:

txtSum.setText(String.valueOf(varSum));

I think we have already gone too far for what we have learned. This is the right time to
learn more about these input/output functions of Java language to feel more comfortable
working with them.

Example 2:

Design and develop a Java applet that computes the area of a circle. Use the formula: A =
πr2 where Pi (π) is approximately equivalent to 3.1416. Follow the design specification
below:

Enter the radius: Text field 1


3

Compute Command button

Area of a circle: 28.2744 Text field 2

Figure 3.2 An applet that computes the area of a circle

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class area1 extends Applet implements ActionListener {
TextField txtRadius, txtArea;
Label lblRadius, lblArea;
Button cmdCompute;
public void init() {
lblRadius = new Label("Enter the radius:");
add(lblRadius);
txtRadius = new TextField(4);
add(txtRadius);
cmdCompute= new Button("Compute");
add(cmdCompute);
160

lblArea = new Label("Area of a circle:");


add(lblArea);
txtArea = new TextField(7);
add(txtArea);
cmdCompute.addActionListener(this);
}
public void actionPerformed(ActionEvent objEvent) {
int varRadius=0;
double varArea = 0;
if (objEvent.getSource() == cmdCompute) {
varRadius = Integer.parseInt(txtRadius.getText());
varArea = 3.1416 * (varRadius*varRadius);
txtArea.setText(String.valueOf(varArea));
}
}
}

2. Then save the Java applet with the filename: area1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>area1</title>
</head>
<body>
<hr>
<applet
code=area1.class
width=250
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: area1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac area1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\area1.htm
161

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>area1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer area1.htm (then press the Enter key)

Sample Output:

Figure 3.2a Applet that computes the area of a circle output

Explanation:

We place the label “Enter the radius:” and “Area of a circle:” on the applet using the
Label control as you can see in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class area1 extends Applet implements ActionListener {
TextField txtRadius, txtArea;
Label lblRadius, lblArea;
Button cmdCompute;
.
.
.
162

The next thing we do is to initialize these label controls in the init ( ) method, like the
way we do with other controls as you can observe in our code below:
.
.
.
public void init( ) {
lblRadius = new Label("Enter the radius:");
add(lblRadius);
txtRadius = new TextField(4);
add(txtRadius);
cmdCompute= new Button("Compute");
add(cmdCompute);
lblArea = new Label("Area of a circle:");
add(lblArea);
txtArea = new TextField(7);
add(txtArea);
cmdCompute.addActionListener(this);
}
.
.
.

The label control will simply display text on the applet and nothing else. We can set the
text string of a label control the same way we do with text field by using the setText( )
method.
We can make the program to compute the sum of two input numbers by implementing
the ActionListener interface, and connect our command button (cmdCompute) to it. Then
finally add the actionPerformed ( ) method to complete the process:
.
.
.
public void actionPerformed(ActionEvent objEvent) {
int varRadius=0;
double varArea = 0;
if (objEvent.getSource( ) == cmdCompute) {
varRadius = Integer.parseInt(txtRadius.getText( ));
varArea = 3.1416 * (varRadius*varRadius);
txtArea.setText(String.valueOf(varArea));
}
}
}
.
.
.
When the command button Compute (cmdCompute) is clicked, we instruct the computer
to read the numeric data entered by the user in the text field, txtRadius. To read the
numeric data from the text field, we apply the getText( ) method such as the following
syntax:

txtRadius.getText( )
163

This syntax returns the text string in the text field, txtRadius. For example, if the user
inputs the data “3” in txtRadius text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtRadius.getText( ))

In this way, we can now calculate the numeric data of the radius entered by the user from
text field txtRadius and store it to variable varRadius. We can now use the stored value
of the variable varRadius in our equation since it is already a numeric data using the
following equation:

varArea = 3.1416 * (varRadius*varRadius);

Now we need to convert back the numeric value stored in the varArea into text string so
that we can display it to the text field txtArea, using the valueOf( ) method under the
String class of the Java language such as the following syntax:

txtArea.setText(String.valueOf(varArea));

You will notice here that we increase the applet’s width to 250 and decrease the height to
150 (as you can see in the HTML script below), because we want to accommodate the
label “Enter the radius:” , the text field used for entering the data and command button
Compute (cmdCompute) to be displayed in the applet within the same line. With this
adjustment, these three controls will be displayed in the applet properly, as well as the
controls that follow.
.
.
.
<applet
code=area1.class
width=250
height=150>
</applet>
.
.
.

Example 3:

Design and develop a Java applet that computes the average of three input quizzes. Then
display the result. Follow the design specification below:
164

Enter three quizzes:


Text fields
91 88 67

Compute Command button

The average quiz is: 82.0 Text field

Figure 3.3 Applet that computes the average

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class average1 extends Applet implements ActionListener {
TextField txtQuiz1, txtQuiz2, txtQuiz3, txtAve;
Label lblQuiz, lblAve;
Button cmdCompute;
public void init() {
lblQuiz = new Label("Enter three quizzes:");
add(lblQuiz);
txtQuiz1 = new TextField(3);
add(txtQuiz1);
txtQuiz2 = new TextField(3);
add(txtQuiz2);
txtQuiz3 = new TextField(3);
add(txtQuiz3);
cmdCompute= new Button("Compute");
add(cmdCompute);
lblAve = new Label("The average quiz is:");
add(lblAve);
txtAve = new TextField(7);
add(txtAve);
cmdCompute.addActionListener(this);
}
public void actionPerformed(ActionEvent objEvent) {
int varQuiz1, varQuiz2, varQuiz3;
double varAve = 0;
if (objEvent.getSource() == cmdCompute) {
varQuiz1 = Integer.parseInt(txtQuiz1.getText());
varQuiz2 = Integer.parseInt(txtQuiz2.getText());
varQuiz3 = Integer.parseInt(txtQuiz3.getText());
varAve = (varQuiz1+varQuiz2+varQuiz3)/3;
txtAve.setText(String.valueOf(varAve));
}
}
}
165

2. Then save the Java applet with the filename: average1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>average1</title>
</head>
<body>
<hr>
<applet
code=average1.class
width=150
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: average1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac average1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\average1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>average1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer average1.htm (then press the Enter key)

Sample Output:
166

Figure 3.3a Applet that computes the average output

Explanation:

We place the label “Enter three quizzes:” on the applet using the Label control as you can
see in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class average1 extends Applet implements ActionListener {
TextField txtQuiz1, txtQuiz2, txtQuiz3, txtAve;
Label lblQuiz, lblAve;
Button cmdCompute;
.
.
.
The next thing we do is to initialize these label controls in the init ( ) method, like the
way we do with other controls as you can observe in our code below:
.
.
.
public void init( ) {
lblQuiz = new Label("Enter three quizzes:");
add(lblQuiz);
txtQuiz1 = new TextField(3);
add(txtQuiz1);
txtQuiz2 = new TextField(3);
add(txtQuiz2);
txtQuiz3 = new TextField(3);
add(txtQuiz3);
cmdCompute= new Button("Compute");
167

add(cmdCompute);
lblAve = new Label("The average quiz is:");
add(lblAve);
txtAve = new TextField(7);
add(txtAve);
cmdCompute.addActionListener(this);
}
.
.
.
The label control will simply display text on the applet and nothing else. We can set the
text string of a label control the same way we do with text field by using the setText( )
method.
We can make the program to compute the sum of two input numbers by implementing
the ActionListener interface, and connect our command button (cmdCompute) to it. Then
finally add the actionPerformed ( ) method to complete the process:
.
.
.
public void actionPerformed(ActionEvent objEvent) {
int varQuiz1, varQuiz2, varQuiz3;
double varAve = 0;
if (objEvent.getSource() == cmdCompute) {
varQuiz1 = Integer.parseInt(txtQuiz1.getText( ));
varQuiz2 = Integer.parseInt(txtQuiz2.getText( ));
varQuiz3 = Integer.parseInt(txtQuiz3.getText( ));
varAve = (varQuiz1+varQuiz2+varQuiz3)/3;
txtAve.setText(String.valueOf(varAve));
}
}
}

When the command button Compute (cmdCompute) is clicked, we instruct the computer
to read the numeric data entered by the user in the three text fields, txtQuiz1, txtQuiz2,
and txtQuiz3. To read the numeric data from the text field, we apply the getText( )
method such as the following syntax:

txtQuiz1.getText( )

This syntax returns the text string in the text field, txtQuiz1. For example, if the user
inputs the data “91” in txtQuiz1 text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtQuiz1.getText( ))

In this way, we can now calculate the numeric data of the quiz 1 entered by the user from
text field txtQuiz1 and store it to variable varQuiz1. We can now use the stored value of
168

the variable varQuiz1 (as well as varQuiz2 and varQuiz3) in our equation since it is
already a numeric data using the following equation:

varAve = (varQuiz1+varQuiz2+varQuiz3)/3;

Now we need to convert back the numeric value stored in the varAve into text string so
that we can display it to the text field txtAve, using the valueOf( ) method under the
String class of the Java language such as the following syntax:

txtAve.setText(String.valueOf(varAve));

You will notice here that we decrease the applet’s width to 150 and decrease the height to
150 (as you can see in the HTML script below), because we want to accommodate the
label “Enter three quizzes:”, to be displayed at the top portion in the applet then followed
by the text fields used for entering the three quizzes in the second line and command
button Compute (cmdCompute) to be displayed right below the three text fields, then
followed by the next label, “The average is:” and finally the last text field which is used
to display the computed average quiz. With this adjustment, these controls will be
displayed in the applet properly.
.
.
.
<applet
code=average1.class
width=150
height=150>
</applet>
.
.
.

Example 4:

Design and develop a Java applet that converts the input value of Celsius into its
equivalent Fahrenheit degree. Use the formula: F = (9/5) * C + 32. Then display the
result. Follow the design specification below:

Enter the Celsius: 19 Text field 1

Compute Command button

91.8 Text field 2


Fahrenheit conversion is:

Figure 3.4 An applet that converts Celsius to Fahrenheit


169

Solution:

1. At the Microsoft NotePad, write the following code:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class degree1 extends Applet implements ActionListener {
TextField txtCelsius, txtFahrenheit;
Label lblCelsius, lblFahrenheit;
Button cmdCompute;
public void init() {
lblCelsius = new Label("Enter the Celsius:");
add(lblCelsius);
txtCelsius = new TextField(4);
add(txtCelsius);
cmdCompute= new Button("Compute");
add(cmdCompute);
cmdCompute.addActionListener(this);
lblFahrenheit = new Label("Fahrenheit conversion is:");
add(lblFahrenheit);
txtFahrenheit = new TextField(8);
add(txtFahrenheit);
}
public void actionPerformed(ActionEvent objEvent) {
int varCelsius=0;
double varFahrenheit = 0;
if (objEvent.getSource() == cmdCompute) {
varCelsius = Integer.parseInt(txtCelsius.getText());
varFahrenheit = (9.0/5.0) * (varCelsius + 32.0);
txtFahrenheit.setText(String.valueOf(varFahrenheit));
}
}
}

2. Then save the Java applet with the filename: degree1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>degree1</title>
</head>
<body>
<hr>
<applet
code=degree1.class
width=250
height=150>
</applet>
<hr>
170

</body>
</html>

4. Now save the HTML script with the filename: degree1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac degree1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\degree1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>degree1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer degree1.htm (then press the Enter key)

Sample Output:

Figure 3.4a Applet that converts Celsius to Fahrenheit output


171

Explanation:

We place the label “Enter the Celsius:” and “The Fahrenheit conversion is:” on the applet
using the Label control as you can see in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class degree1 extends Applet implements ActionListener {
TextField txtCelsius, txtFahrenheit;
Label lblCelsius, lblFahrenheit;
Button cmdCompute;
.
.
.
The next thing we do is to initialize these label controls in the init ( ) method, like the
way we do with other controls as you can observe in our code below:
.
.
.
public void init( ) {
lblCelsius = new Label("Enter the Celsius:");
add(lblCelsius);
txtCelsius = new TextField(4);
add(txtCelsius);
cmdCompute= new Button("Compute");
add(cmdCompute);
cmdCompute.addActionListener(this);
lblFahrenheit = new Label("Fahrenheit conversion is:");
add(lblFahrenheit);
txtFahrenheit = new TextField(8);
add(txtFahrenheit);
}
.
.
.

The label control will simply display text on the applet and nothing else. We can set the
text string of a label control the same way we do with text field by using the setText( )
method.
We can make the program to compute the sum of two input numbers by implementing
the ActionListener interface, and connect our command button (cmdCompute) to it. Then
finally add the actionPerformed ( ) method to complete the process:
.
.
.
public void actionPerformed(ActionEvent objEvent) {
int varCelsius=0;
double varFahrenheit = 0;
if (objEvent.getSource( ) == cmdCompute) {
172

varCelsius = Integer.parseInt(txtCelsius.getText( ));


varFahrenheit = (9.0/5.0) * (varCelsius + 32.0);
txtFahrenheit.setText(String.valueOf(varFahrenheit));
}
}
}

When the command button Compute (cmdCompute) is clicked, we instruct the computer
to read the numeric data entered by the user in the text field, txtCelsius. To read the
numeric data from the text field, we apply the getText( ) method such as the following
syntax:

txtCelsius.getText( )

This syntax returns the text string in the text field, txtCelsius. For example, if the user
inputs the data “19” in txtCelsius text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtCelsius.getText( ))

In this way, we can now calculate the numeric data of the radius entered by the user from
text field txtCelsius and store it to variable varCelsius. We can now use the stored value
of the variable varCelsius in our equation since it is already a numeric data using the
following equation:

varFahrenheit = (9.0/5.0) * (varCelsius + 32.0);

Now we need to convert back the numeric value stored in the varFahrenheit into text
string so that we can display it to the text field txtFahrenheit, using the valueOf( )
method under the String class of the Java language such as the following syntax:

txtFahrenheit.setText(String.valueOf(varFahrenheit)

You will notice here that we increase the applet’s width to 250 and decrease the height to
150 (as you can see in the HTML script below), because we want to accommodate the
label “Enter the Celsius:” , the text field used for entering the data and command button
Compute (cmdCompute) to be displayed in the applet within the same line. With this
adjustment, these three controls will be displayed in the applet properly, as well as the
controls that follow.
.
.
.
<applet
code=degree1.class
width=250
height=150>
</applet>
.
173

LAB ACTIVITY
TEST 3

1. Design and develop a Java applet that calculates the difference of two input numbers.
Follow the design specification below:

Command button
5 3 =

3 Text fields

2. Design and develop a Java applet that calculates the product of two input numbers.
Follow the design specification below:

Command button
5 2 =
*

10

3 Text fields
174

3. Design and develop a Java applet that calculates the quotient of two input numbers.
Follow the design specification below:

Command button
5 / 2 =

2.5

3 Text fields

4. Design and develop a Java applet that computes the volume of a sphere. Use the
formula: V = 4/3 πr3 where Pi (π) is approximately equivalent to 3.1416.
Follow the design specification below:

Enter the radius: Command button


3 Compute

The sphere is: 113.0976

2 Text fields

5. Design and develop a Java applet that converts the input inch(es) into its equivalent
centimeters. One inch is equivalent to 2.54 cms. Follow the design specification below:

Enter the iches:


4 Convert
Command button
Centimeter convesion is:
10.16

2 Text fields
175

5. Design and develop a Java applet that converts the input dollar(s) into its
equivalent peso rate. One dollar is equivalent to 56.47 pesos. Follow the design
specification below:

Enter the dollars: Command button


3 Convert

Peso rate convesion is: 169.41

2 Text fields

7. Design and develop a Java applet that converts the input Fahrenheit into its equivalent
Celsius degree. Use the formula: C = (5/9) * F - 32. Follow the design specification
below:

Enter the Fahrenheit: Command button


125 Convert

Celsius equivalent is: 51.667

Text fields

8. Design and develop a Java applet that computes the Depreciation cost of the item (D).
Takes as input the purchase Price of an item (P), its expected number of years of Service
(S), and Yearly depreciation for the item (Y).
Use the formula: D=P-S /Y. Follow the design specification below:

Price Service Yearly Depreciation

80 5 4 Text boxes 1,2, & 3

Compute Command button

Text box 4
The Depreciation is: 18.75
176

Note:
After the user enters the purchase Price of an item (P), its expected number of years of
Service (S), and Yearly depreciation for the item (Y) at text fields 1,2 & 3, the user
should click the Command button (with a Compute caption) before the resulting
computed value will be displayed at the text field 4.

9. Design and develop a Java applet that determines the most economical quantity to be
stocked for each product that a manufacturing company has in its inventory. This quantity
called economic order quantity (EOQ) is calculated as follows:

EOQ = sqrt( 2RS/I)

where:
R = total yearly production Requirement
S = Set Up Cost per order
I = Inventory Carrying Cost per unit

Follow the design specification below:

Requirement Set Up Cost Inventory

4 100 20 Text fields

Compute Command button

Economic order quantity: 6.324 Text field

Note:
After the user enters the total year production Requirement (R), its Set up cost per
order (S), and Inventory carrying cost per unit (I) at text fields 1,2 & 3, the user should
click the Command button (with a Compute caption) before the resulting computed value
will be displayed at the text field 4.

Hint:
Use the Math.sqrt( ) mathematical function to solve this Lab activity with all variables
should be declared using Double data type.

For example:
.
.
double varResul=0;
double varNum1, varNum2, varNum3;
varResult = Math.sqrt((varNum1*2)(varNum2/varNum3))
177

Chapter 5
Arranging and Organizing Controls

The GridLayout Manager


By far, we were just using the Flow Layout Manager in all our previous examples,
whether we like it or not. Because in Java programming, by default, this Flow Layout
Manager is utilized by the Java compiler once we put the controls in our applet. To
explain it further, this Flow Layout manager simply places the controls in A program one
by one, wrapping them at the end of a row; while in the GridLayout Manager, it places
the controls in a grid to arrange the controls vertically and add them to our applet. This is
also the main reason why we keep on adjusting the width and height of our applet in the
HTML script to accommodate the controls in order to be displayed properly. However,
this is but just a quick fix in our part. In other words, with the default Flow Layout
Manager, we have no other way on where to place the controls wherever we want to
display them on the applet. Using the GridLayout Manager, we can place the control to
any parts of the applet, though we need to add some laborious code in our Java program.
Well, it’s worth the effort.

Example 1:

Using the GridLayout Manager, design and develop a Java applet that multiplies the two
input numbers. Follow the design specification below (in a grid form):

Blank1 Blank2
5
Blank3 Blank4
*
Blank5 Blank6
7
Space1 Space2 Space3

Blank7 Blank8
Compute
Space4 Space5 Space6

Blank9 Blank10
35

Figure 4.1 An applet that multiplies two input numbers using GridLayout
178

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class multiply1 extends Applet implements ActionListener {
TextField txtNum1, txtNum2, txtProduct;
Label lblAsterisk, lblBlank1, lblBlank2,lblBlank3,lblBlank4,
lblBlank5,lblBlank6,lblBlank7,lblBlank8,lblBlank9,lblBlank10;
Label lblSpace1, lblSpace2, lblSpace3, lblSpace4, lblSpace5,
lblSpace6;
Button cmdCompute;
public void init() {
setLayout( new GridLayout(9,3));
lblBlank1 = new Label();
add(lblBlank1);
txtNum1 = new TextField(5);
add(txtNum1);
lblBlank2 = new Label();
add(lblBlank2);
lblBlank3 = new Label();
add(lblBlank3);
lblAsterisk = new Label("*",Label.CENTER);
add(lblAsterisk);
lblBlank4 = new Label();
add(lblBlank4);
lblBlank5 = new Label();
add(lblBlank5);
txtNum2 = new TextField(5);
add(txtNum2);
lblBlank6 = new Label();
add(lblBlank6);
lblSpace1 = new Label();
add(lblSpace1);
lblSpace2 = new Label();
add(lblSpace2);
lblSpace3 = new Label();
add(lblSpace3);
lblBlank7 = new Label();
add(lblBlank7);
cmdCompute = new Button("Compute");
add(cmdCompute);
cmdCompute.addActionListener(this);
lblBlank8 = new Label();
add(lblBlank8);
lblSpace4 = new Label();
add(lblSpace4);
lblSpace5 = new Label();
add(lblSpace5);
lblSpace6 = new Label();
add(lblSpace6);
lblBlank9 = new Label();
add(lblBlank9);
txtProduct = new TextField(8);
179

add(txtProduct);
lblBlank10 = new Label();
add(lblBlank10);
}
public void actionPerformed (ActionEvent objEvent) {
int varNum1, varNum2, varProduct;
if (objEvent.getSource()==cmdCompute) {
varNum1 = Integer.parseInt(txtNum1.getText());
varNum2 = Integer.parseInt(txtNum2.getText());
varProduct = varNum1 * varNum2;
txtProduct.setText(String.valueOf(varProduct));
}
}
}

2. Then save the Java applet with the filename: multiply1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>multiply1</title>
</head>
<body>
<hr>
<applet
code=multiply1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: multiply1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac multiply1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\multiply1.htm

Or, alternatively, you can type the following line at the MS-DOS command:
180

C:\javaprog>multiply1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer multiply1.htm (then press the Enter key)

Sample Output:

Figure 4.1a Applet that multiplies two input numbers using GridLayout output

Explanation:

You will notice here in our code below that we declare so many labels. We need these set
of labels without any text on them to act as space allocator in our applet. They will serve
to fill the blank entries in our 9x3 grid.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class multiply1 extends Applet implements ActionListener {
TextField txtNum1, txtNum2, txtProduct;
Label lblAsterisk, lblBlank1, lblBlank2,lblBlank3,lblBlank4,
lblBlank5,lblBlank6,lblBlank7,lblBlank8,lblBlank9,lblBlank10;
Label lblSpace1, lblSpace2, lblSpace3, lblSpace4, lblSpace5,
lblSpace6;
Button cmdCompute;
.
.
.
181

This time, we need to install the GridLayout manager in our applet and add the controls
on it, by setting it up with the setLayOut( ) method. We can accomplish this task in the
init( ) method as shown below:
.
.
.
public void init( ) {
setLayout( new GridLayout(9,3));
lblBlank1 = new Label( );
add(lblBlank1);
txtNum1 = new TextField(5);
add(txtNum1);
lblBlank2 = new Label( );
add(lblBlank2);
lblBlank3 = new Label( );
add(lblBlank3);
lblAsterisk = new Label("*",Label.CENTER);
add(lblAsterisk);
lblBlank4 = new Label( );
add(lblBlank4);
lblBlank5 = new Label( );
add(lblBlank5);
txtNum2 = new TextField(5);
add(txtNum2);
lblBlank6 = new Label( );
add(lblBlank6);
lblSpace1 = new Label();
add(lblSpace1);
lblSpace2 = new Label( );
add(lblSpace2);
lblSpace3 = new Label( );
add(lblSpace3);
lblBlank7 = new Label( );
add(lblBlank7);
cmdCompute = new Button("Compute");
add(cmdCompute);
cmdCompute.addActionListener(this);
lblBlank8 = new Label( );
add(lblBlank8);
lblSpace4 = new Label( );
add(lblSpace4);
lblSpace5 = new Label( );
add(lblSpace5);
lblSpace6 = new Label( );
add(lblSpace6);
lblBlank9 = new Label( );
add(lblBlank9);
txtProduct = new TextField(8);
add(txtProduct);
lblBlank10 = new Label();
182

add(lblBlank10);
}
.
.
.
Take note also that to place the asterisk symbol in the middle of its label, we include the
class constant Label.CENTER in the call to the constructor of the Label class, with the
following syntax:
lblAsterisk = new Label("*",Label.CENTER);
We can make the program to compute the product of two input numbers by
implementing the ActionListener interface, and connect our command button
(cmdCompute) to it. Then finally add the actionPerformed ( ) method to complete the
process:
.
.
.
public void actionPerformed (ActionEvent objEvent) {
int varNum1, varNum2, varProduct;
if (objEvent.getSource()==cmdCompute) {
varNum1 = Integer.parseInt(txtNum1.getText( ));
varNum2 = Integer.parseInt(txtNum2.getText( ));
varProduct = varNum1 * varNum2;
txtProduct.setText(String.valueOf(varProduct));
}
}
}

When the command button (cmdCompute) is clicked, we instruct the computer to read
the numeric data entered by the user in the two text fields, txtNum1 and txtNum2. To
read the numeric data from the text field, we apply the getText( ) method such as the
following syntax:

txtNum1.getText( )

This syntax returns the text string in the text field, txtNum1. For example, if the user
inputs the data “5” in txtNum1 text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtNum1.getText( ))

In this way, we can now multiply the two numeric data entered by the user from text field
1 txtNum1 and text field txtNum2 and storing the result to variable varProduct. Now we
need to convert back the numeric value stored in the varProduct into its equivalent text
string so that we can display it to the text field, txtProduct using the valueOf( ) method
under the String class of the Java language. Here is its command syntax below:

txtProduct..setText(String.valueOf(varProduct))
183

Example 2:

Using the GridLayout Manager, design and develop a Java applet that multiplies the two
input numbers. This time, we have to put label messages “1st No.” on Blank1, “2nd No.”
on Blank5, and “Answer:” on Blank9. Follow the design specification below (in a grid
form):

Blank1 Blank2
5

Blank3 Blank4
*

Blank5 Blank6
7

Space1 Space2 Space3

Blank7 Blank8
Compute
Space4 Space5 Space6

Blank9 Blank10
35

Figure 4.2 An applet that multiplies two input numbers using GridLayout Part 2

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class multiply2 extends Applet implements ActionListener {
TextField txtNum1, txtNum2, txtProduct;
Label lblAsterisk, lblBlank1, lblBlank2,lblBlank3,lblBlank4,
lblBlank5,lblBlank6,lblBlank7,lblBlank8,lblBlank9,lblBlank10;
Label lblSpace1, lblSpace2, lblSpace3, lblSpace4, lblSpace5,
lblSpace6;
Button cmdCompute;
public void init() {
setLayout( new GridLayout(9,3));
lblBlank1 = new Label("1st No.");
add(lblBlank1);
txtNum1 = new TextField(5);
add(txtNum1);
lblBlank2 = new Label();
add(lblBlank2);
184

lblBlank3 = new Label();


add(lblBlank3);
lblAsterisk = new Label("*",Label.CENTER);
add(lblAsterisk);
lblBlank4 = new Label();
add(lblBlank4);
lblBlank5 = new Label("2nd No.");
add(lblBlank5);
txtNum2 = new TextField(5);
add(txtNum2);
lblBlank6 = new Label();
add(lblBlank6);
lblSpace1 = new Label();
add(lblSpace1);
lblSpace2 = new Label();
add(lblSpace2);
lblSpace3 = new Label();
add(lblSpace3);
lblBlank7 = new Label();
add(lblBlank7);
cmdCompute = new Button("Compute");
add(cmdCompute);
cmdCompute.addActionListener(this);
lblBlank8 = new Label();
add(lblBlank8);
lblSpace4 = new Label();
add(lblSpace4);
lblSpace5 = new Label();
add(lblSpace5);
lblSpace6 = new Label();
add(lblSpace6);
lblBlank9 = new Label("Answer:");
add(lblBlank9);
txtProduct = new TextField(8);
add(txtProduct);
lblBlank10 = new Label();
add(lblBlank10);
}
public void actionPerformed (ActionEvent objEvent) {
int varNum1, varNum2, varProduct;
if (objEvent.getSource()==cmdCompute) {
varNum1 = Integer.parseInt(txtNum1.getText());
varNum2 = Integer.parseInt(txtNum2.getText());
varProduct = varNum1 * varNum2;
txtProduct.setText(String.valueOf(varProduct));
}
}
}

2. Then save the Java applet with the filename: multiply2.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
185

<title>multiply2</title>
</head>
<body>
<hr>
<applet
code=multiply2.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: multiply2.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac multiply2.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\multiply2.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>multiply2.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer multiply2.htm (then press the Enter key)

Sample Output:
186

Figure 4.2a An applet that multiplies two input numbers using


GridLayout Part 2 output

Explanation:

You will notice here in our code below that we declare so many labels. We need these set
of labels without any text on them to act as space allocator in our applet. They will serve
to fill the blank entries in our 9x3 grid.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class multiply2 extends Applet implements ActionListener {
TextField txtNum1, txtNum2, txtProduct;
Label lblAsterisk, lblBlank1, lblBlank2,lblBlank3,lblBlank4,
lblBlank5,lblBlank6,lblBlank7,lblBlank8,lblBlank9,lblBlank10;
Label lblSpace1, lblSpace2, lblSpace3, lblSpace4, lblSpace5,
lblSpace6;
Button cmdCompute;
.
.
.
This time, we need to install the GridLayout manager in our applet and add the controls
on it, by setting it up with the setLayOut( ) method. We can accomplish this task in the
init( ) method as shown below:
.
.
.
public void init( ) {
setLayout( new GridLayout(9,3));
187

lblBlank1 = new Label("1st No.");


add(lblBlank1);
txtNum1 = new TextField(5);
add(txtNum1);
lblBlank2 = new Label( );
add(lblBlank2);
lblBlank3 = new Label( );
add(lblBlank3);
lblAsterisk = new Label("*",Label.CENTER);
add(lblAsterisk);
lblBlank4 = new Label( );
add(lblBlank4);
lblBlank5 = new Label("2nd No.");
add(lblBlank5);
txtNum2 = new TextField(5);
add(txtNum2);
lblBlank6 = new Label( );
add(lblBlank6);
lblSpace1 = new Label( );
add(lblSpace1);
lblSpace2 = new Label( );
add(lblSpace2);
lblSpace3 = new Label( );
add(lblSpace3);
lblBlank7 = new Label( );
add(lblBlank7);
cmdCompute = new Button("Compute");
add(cmdCompute);
cmdCompute.addActionListener(this);
lblBlank8 = new Label( );
add(lblBlank8);
lblSpace4 = new Label( );
add(lblSpace4);
lblSpace5 = new Label( );
add(lblSpace5);
lblSpace6 = new Label( );
add(lblSpace6);
lblBlank9 = new Label("Answer:");
add(lblBlank9);
txtProduct = new TextField(8);
add(txtProduct);
lblBlank10 = new Label( );
add(lblBlank10);
}
.
.
.
We simply put label messages “1st No.” on Blank1, “2nd No.” on Blank5, and “Answer:”
on Blank9, as you can observe in our code above.
188

We can make the program to compute the product of two input numbers by
implementing the ActionListener interface, and connect our command button
(cmdCompute) to it. Then finally add the actionPerformed ( ) method to complete the
process:
.
.
.
public void actionPerformed (ActionEvent objEvent) {
int varNum1, varNum2, varProduct;
if (objEvent.getSource()==cmdCompute) {
varNum1 = Integer.parseInt(txtNum1.getText( ));
varNum2 = Integer.parseInt(txtNum2.getText( ));
varProduct = varNum1 * varNum2;
txtProduct.setText(String.valueOf(varProduct));
}
}
}

When the command button (cmdCompute) is clicked, we instruct the computer to read
the numeric data entered by the user in the two text fields, txtNum1 and txtNum2. To
read the numeric data from the text field, we apply the getText( ) method such as the
following syntax:

txtNum1.getText( )

This syntax returns the text string in the text field, txtNum1. For example, if the user
inputs the data “5” in txtNum1 text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtNum1.getText( ))

In this way, we can now multiply the two numeric data entered by the user from text field
1 txtNum1 and text field txtNum2 and storing the result to variable varProduct. Now we
need to convert back the numeric value stored in the varProduct into its equivalent text
string so that we can display it to the text field, txtProduct using the valueOf( ) method
under the String class of the Java language. Here is its command syntax below:

txtProduct..setText(String.valueOf(varProduct))

Example 3:

Using the GridLayout Manager, Design and develop a Java applet that converts the input
value of Celsius into its equivalent Fahrenheit degree. Use the formula: F = (9/5) * C +
32. Then display the result. Follow the design specification below (in a grid form):
189

Enter Celsius: Blank1


5

Space1 Space2 Space3

Blank2 Blank3
Convert

Space4 Space5 Space6

Fahrenheit: Blank4
66.60

Figure 4.3 An applet that converts Celsius to Fahrenheit using GridLayout

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class degree2 extends Applet implements ActionListener {
TextField txtCelsius, txtFahrenheit;
Label lblCelsius, lblFahrenheit;
Label lblBlank1, lblBlank2,lblBlank3,lblBlank4;
Label lblSpace1,lblSpace2, lblSpace3, lblSpace4, lblSpace5,
lblSpace6;
Button cmdConvert;
public void init() {
setLayout( new GridLayout(7,3));
lblCelsius = new Label("Enter Celsius:");
add(lblCelsius);
txtCelsius = new TextField(5);
add(txtCelsius);
lblBlank1 = new Label();
add(lblBlank1);
lblSpace1 = new Label();
add(lblSpace1);
lblSpace2 = new Label();
add(lblSpace2);
lblSpace3 = new Label();
add(lblSpace3);
lblBlank2 = new Label();
add(lblBlank2);
190

cmdConvert = new Button("Convert");


add(cmdConvert);
cmdConvert.addActionListener(this);
lblBlank3 = new Label();
add(lblBlank3);
lblSpace4 = new Label();
add(lblSpace4);
lblSpace5 = new Label();
add(lblSpace5);
lblSpace6 = new Label();
add(lblSpace6);
lblFahrenheit = new Label("Fahrenheit:");
add(lblFahrenheit);
txtFahrenheit = new TextField(8);
add(txtFahrenheit);
lblBlank4 = new Label();
add(lblBlank4);
}
public void actionPerformed (ActionEvent objEvent) {
int varCelsius;
double varFahrenheit;
if (objEvent.getSource()==cmdConvert) {
varCelsius = Integer.parseInt(txtCelsius.getText());
varFahrenheit = (9.0/5.0)* (varCelsius + 32.0);
txtFahrenheit.setText(String.valueOf(varFahrenheit));
}
}
}

2. Then save the Java applet with the filename: degree2.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>degree2</title>
</head>
<body>
<hr>
<applet
code=degree2.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: degree2.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


191

C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac degree2.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\degree2.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>degree2.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer degree2.htm (then press the Enter key)

Figure 4.3a An applet that converts Celsius to Fahrenheit


using GridLayout ouput

Explanation:

You will notice here in our code below that we declare so many labels. We need these set
of labels without any text on them to act as space allocator in our applet. They will serve
to fill the blank entries in our 7x3 grid.

import java.applet.Applet;
import java.awt.*;
192

import java.awt.event.*;
public class degree2 extends Applet implements ActionListener {
TextField txtCelsius, txtFahrenheit;
Label lblCelsius, lblFahrenheit;
Label lblBlank1, lblBlank2,lblBlank3,lblBlank4;
Label lblSpace1,lblSpace2, lblSpace3, lblSpace4, lblSpace5,
lblSpace6;
Button cmdConvert;
.
.
.
This time, we need to install the GridLayout manager in our applet and add the controls
on it, by setting it up with the setLayOut( ) method. We can accomplish this task in the
init( ) method as shown below:
.
.
.
public void init( ) {
setLayout( new GridLayout(7,3));
lblCelsius = new Label("Enter Celsius:");
add(lblCelsius);
txtCelsius = new TextField(5);
add(txtCelsius);
lblBlank1 = new Label( );
add(lblBlank1);
lblSpace1 = new Label( );
add(lblSpace1);
lblSpace2 = new Label( );
add(lblSpace2);
lblSpace3 = new Label( );
add(lblSpace3);
lblBlank2 = new Label( );
add(lblBlank2);
cmdConvert = new Button("Convert");
add(cmdConvert);
cmdConvert.addActionListener(this);
lblBlank3 = new Label( );
add(lblBlank3);
lblSpace4 = new Label( );
add(lblSpace4);
lblSpace5 = new Label( );
add(lblSpace5);
lblSpace6 = new Label( );
add(lblSpace6);
lblFahrenheit = new Label("Fahrenheit:");
add(lblFahrenheit);
txtFahrenheit = new TextField(8);
add(txtFahrenheit);
lblBlank4 = new Label( );
add(lblBlank4);
193

}
.
.
.
We can make the program to convert the input Celsius degree into its equivalent
Fahrenheit degree by implementing the ActionListener interface, and connect our
command button (cmdConvert) to it. Then finally add the actionPerformed ( ) method to
complete the process:
.
.
.
public void actionPerformed (ActionEvent objEvent) {
int varCelsius;
double varFahrenheit;
if (objEvent.getSource( )==cmdConvert) {
varCelsius = Integer.parseInt(txtCelsius.getText( ));
varFahrenheit = (9.0/5.0)* (varCelsius + 32.0);
txtFahrenheit.setText(String.valueOf(varFahrenheit));
}
}
}
.
.
.
When the command button (cmdConvert) is clicked, we instruct the computer to read the
numeric data entered by the user in text field 1, txtCelsius. To read the numeric data from
the text field, we apply the getText( ) method such as the following syntax:

txtCelsius.getText( )

This syntax returns the text string in the text field, txtCelsius. For example, if the user
inputs the data “5” in txtCelsius text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtCelsius.getText( ))

In this way, we can now store the entered numeric data from txtCelsius and store the
result to variable varCelsius. This time, we can use the numeric data from varCelsius for
our equation to get the convertion into the Fahrenheit degree with the following syntax:

varFahrenheit = (9.0/5.0)* (varCelsius + 32.0);

Now we need to convert back the numeric value stored in the varFahrenheit into its
equivalent text string so that we can display it to the text field, txtFahrenheit using the
valueOf( ) method under the String class of the Java language. Here is its command
syntax below:

txtProduct.setText(String.valueOf(varProduct))
194

Now this time, I’m sure we are pretty well knowledgeable on how to use the GridLayout
Manager to arrange the displayed controls in our applet. With this skill, we can continue
learning more on how to arrange the controls using the Panels. This is our topic for the
next example. So be ready now!

The Panel Class


Another way of arranging controls is using the Panel class. A panel is a rectangular
region that contains a group of control such as check boxes or option buttons. Let us have
now the examples to learn it in action.

Example 4:

Using a Panel, design and develop a Java applet that contains two panels for two groups
of check boxes. Follow the design specification below:

Check 1 Check 1

Check 2 Check 2

Check 3 Check 3

Figure 4.4 An applet with check boxes panels

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
public class checkpanel1 extends Applet {
Checkboxpanel panPanel1, panPanel2;
public void init() {
setLayout(new GridLayout(1,2));
panPanel1 = new Checkboxpanel();
panPanel2 = new Checkboxpanel();
add(panPanel1);
add(panPanel2);
}
}
class Checkboxpanel extends Panel {
Checkbox chkBox1, chkBox2, chkBox3;
195

Checkboxpanel() {
chkBox1 = new Checkbox("Check 1");
add(chkBox1);
chkBox2 = new Checkbox("Check 2");
add(chkBox2);
chkBox3 = new Checkbox("Check 3");
add(chkBox3);
}
}

2. Then save the Java applet with the filename: checkpanel1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>checkpanel1</title>
</head>
<body>
<hr>
<applet
code=checkpanel1.class
width=150
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: checkpanel1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac checkpanel1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\checkpanel1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>checkpanel1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:
196

C:\javaprog>appletviewer checkpanel1.htm (then press the Enter key)

Figure 4.4a An applet with check boxes panels output

Explanation:

First, we have to create the check box panel by deriving it from the Java language Panel
class as shown in our code below:

import java.applet.Applet;
import java.awt.*;
public class checkpanel1 extends Applet {
Checkboxpanel panPanel1, panPanel2;
.
.
.
Since we need two panels for our two groups of checkboxes, that is why we declared the
two panels which we named: panPanel1, and panPanel2.
Next, we have to initialize these two panels in the init( ) method. We will apply the
GridLayout manager with 1 row and 2 columns to make these panels appear side by side,
as you can see in the following code:
.
.
.
public void init( ) {
setLayout(new GridLayout(1,2));
panPanel1 = new Checkboxpanel( );
panPanel2 = new Checkboxpanel( );
add(panPanel1);
add(panPanel2);
}
}
197

.
.
.
Lastly, we have to create and add the new check boxes to this panel. We can accomplish
this task in the constructor method of the Panel class:
.
.
.
class Checkboxpanel extends Panel {
Checkbox chkBox1, chkBox2, chkBox3;
Checkboxpanel( ) {
chkBox1 = new Checkbox("Check 1");
add(chkBox1);
chkBox2 = new Checkbox("Check 2");
add(chkBox2);
chkBox3 = new Checkbox("Check 3");
add(chkBox3);
}
}

Unlike in our previous examples, we always create and add the new check boxes in the
init( ) method . In the Panel class, creating and adding the check boxes in the init( )
method is not supported. The constructor method has the same name with its associated
class and it is automatically run when an object of the class is created.

Example 5:

Using a Panel, design and develop a Java applet that contains two panels for two groups
of option buttons. Follow the design specification below:

Option 1 Option 1

Option 2 Option 2

Option 3 Option 3

Figure 4.5 An applet with option buttons panels

Solution:

1. At the Microsoft NotePad, write the following code:


198

import java.applet.Applet;
import java.awt.*;
public class optionpanel1 extends Applet {
Optionbuttonpanel panPanel1, panPanel2;
public void init() {
setLayout(new GridLayout(1,2));
panPanel1 = new Optionbuttonpanel();
panPanel2 = new Optionbuttonpanel();
add(panPanel1);
add(panPanel2);
}
}
class Optionbuttonpanel extends Panel {
CheckboxGroup optGroup;
Checkbox optButton1, optButton2, optButton3;
Optionbuttonpanel() {
optGroup = new CheckboxGroup();
add(optButton1 = new Checkbox("Option 1",optGroup,false));
add(optButton2 = new Checkbox("Option 2",optGroup,false));
add(optButton3 = new Checkbox("Option 3",optGroup,false));
}
}

2. Then save the Java applet with the filename: optionpanel1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>optionpanel1</title>
</head>
<body>
<hr>
<applet
code=optionpanel1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: optionpanel1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:
199

C:\JAVAPROG>javac optionpanel1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\optionpanel1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>optionpanel1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer optionpanel1.htm (then press the Enter key)

Figure 4.5a Applet with option buttons panels output

Explanation:

First, we have to create the option button panel by deriving it from the Java language
Panel class as shown in our code below:

import java.applet.Applet;
import java.awt.*;
public class optionpanel1 extends Applet {
Optionbuttonpanel panPanel1, panPanel2;
.
.
.
Since we need two panels for our two groups of option buttons, we declared the two
panels which we named: panPanel1, and panPanel2.
200

Next, we have to initialize these two panels in the init( ) method. We will apply the
GridLayout manager with 1 row and 2 columns to make these panels appear side by side,
as you can see in the following code:
.
.
.
public void init( ) {
setLayout(new GridLayout(1,2));
panPanel1 = new Optionbuttonpanel( );
panPanel2 = new Optionbuttonpanel( );
add(panPanel1);
add(panPanel2);
}
}
.
.
.
Lastly, we have to create and add the new option buttons to this panel. We can
accomplish this task in the constructor method of the Panel class:
.
.
.
class Optionbuttonpanel extends Panel {
CheckboxGroup optGroup;
Checkbox optButton1, optButton2, optButton3;
Optionbuttonpanel( ) {
optGroup = new CheckboxGroup( );
add(optButton1 = new Checkbox("Option 1",optGroup,false));
add(optButton2 = new Checkbox("Option 2",optGroup,false));
add(optButton3 = new Checkbox("Option 3",optGroup,false));
}
}
.
.
.
Unlike in our previous examples, we always create and add the new option buttons in the
init( ) method . In the Panel class, creating and adding the option buttons in the init( )
method is not supported. The constructor method has the same name with its associated
class and it is automatically run when an object of the class is created.
201

LAB ACTIVITY
TEST 4

1. Using the GridLayout Manager, design and develop a Java applet that adds the
two input numbers. We have to put label messages “1st No.” on Blank1, “2nd
No.” on Blank5, and “Answer:” on Blank9. Follow the design specification below
(in a grid form):

Blank1 Blank2
5
Blank3 Blank4
+

Blank5 Blank6
7

Space1 Space2 Space3

Blank7 Blank8
Add
Space4 Space5 Space6

Blank9 Blank10
12

2. Using the GridLayout Manager, design and develop a Java applet that subtracts
the two input numbers. We have to put label messages “1st No.” on Blank1, “2nd
No.” on Blank5, and “Answer:” on Blank9. Follow the design specification below
(in a grid form):

Blank1 Blank2
7

Blank3 Blank4
_-

Blank5 Blank6
4

Space1 Space2 Space3

Blank7 Blank8
Subtract

Space4 Space5 Space6

Blank9 Blank10
3
202

3. Using the GridLayout Manager, design and develop a Java applet that divides the
two input numbers. We have to put label messages “1st No.” on Blank1, “2nd
No.” on Blank5, and “Answer:” on Blank9. Follow the design specification below
(in a grid form):

Blank1 Blank2
5
Blank3 Blank4
/
Blank5 Blank6
2
Space1 Space2 Space3

Blank7 Blank8
Divide
Space4 Space5 Space6

Blank9 Blank10
2.5

4. Using the GridLayout Manager, design and develop a Java applet that converts
the input value of Fahrenheit into its equivalent Celsius degree. Use the formula:
C = (5/9) * F - 32. Then display the result. Follow the design specification below
(in a grid form):

Fahrenheit: Blank1
125

Space1 Space2 Space3

Blank2 Blank3
Convert

Space4 Space5 Space6

Celsius: Blank4
51.667
203

5. Using the GridLayout Manager, design and develop a Java applet that converts
the input dollar(s) into its equivalent peso rate. One dollar conversion is 56.47
pesos. Follow the design specification below (in a grid form):

Enter dollar(s): Blank1


3

Space1 Space2 Space3

Blank2 Blank3
Convert

Space4 Space5 Space6

Peso rate: Blank4


169.41

6.Using the GridLayout Manager, design and develop a Java applet that converts the
input inch(es) into its equivalent centimeters. One inch is equivalent to 2.54 cms. Follow
the design specification below (in a grid form):

Enter Inch(es): Blank1


4

Space1 Space2 Space3

Blank2 Blank3
Convert

Space4 Space5 Space6

Centimeters: Blank4
10.16

7.Using the GridLayout Manager, design and develop a Java applet that computes the
volume of a sphere. Use the formula: V = 4/3 πr3 where Pi (π) is approximately
equivalent to 3.1416. Follow the design specification below (in a grid form):
204

Enter the radius: Blank1


3

Space1 Space2 Space3

Blank2 Blank3
Compute

Space4 Space5 Space6

The Sphere is: Blank4


113.0976

8. Using a Panel, design and develop a Java applet that contains two panels for two
groups of check boxes. Follow the design specification below:

Check 1 Check 1

Check 2 Check 2

Check 3 Check 3

Check 4 Check 4

9. Using a Panel, design and develop a Java applet that contains two panels for two
groups of option buttons. Follow the design specification below:

Option 1 Option 1

Option 2 Option 2

Option 3 Option 3

Option 4 Option 4
205

10. Using a Panel, design and develop a Java applet that contains two panels for
three groups of check boxes. Follow the design specification below:

Check 1 Check 1 Check 1

Check 2 Check 2 Check 2

Check 3 Check 3 Check 3

11. Using a Panel, design and develop a Java applet that contains two panels for
three groups of option buttons. Follow the design specification below:

Option 1 Option 1 Option 1

Option 2 Option 2 Option 2

Option 3 Option 3 Option 3


206

Chapter 6
Using Controls with Conditional Statements

Computers can make decisions based on given condition. This condition can be evaluated
whether true or false. The computer will act appropriately based on the result of the
evaluation. In most cases, the conditions are conditional expressions with the application
of relational operators and logical operators.

if-else if Syntax

The if-else if control construct allows the computer to evaluate three or more conditional
statements, but to execute only one associated statement which is the statement of the
first conditional expression that is evaluated to True. In other words, use the if-else if
control structure to define several blocks of statements, one of which will execute. Its
general syntax is:

if condition1 {
Statement1 associated statement
}
else if condition2 {
Statement2
}
else if condition3 {
Statement3
}
.
.
.
else {
Statementn
}

The Java language will evaluate first the condition1. If it is False, the Java language’s
invisible program pointer will proceed to evaluate condition2, and so on, until it finds a
True condition. When True condition is found, only then that its associated statement will
be executed. We can also add the else conditional statement as the option to choose in the
if-else if conditional statement. This will provide a way to catch some impossible to meet
conditions or the “none of the above” situation. We may use the else statement for error-
checking, sometimes.
207

switch/case Syntax
The switch/case conditional statement is an alternative to if-else if conditional statement.
With the use of switch/case statement, we can simplify some of the code that are tedious,
long, and cumbersome when we use the if-else if statement. In other words, the
switch/case can be the best substitute conditional statement to write a clearer and concise
multi-way decision program compared to the messy if-else if statement. Here is the
switch/case general syntax:

switch (var_expression) {
case value_expression1:
Statement1 associated statement
case value_expression2:
Statement2
case value_expression3:
Statement3
default:
Statementn
}

Like in the rules of if-else if statement, if more than one case matches the var_expression,
only the statement associated with the first matching case will be executed. The default
statement will be executed if none of the values in the above expression list matches the
var_expression.
It acts like else statement in if-else if conditional statement. It is an optional statement
too.
We have to take note also that although the switch/case statement is the best substitute
for the if/else if statement, it has an inherent limitations. For example, we cannot apply
the relational operators that are mixed with logical operators such as less than (<), greater
than (>), less than or equal to (<=), greater than or equal to (>=), not equal (<>) logical ||
(or) and logical && (and) operators. We cannot say:

case >0 || case <100


Or
case >0 && case <100

This is a syntax error. Instead, we have to rewrite the code in switch/case format which
in many cases look so very different from the if/else if syntax and yet produce the same
result.
It takes you to learn deeply the switch/case syntax and its limitations and capabilities
before you can successfully convert your if-else if code into its switch/case equivalent.
Otherwise, you would have a hard time converting an if- else if code into switch/case
code. Let us now have our examples for these conditional statements.
208

Example 1:

Design and develop a Java applet that determines if the input number at Text field 1 is
equivalent to the magic words: “I love you” or not. Display the result “I love you!” at the
Text field 2 if the input number is 143, and “Wrong guess!” if it is not. Follow the design
specification below:

Text field 1

Enter the magic number: Button


143 Execute

I love you! Text field 2

Figure 5.1 An applet that determines a magic number

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class magicno1 extends Applet implements ActionListener {
TextField txtMNumber, txtMessage;
Label lblMNumber;
Button cmdExecute;
public void init() {
lblMNumber = new Label("Enter the magic number:");
add(lblMNumber);
txtMNumber = new TextField(4);
add(txtMNumber);
cmdExecute = new Button("Execute");
add(cmdExecute);
cmdExecute.addActionListener(this);
txtMessage = new TextField(19);
add(txtMessage);
}
public void actionPerformed(ActionEvent objE) {
int varMNumber=0;
if (objE.getSource() == cmdExecute) {
varMNumber= Integer.parseInt(txtMNumber.getText());
if (varMNumber==143)
txtMessage.setText("I love you!");
else
209

txtMessage.setText("Wrong guess!");
}
}
}

2. Then save the Java applet with the filename: magicno1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:

<html>
<!- Web page written with Java Applet>
<head>
<title>magicno1</title>
</head>
<body>
<hr>
<applet
code=magicno1.class
width=250
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: magicno1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac magicno1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\magicno1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>magicno1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer magicno1.htm (then press the Enter key)


210

Sample Output:

Figure 5.1a Applet that determines a magic number output

Explanation:

We created a new class named magicno1 here in our program. Then we declared the two
text fields which we named txtMNumber and txtMessage. We used the txtMNumber
object to get the number entered by the user, while the txtMessage object is used to
display the message in the second text field. The label lblMNumber is declared using
Java Label class and the command button cmdExecute is declared using the Button class
as you can see in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class magicno1 extends Applet implements ActionListener {
TextField txtMNumber, txtMessage;
Label lblMNumber;
Button cmdExecute;
.
.
.

You will notice that we actually created and add the objects we had declared at the top of
our program here in the init( ) method:
.
.
.
public void init( ) {
lblMNumber = new Label("Enter the magic number:");
add(lblMNumber);
txtMNumber = new TextField(4);
211

add(txtMNumber);
cmdExecute = new Button("Execute");
add(cmdExecute);
cmdExecute.addActionListener(this);
txtMessage = new TextField(19);
add(txtMessage);
}
.
.
.
We can make the program to determine if the input number of the user at text field 1
(txtMNumber) is a magic number by implementing the ActionListener interface, and
connect our command button cmdExecute to it. Then finally add the actionPerformed ( )
method to complete the process:

public void actionPerformed(ActionEvent objE) {


int varMNumber=0;
if (objE.getSource( ) == cmdExecute) {
varMNumber= Integer.parseInt(txtMNumber.getText( ));
if (varMNumber==143)
txtMessage.setText("I love you!");
else
txtMessage.setText("Wrong guess!");
}
}
}

When the command button cmdExecute is clicked, we instruct the computer to read the
numeric data entered by the user in text field 1, txtMNumber. To read the numeric data
from the text field, we apply the getText( ) method such as the following syntax:

txtMNumber.getText( )

This syntax returns the text string in the text field, txtMNumber. For example, if the user
inputs the data “143” in txtMNumber text field, this is actually a text string value. We
need to convert it to its equivalent numeric value using the parseInt( ) method under the
Integer class of the Java language such as the following syntax:

Integer.parseInt(txtMNumber.getText( ))

In this way, we can now store the entered numeric data from txtMNumber and store the
result to variable varMNumber. This time we can use the numeric data of varMNumber
to be evaluated if it is equal to 143 which is the equivalent of the magic number, using
the following syntax:

if (varMNumber==143)
txtMessage.setText("I love you!");
else
txtMessage.setText("Wrong guess!");
212

Now if the conditional expression is evaluated to true, then its associated statement

txtMessage.setText("I love you!")

will be executed. Otherwise, the associated statement of the else conditional statement:

txtMessage.setText("Wrong guess!")

will be executed instead.


Remember that here in our program, we use an outer if statement and inner if statement.
The outer if statement:

if (objE.getSource( ) == cmdExecute)

simply tests if the cmdExecute button was clicked by the user. And if it is indeed
clicked, its associated statements will be executed. It happened that its associated
statements contain an inner
if:

if (varMNumber==143)

which is also being tested. This further means that the inner if conditional statement can
have a chance to be executed only if and only if the outer if conditional statement is
evaluated or tested as true first. Otherwise, there is no way for it to be executed. This is
how the outer and inner ifs work technically.

You will notice here that we increase the applet’s width to 250 and decrease the height to
150 (as you can see in the HTML script below), because we want to accommodate the
label “Enter the magic number:” , the text field used for entering the data and command
button Execute (cmdExecute) to be displayed in the applet within the same line. With
this adjustment, these three controls will be displayed in the applet properly, as well as
the controls that follow.
.
.
.
<applet
code=magicno1.class
width=250
height=150>
</applet>
.
.
.
213

Example 2:

Design and develop a Java applet that determines if the input number at Text field 1 is a
positive or negative. Consider 0 as positive number. Follow the design specification
below:

Text field 1

Enter a number: -5

Execute Button

It is a Negative number! Text field 2

Figure 5.2 An applet that determines if a number is positive or negative

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class positive1 extends Applet implements ActionListener {
TextField txtNumber, txtMessage;
Label lblNumber;
Button cmdExecute;
public void init() {
lblNumber = new Label("Enter a number:");
add(lblNumber);
txtNumber = new TextField(6);
add(txtNumber);
cmdExecute = new Button("Execute");
add(cmdExecute);
cmdExecute.addActionListener(this);
txtMessage = new TextField(19);
add(txtMessage);
}
public void actionPerformed(ActionEvent objE) {
int varNumber=0;
if (objE.getSource() == cmdExecute) {
varNumber= Integer.parseInt(txtNumber.getText());
if (varNumber>=0)
txtMessage.setText("It is a Positive number!");
else
txtMessage.setText("It is a Negative number!");
}
214

}
}

2. Then save the Java applet with the filename: positive1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:

<html>
<!- Web page written with Java Applet>
<head>
<title>positive1</title>
</head>
<body>
<hr>
<applet
code=positive1.class
width=200
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: positive1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac positive1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\positive1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>positive1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer positive1.htm (then press the Enter key)


215

Sample Output:

Figure 5.2a Applet that determines if a number is positive or negative output

Explanation:

We created a new class named positive1 here in our program. Then we declared the two
text fields which we named txtNumber and txtMessage. We used the txtNumber object
to get the number entered by the user, while the txtMessage object is used to display the
message in the second text field. The label lblNumber is declared using Java Label
class and the command button cmdExecute is declared using the Button class as you can
see in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class positive1 extends Applet implements ActionListener {
TextField txtNumber, txtMessage;
Label lblNumber;
Button cmdExecute;
.
.
.
You will notice that we actually created and add the objects we had declared at the top of
our program here in the init( ) method:
.
.
.
216

public void init( ) {


lblNumber = new Label("Enter a number:");
add(lblNumber);
txtNumber = new TextField(6);
add(txtNumber);
cmdExecute = new Button("Execute");
add(cmdExecute);
cmdExecute.addActionListener(this);
txtMessage = new TextField(19);
add(txtMessage);
}
.
.
.
We can make the program to determine if the input number of the user at text field 1
(txtNumber) is positive or negative number by implementing the ActionListener
interface, and connect our command button cmdExecute to it. Then finally add the
actionPerformed ( ) method to complete the process:
.
.
.
public void actionPerformed(ActionEvent objE) {
int varNumber=0;
if (objE.getSource( ) == cmdExecute) {
varNumber= Integer.parseInt(txtNumber.getText( ));
if (varNumber>=0)
txtMessage.setText("It is a Positive number!");
else
txtMessage.setText("It is a Negative number!");
}
}
}

When the command button cmdExecute is clicked, we instruct the computer to read the
numeric data entered by the user in text field 1, txtNumber. To read the numeric data
from the text field, we apply the getText( ) method such as the following syntax:

txNumber.getText( )

This syntax returns the text string in the text field, txtNumber. For example, if the user
inputs the data “-5” in txtNumber text field, this is actually a text string value. We need
to convert it to its equivalent numeric value using the parseInt( ) method under the
Integer class of the Java language such as the following syntax:

Integer.parseInt(txtNumber.getText( ))

In this way, we can now store the entered numeric data from txtNumber and store the
result to variable varNumber. This time we can use the numeric data of varNumber to be
217

evaluated if it is equal to or greater than zero (varNumber>=0) which is our process to


determine a positive number, using the following syntax:

if (varNumber>=0)
txtMessage.setText("It is a Positive number!");
else
txtMessage.setText("It is a Negative number!");

Now if the conditional expression is evaluated to true, then its associated statement

txtMessage.setText("It is a Positive number!")

will be executed. Otherwise, the associated statement of the else conditional statement:

txtMessage.setText("It is a Negative number!")

will be executed instead.


Remember that here in our program, we use an outer if statement and inner if statement.
The outer if statement:

if (objE.getSource( ) == cmdExecute)

simply tests if the cmdExecute button was clicked by the user. And if it is indeed
clicked, its associated statements will be executed. It happened that its associated
statements contain an inner if:

if (varNumber>=0)

which is also being tested. This further means that the inner if conditional statement can
have a chance to be executed only if and only if the outer if conditional statement is
evaluated or tested as true first. Otherwise, there is no way for it to be executed. This is
how the outer and inner ifs work technically.

You will notice here that we decrease the height to 150 (as you can see in the HTML
script below), because we want to position the label “Enter a number:” and the text field
used for entering the data at the top of our applet, then position the command button
Execute (cmdExecute) below it. With this adjustment, the controls will be displayed in
the applet properly, in accordance to the required design specification.
.
.
.
<applet
code=positive1.class
width=200
height=150>
</applet>
.
.
.
218

Example 3:

Design and develop a Java program to display the high school level of a student, based
on its year-entry number. For example, the year-entry 1 means the student is freshman, 2
for sophomore, and so on. Here is the given criteria:

Year-entry number High-School Level

1 Freshman
2 Sophomore
3 Junior
4 Senior
Other no. Out-Of-Range

Follow the design specification below:

Text field 1

Enter the Year-entry level: 2 Execute


Button

The High-School Level is: Sophomore Text field 2

Figure 5.3 An applet that displays a high-school level

1st Solution: (using if - else if conditional statements)

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class school1 extends Applet implements ActionListener {
TextField txtYear, txtMessage;
Label lblYear,lblMessage;
Button cmdExecute;
public void init() {
lblYear = new Label("Enter the Year-entry number:");
add(lblYear);
txtYear = new TextField(3);
add(txtYear);
cmdExecute = new Button("Execute");
219

add(cmdExecute);
cmdExecute.addActionListener(this);
lblMessage = new Label("The High-School Level is:");
add(lblMessage);
txtMessage = new TextField(17);
add(txtMessage);
}
public void actionPerformed(ActionEvent objE) {
int varYear;
if (objE.getSource() == cmdExecute) {
varYear = Integer.parseInt(txtYear.getText());
if (varYear==1)
txtMessage.setText("Freshman");
else if (varYear==2)
txtMessage.setText("Sophomore");
else if (varYear==3)
txtMessage.setText("Junior");
else if (varYear==4)
txtMessage.setText("Senior");
else
txtMessage.setText("Out-Of-Range");
}
}
}

2. Then save the Java applet with the filename: school1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>school1</title>
</head>
<body>
<hr>
<applet
code=school1.class
width=300
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: school1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:
220

C:\JAVAPROG>javac school1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\school1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>schoo1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer school1.htm (then press the Enter key)

Sample Output:

Figure 5.3a Applet that displays a high-school level output


(using if-else if conditional statement solution)

Explanation:

We created a new class named school1 here in our program. Then we declared the two
text fields which we named txtYear and txtMessage. We used the txtYear object to get
the year-entry number entered by the user, while the txtMessage object is used to display
the message in the second text field. The label lblYear and lblMessage are declared using
Java Label class and the command button cmdExecute is declared using the Button class
as you can see in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class school1 extends Applet implements ActionListener {
TextField txtYear, txtMessage;
221

Label lblYear,lblMessage;
Button cmdExecute;
.
.
.

You will notice that we actually created and add the objects we had declared at the top of
our program here in the init( ) method:
.
.
.
public void init( ) {
lblYear = new Label("Enter the Year-entry number:");
add(lblYear);
txtYear = new TextField(3);
add(txtYear);
cmdExecute = new Button("Execute");
add(cmdExecute);
cmdExecute.addActionListener(this);
lblMessage = new Label("The High-School Level is:");
add(lblMessage);
txtMessage = new TextField(17);
add(txtMessage);
}
.
.
.
We can make our program to determine the year-entry level of the student at text field 1
(txtYear) by implementing the ActionListener interface, and connect our command
button cmdExecute to it. Then finally add the actionPerformed ( ) method to complete the
process:
.
.
.
public void actionPerformed(ActionEvent objE) {
int varYear;
if (objE.getSource( ) == cmdExecute) {
varYear = Integer.parseInt(txtYear.getText( ));
if (varYear==1)
txtMessage.setText("Freshman");
else if (varYear==2)
txtMessage.setText("Sophomore");
else if (varYear==3)
txtMessage.setText("Junior");
else if (varYear==4)
txtMessage.setText("Senior");
else
txtMessage.setText("Out-Of-Range");
}
}
222

When the command button cmdExecute is clicked, we instruct the computer to read the
numeric data entered by the user in text field 1, txtYear. To read the numeric data from
the text field, we apply the getText( ) method such as the following syntax:

txtYear.getText( )

This syntax returns the text string in the text field, txtYear. For example, if the user
inputs the data “2” in txtYear text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtYear.getText( ))

In this way, we can now store the entered numeric data from txtYear and store the
result to variable varYear:

varYear = Integer.parseInt(txtYear.getText( ))

This time we can use the numeric data of varYear to be evaluated if it is equal to 1
(varYear==1) which is our process to determine the year-entry level of the student, using
the following syntax:

if (varYear==1)
txtMessage.setText("Freshman");

Now if the conditional expression is evaluated to true, then its associated statement

txtMessage.setText("Freshman")

will be executed. Otherwise, the other else if conditional statements:

else if (varYear==2)
txtMessage.setText("Sophomore");
else if (varYear==3)
txtMessage.setText("Junior");
else if (varYear==4)
txtMessage.setText("Senior");
else
txtMessage.setText("Out-Of-Range");

will be the next to be evaluated or tested. Now if one of them are evaluated to True, then
its corresponding associated statement will be executed. For example, the year-entry
number entered by the user is 2, then the following else if conditional statement is
evaluated to True:

else if (varYear==2)
txtMessage.setText("Sophomore");
223

thus, the output to be displayed is “Sophomore”.


In the if-else if syntax, after finding a True evaluation for a particular conditional
statement, the Java program compiler will jump right to the end of the if statement, thus
ending the evaluation or testing process. In other words, the remaining conditions below
it will no longer be evaluated or tested ( or simply ignored). Technically, this will save
much microprocessor’s processing power compared to using all ifs conditional statements
in our program. Meaning, using the if statement all throughout instead of else if
statement. With the if statement, all conditional statements will be evaluated or tested,
regardless of how many True evaluations found at the upper part of the conditional block.
This makes very taxing to the microprocessor’s processing power. In other words, the
following code is not advisable to use (since there is only one option to be selected by our
Java program to comply with the given requirement):

if (varYear==1)
txtMessage.setText("Freshman");
if (varYear==2)
txtMessage.setText("Sophomore");
if (varYear==3)
txtMessage.setText("Junior");
if (varYear==4)
txtMessage.setText("Senior");

Notice all the conditional statements pointed by the arrows. It contained all ifs. It’s bad in
programming. There are cases or situations in real-world application that we have no
other choice but to use all the ifs statements throughout in our program (like the one you
see above), however such cases or situations rarely occur. So use all ifs statements with
utmost care, okay?

2nd Solution: (using the switch/case conditional statement)

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class school2 extends Applet implements ActionListener {
TextField txtYear, txtMessage;
Label lblYear,lblMessage;
Button cmdExecute;
public void init() {
lblYear = new Label("Enter the Year-entry number:");
add(lblYear);
txtYear = new TextField(3);
add(txtYear);
cmdExecute = new Button("Execute");
add(cmdExecute);
cmdExecute.addActionListener(this);
lblMessage = new Label("The High-School Level is:");
add(lblMessage);
224

txtMessage = new TextField(17);


add(txtMessage);
}
public void actionPerformed(ActionEvent objE) {
int varYear;
if (objE.getSource() == cmdExecute) {
varYear = Integer.parseInt(txtYear.getText());
switch(varYear) {
case 1:
txtMessage.setText("Freshman");
break;
case 2:
txtMessage.setText("Sophomore");
break;
case 3:
txtMessage.setText("Junior");
break;
case 4:
txtMessage.setText("Senior");
break;
default:
txtMessage.setText("Out-Of-Range");
}
}
}
}

2. Then save the Java applet with the filename: school2.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>school2</title>
</head>
<body>
<hr>
<applet
code=school2.class
width=300
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: school2.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)
225

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac school2.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\school2.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>school2.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer school2.htm (then press the Enter key)

Sample Output:

Figure 5.3b Applet that displays a high-school level output


(case/switch conditional statement solution)

Explanation:

We created a new class named school2 here in our program. Then we declared the two
text fields which we named txtYear and txtMessage. We used the txtYear object to get
the year-entry entered by the user, while the txtMessage object is used to display the
message in the second text field. The label lblYear and lblMessage are declared using
Java Label class and the command button cmdExecute is declared using the Button class
as you can see in our code below:

import java.applet.Applet;
226

import java.awt.*;
import java.awt.event.*;
public class school2 extends Applet implements ActionListener {
TextField txtYear, txtMessage;
Label lblYear,lblMessage;
Button cmdExecute;
.
.
.
You will notice that we actually created and add the objects we had declared at the top of
our program here in the init( ) method:
.
.
.
public void init( ) {
lblYear = new Label("Enter the Year-entry number:");
add(lblYear);
txtYear = new TextField(3);
add(txtYear);
cmdExecute = new Button("Execute");
add(cmdExecute);
cmdExecute.addActionListener(this);
lblMessage = new Label("The High-School Level is:");
add(lblMessage);
txtMessage = new TextField(17);
add(txtMessage);
}
.
.
.
We can make our program to determine the year-entry level of the student at text field 1
(txtYear) by implementing the ActionListener interface, and connect our command
button cmdExecute to it. Then finally add the actionPerformed ( ) method to complete the
process:

public void actionPerformed(ActionEvent objE) {


int varYear;
if (objE.getSource( ) == cmdExecute) {
varYear = Integer.parseInt(txtYear.getText( ));
switch(varYear) {
case 1:
txtMessage.setText("Freshman");
break;
case 2:
txtMessage.setText("Sophomore");
break;
case 3:
txtMessage.setText("Junior");
break;
case 4:
227

txtMessage.setText("Senior");
break;
default:
txtMessage.setText("Out-Of-Range");
}
}
}
}

When the command button cmdExecute is clicked, we instruct the computer to read the
numeric data entered by the user in text field 1, txtYear. To read the numeric data from
the text field, we apply the getText( ) method such as the following syntax:

txtYear.getText( )

This syntax returns the text string in the text field, txtYear. For example, if the user
inputs the data “2” in txtYear text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtYear.getText( ))

In this way, we can now store the entered numeric data from txtYear and store the
result to variable varYear:

varYear = Integer.parseInt(txtYear.getText( ))

In switch/case conditional statement, we have to pass varGrade variable to switch


statement using the following syntax:

switch (varYear)

The switch (varYear) command holds the value of the variable varYear for testing,
evaluation, or comparison with the given value_expression of each case or group of
cases.
Once the match is found (means the value of variable varYear is the same with the
value_expression found) then the program pointer will search the associated statement
and execute it. For example, if we enter the value of 2 at the text field txtYear, the
program pointer will execute the associated statement:

txtMessage.setText("Sophomore");

since this value_expression can be found at the second case label. When the value
entered does not match to any value_expression listed, the associated statement of default
is executed instead. If the default is not included (since it is optional), then nothing will
be executed.
You will observe that all the associated statements are followed by the break command.
228

This break command will trigger the program pointer to break out from the whole
switch/case (statement) block. Meaning, it jumps to the statement that follows the end ( }
) symbol of switch/case statement. This makes our switch/case solution to act and
execute like the way if / else if / else do. It’s like ignoring all the remaining conditional
statements and expressions below when there is already a true-evaluation at the top. In
short, the break statement causes an immediate exit from the switch/case (statement)
block.

Example 4:

Design and develop a Java applet that will assist a teacher in converting a range of
numerical grade into its equivalent letter form grade, based on the given scale.

Range Grade

90 - 100 A
80 - 89 B
70 - 79 C
60 - 69 D
50 - 59 F
other grades I (for Invalid)

Follow the design specification below:

Text field 1

Enter your grade: 94 Button


Execute

Your grade in letter form is: A Text field 2

Figure 5.4 An applet that converts a grade into a letter form

1st Solution: (using if - else if conditional statements)

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class grade1 extends Applet implements ActionListener {
229

TextField txtGrade, txtMessage;


Label lblGrade,lblMessage;
Button cmdExecute;
public void init() {
lblGrade = new Label("Enter a grade:");
add(lblGrade);
txtGrade = new TextField(3);
add(txtGrade);
cmdExecute = new Button("Execute");
add(cmdExecute);
cmdExecute.addActionListener(this);
lblMessage = new Label("Your grade in letter for is:");
add(lblMessage);
txtMessage = new TextField(4);
add(txtMessage);
}
public void actionPerformed(ActionEvent objE) {
int varGrade=0;
if (objE.getSource() == cmdExecute) {
varGrade = Integer.parseInt(txtGrade.getText());
if ((varGrade>=90) && (varGrade<=100))
txtMessage.setText("A");
else if ((varGrade>=80) && (varGrade<=89))
txtMessage.setText("B");
else if ((varGrade>=70) && (varGrade<=79))
txtMessage.setText("C");
else if ((varGrade>=60) && (varGrade<=69))
txtMessage.setText("D");
else if ((varGrade>=50) && (varGrade<=59))
txtMessage.setText("F");
else
txtMessage.setText(“I”);
}
}
}

2. Then save the Java applet with the filename: grade1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:

<html>
<!- Web page written with Java Applet>
<head>
<title>grade1</title>
</head>
<body>
<hr>
<applet
code=grade1.class
width=250
height=150>
</applet>
<hr>
</body>
230

</html>

4. Now save the HTML script with the filename: grade1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac grade1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\grade1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>grade1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer grade1.htm (then press the Enter key)

Sample Output:

Figure 5.4a Applet that converts a grade into a letter form output
(using the if-else if conditional statements)
231

Explanation:

We created a new class named grade1 here in our program. Then we declared the two
text fields which we named txtGrade and txtMessage. We used the txtGrade object to get
the grade entered by the user, while the txtMessage object is used to display the message
in the second text field. The label lblGrade is declared using Java Label class and the
command button cmdExecute is declared using the Button class as you can see in our
code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class grade1 extends Applet implements ActionListener {
TextField txtGrade, txtMessage;
Label lblGrade,lblMessage;
Button cmdExecute;
.
.
.

You will notice that we actually created and add the objects we had declared at the top of
our program here in the init( ) method:
.
.
.
public void init( ) {
lblGrade = new Label("Enter a grade:");
add(lblGrade);
txtGrade = new TextField(3);
add(txtGrade);
cmdExecute = new Button("Execute");
add(cmdExecute);
cmdExecute.addActionListener(this);
lblMessage = new Label("Your grade in letter for is:");
add(lblMessage);
txtMessage = new TextField(4);
add(txtMessage);
}
.
.
.
We can make our program to determine the equivalent letter form grade of the input
numeric grade of the user at text field 1 (txtGrade) by implementing the ActionListener
interface, and connect our command button cmdExecute to it. Then finally add the
actionPerformed ( ) method to complete the process:
.
232

.
.
public void actionPerformed(ActionEvent objE) {
int varGrade=0;
if (objE.getSource( ) == cmdExecute) {
varGrade = Integer.parseInt(txtGrade.getText( ));
if ((varGrade>=90) && (varGrade<=100))
txtMessage.setText("A");
else if ((varGrade>=80) && (varGrade<=89))
txtMessage.setText("B");
else if ((varGrade>=70) && (varGrade<=79))
txtMessage.setText("C");
else if ((varGrade>=60) && (varGrade<=69))
txtMessage.setText("D");
else if (varGrade>=50) && (varGrade<=59))
txtMessage.setText("F");
else
txtMessage.setText(“I”);
}
}
}

When the command button cmdExecute is clicked, we instruct the computer to read the
numeric data entered by the user in text field 1, txtGrade. To read the numeric data from
the text field, we apply the getText( ) method such as the following syntax:

txGrade.getText( )

This syntax returns the text string in the text field, txtGrade. For example, if the user
inputs the data “94” in txtGrade text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtGrade.getText( ))

In this way, we can now store the entered numeric data from txtGrade and store the
result to variable varGrade. This time we can use the numeric data of varGrade to be
evaluated if it is equal to or greater than 90 (varGrade>=90) which is our process to
determine what is its equivalent in letter form grade, using the following syntax:

if ((varGrade>=90) && (varGrade<=100))


txtMessage.setText("A");

Now if the conditional expression is evaluated to true, then its associated statement

txtMessage.setText("A")

will be executed. Otherwise, the other else if conditional statements:

else if ((varGrade>=80) && (varGrade<=89))


233

txtMessage.setText("B");
else if ((varGrade>=70) && (varGrade<=79))
txtMessage.setText("C");
else if ((varGrade>=60) && (varGrade<=69))
txtMessage.setText("D");
else if (varGrade>=50) && (varGrade<=59))
txtMessage.setText("F");
else
txtMessage.setText(“I”);

will be the next to be evaluated or tested. Now if one of them is evaluated to True, then
its corresponding associated statement will be executed. For example, the grade entered
by the user is 78, and since this grade falls between the range of 70 to 79, therefore the
following else if conditional statement is evaluated to True:

else if ((varGrade>=70) && (varGrade<=79))


txtMessage.setText("C");

thus, the output to be displayed is “C”. To explain it further how the above code works
(as well as the others), let us learn how the logical && (and) operates in this situation.
Using the logical && (and), we can trap the numeric range of the grade entered. In doing
so, we can ensure that the grade entered falls within a specific range, and our program
will respond appropriately based on it. Remember that in logical && (and), both or all
conditional expressions must be evaluated to True so that its associated statement(s) will
be executed. In our case, the entered grade is 78 which is greater than 70 and less than 79
(so both conditional expressions are tested true).
In the if-else if syntax, after finding a True evaluation for a particular conditional
statement, the Java program compiler will jump right to the end of the if statement, thus
ending the evaluation or testing process. In other words, the remaining conditions below
it will no longer be evaluated or tested ( or simply ignored). Technically, this will save
much microprocessor’s processing power compared to using all ifs conditional statements
in our program. Meaning, using the if statement all throughout instead of else if
statement. With the if statement, all conditional statements will be evaluated or tested,
regardless of how many True evaluations found at the upper part of the conditional block.
This makes very taxing to the microprocessor’s processing energy. In other words, the
following code is not advisable to use (since there is only one option to be selected by our
Java program to comply with the given requirement):
.
.
.
if (varGrade>=90) && (varGrade<=100))
txtMessage.setText("A");
if ((varGrade>=80) && (varGrade<=89))
txtMessage.setText("B");
if ((varGrade>=70) && (varGrade<=79))
txtMessage.setText("C");
if ((varGrade>=60) && (varGrade<=69))
txtMessage.setText("D");
if (varGrade>=50) && (varGrade<=59))
234

txtMessage.setText("F");
if (varGrade>100) || (varGrade<50)
txtMessage.setText(“I”);
.
.
.
Notice all the conditional statements pointed by the arrows. It contained all ifs. It’s bad in
programming. There are cases or situations in real-world application that we have no
other choice but to use all the ifs statements throughout in our program (like the one you
see above), however such cases or situations rarely occur. So use all ifs statements with
utmost care, okay?

2nd Solution: (using the switch/case conditional statement)

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class grade2 extends Applet implements ActionListener {
TextField txtGrade, txtMessage;
Label lblGrade,lblMessage;
Button cmdExecute;
public void init() {
lblGrade = new Label("Enter a grade:");
add(lblGrade);
txtGrade = new TextField(3);
add(txtGrade);
cmdExecute = new Button("Execute");
add(cmdExecute);
cmdExecute.addActionListener(this);
lblMessage = new Label("Your grade in letter for is:");
add(lblMessage);
txtMessage = new TextField(4);
add(txtMessage);
}
public void actionPerformed(ActionEvent objE) {
int varGrade=0;
if (objE.getSource() == cmdExecute) {
varGrade = Integer.parseInt(txtGrade.getText());
switch (varGrade) {
case 90: case 91: case 92: case 93: case 94:
case 95: case 96: case 97: case 98: case 99: case 100:
txtMessage.setText("A");break;
case 80: case 81: case 82: case 83: case 84:
case 85: case 86: case 87: case 88: case 89:
txtMessage.setText("B");break;
case 70: case 71: case 72: case 73: case 74:
case 75: case 76: case 77: case 78: case 79:
txtMessage.setText("C");break;
case 60: case 61: case 62: case 63: case 64:
case 65: case 66: case 67: case 68: case 69:
txtMessage.setText("D");break;
235

case 50: case 51: case 52: case 53: case 54:
case 55: case 56: case 57: case 58: case 59:
txtMessage.setText("F");break;
default:
txtMessage.setText("I");
}
}
}
}

2. Then save the Java applet with the filename: grade2.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>grade2</title>
</head>
<body>
<hr>
<applet
code=grade2.class
width=250
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: grade2.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac grade2.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\grade2.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>grade2.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:
236

C:\javaprog>appletviewer grade2.htm (then press the Enter key)

Sample Output:

Figure 5.4b Applet that converts a grade into a letter form output
(using the case/switch conditional statement)

Explanation:

We created a new class named grade2 here in our program. Then we declared the two
text fields which we named txtGrade and txtMessage. We used the txtGrade object to get
the grade entered by the user, while the txtMessage object is used to display the message
in the second text field. The label lblGrade is declared using Java Label class and the
command button cmdExecute is declared using the Button class as you can see in our
code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class grade2 extends Applet implements ActionListener {
TextField txtGrade, txtMessage;
Label lblGrade,lblMessage;
Button cmdExecute;
.
.
.
You will notice that we actually created and add the objects we had declared at the top of
our program here in the init( ) method:
237

.
.
.
public void init( ) {
lblGrade = new Label("Enter a grade:");
add(lblGrade);
txtGrade = new TextField(3);
add(txtGrade);
cmdExecute = new Button("Execute");
add(cmdExecute);
cmdExecute.addActionListener(this);
lblMessage = new Label("Your grade in letter for is:");
add(lblMessage);
txtMessage = new TextField(4);
add(txtMessage);
}
.
.
.
We can make our program to determine the equivalent letter form grade of the input
numeric grade of the user at text field 1 (txtGrade) by implementing the ActionListener
interface, and connect our command button cmdExecute to it. Then finally add the
actionPerformed ( ) method to complete the process:

public void actionPerformed(ActionEvent objE) {


int varGrade=0;
if (objE.getSource( ) == cmdExecute) {
varGrade = Integer.parseInt(txtGrade.getText( ));
switch (varGrade) {
case 90: case 91: case 92: case 93: case 94:
case 95: case 96: case 97: case 98: case 99: case 100:
txtMessage.setText("A");break;
case 80: case 81: case 82: case 83: case 84:
case 85: case 86: case 87: case 88: case 89:
txtMessage.setText("B");break;
case 70: case 71: case 72: case 73: case 74:
case 75: case 76: case 77: case 78: case 79:
txtMessage.setText("C");break;
case 60: case 61: case 62: case 63: case 64:
case 65: case 66: case 67: case 68: case 69:
txtMessage.setText("D");break;
case 50: case 51: case 52: case 53: case 54:
case 55: case 56: case 57: case 58: case 59:
txtMessage.setText("F");break;
default:
txtMessage.setText("I");
}
}
}
}
238

When the command button cmdExecute is clicked, we instruct the computer to read the
numeric data entered by the user in text field 1, txtGrade. To read the numeric data from
the text field, we apply the getText( ) method such as the following syntax:

txGrade.getText( )

This syntax returns the text string in the text field, txtGrade. For example, if the user
inputs the data “94” in txtGrade text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtGrade.getText( ))

In this way, we can now store the entered numeric data from txtGrade and store the
result to variable varGrade. In switch/case conditional statement, we have to pass
varGrade variable to switch statement using the following syntax:

switch (varGrade)

The switch (varGrade) command holds the value of the variable varGrade for testing,
evaluation, or comparison with the given value_expression of each case or group of
cases.
Once the match is found (means the value of variable varGrade is the same with the
value_expression found) then the program pointer will search the associated statement
and execute it. For example, if we enter the value of 94 at the text field txtGrade, the
program pointer will execute the associated statement:

txtMessage.setText("A")

since this value_expression can be found at the first group of case labels. When the value
entered does not match to any value_expression listed, the associated statement of default
is executed instead. If the default is not included (since it is optional), then nothing will
be executed.
You will observe that all the associated statements are followed by the break command.
This break command will trigger the program pointer to break out from the whole
switch/case (statement) block. Meaning, it jumps to the statement that follows the end ( }
) symbol of switch/case statement. This makes our switch/case solution to act and
execute like the way if / else if / else do. It’s like ignoring all the remaining conditional
statements and expressions below when there is already a true-evaluation at the top. In
short, the break statement causes an immediate exit from the switch/case (statement)
block.
What is noticeable also in our program is that it seems our equivalent switch/case
conditional statement does not improve the readability of our program. Nor it shortens
our program listing. Yes, we can say that it is not like in Visual Basic programming
language, where in we can write the range of 90 to 100 with the simple syntax:
239

Case 90 To 100
txtMessage.Text = “A”

Well, we can consider this case as one of the weaknesses of switch/case statement
compared to if/else if conditional statement.

Example 5:

Design and develop a Java applet that determines if the input number at Text field 1 is a
positive or negative. Consider 0 as positive number. This time, develop your program
without the use of command button control, instead we have to use the TextListener
interface and addTextListener method. Follow the design specification below:

Text field 1

Enter a number: -7

It is a Negative number! Text field 2

Figure 5.5 An applet that determines if a number is positive or negative without a button

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class positive2 extends Applet implements TextListener {
TextField txtNumber, txtMessage;
Label lblNumber;
public void init() {
lblNumber = new Label("Enter a number:");
add(lblNumber);
txtNumber = new TextField(6);
add(txtNumber);
txtNumber.addTextListener(this);
txtMessage = new TextField(19);
add(txtMessage);
}
public void textValueChanged(TextEvent objE) {
int varNumber=0;
240

varNumber= Integer.parseInt(txtNumber.getText());
if (varNumber>=0)
txtMessage.setText("It is a Positive number!");
else
txtMessage.setText("It is a Negative number!");
repaint();
}
}

2. Then save the Java applet with the filename: positive2.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>positive2</title>
</head>
<body>
<hr>
<applet
code=positive2.class
width=200
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: positive2.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac positive2.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\positive2.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>positive2.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:
241

C:\javaprog>appletviewer positive2.htm (then press the Enter key)

Figure 5.5a Applet that determines if a number is positive or


negative without a button output

Explanation:

We created a new class named positive2 here in our program. Then we declared the two
text fields which we named txtNumber and txtMessage. We used the txtNumber object
to get the number entered by the user, while the txtMessage object is used to display the
message in the second text field. The label lblNumber is declared using Java Label
class. You can observe that we are using here the TextListener interface instead of the
ActionListener as you can see in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class positive2 extends Applet implements TextListener {
TextField txtNumber, txtMessage;
Label lblNumber;
.
.
.
You will notice that we actually created and add the objects we had declared at the top of
our program in the init( ) method. You will notice that this time we are using here the
addTextListener method instead of the addActionListener as follows:
.
.
.
public void init( ) {
lblNumber = new Label("Enter a number:");
242

add(lblNumber);
txtNumber = new TextField(6);
add(txtNumber);
txtNumber.addTextListener(this);
txtMessage = new TextField(19);
add(txtMessage);
}
.
.
.
We can make the program to determine if the input number of the user at text field 1
(txtNumber) is positive or negative number by implementing the ItemListener interface,
and connect our text field txtNumber to it. Then finally add the textValueChanged ( )
method to complete the process:
.
.
.
public void textValueChanged(TextEvent objE) {
int varNumber=0;
varNumber= Integer.parseInt(txtNumber.getText( ));
if (varNumber>=0)
txtMessage.setText("It is a Positive number!");
else
txtMessage.setText("It is a Negative number!");
repaint( );
}
}

When the value of the text field 1 has changed (meaning, the user is entering another
value) , we instruct the computer to read the numeric data entered by the user. To read the
numeric data from the text field, we apply the getText( ) method such as the following
syntax:

txNumber.getText( )

This syntax returns the text string in the text field, txtNumber. For example, if the user
inputs the data “-7” in txtNumber text field, this is actually a text string value. We need
to convert it to its equivalent numeric value using the parseInt( ) method under the
Integer class of the Java language such as the following syntax:

Integer.parseInt(txtNumber.getText( ))

In this way, we can now store the entered numeric data from txtNumber and store the
result to variable varNumber. This time we can use the numeric data of varNumber to be
evaluated if it is equal to or greater than zero (varNumber>=0) which is our process to
determine a positive number, using the following syntax:

if (varNumber>=0)
txtMessage.setText("It is a Positive number!");
243

else
txtMessage.setText("It is a Negative number!");

Now if the conditional expression is evaluated to true, then its associated statement

txtMessage.setText("It is a Positive number!")

will be executed. Otherwise, the associated statement of the else conditional statement:

txtMessage.setText("It is a Negative number!")

will be executed instead.

Example 6:

Design and develop a Java applet that will assist a teacher in converting a range of
numerical grade into its equivalent letter form grade, based on the given scale. This time,
develop your program without the use of command button control, instead we have to use
the TextListener interface and addTextListener method.

Range Grade

90 - 100 A
80 - 89 B
70 - 79 C
60 - 69 D
50 - 59 F
other grades I (for Invalid)

Follow the design specification below:

Text field 1

Enter your grade: 94

Your grade in letter form is:


A Text field 2

Figure 5.6 An applet that converts a grade into a letter form without a button
244

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class grade3 extends Applet implements TextListener {
TextField txtGrade, txtMessage;
Label lblGrade,lblMessage;
public void init() {
lblGrade = new Label("Enter a grade:");
add(lblGrade);
txtGrade = new TextField(3);
add(txtGrade);
txtGrade.addTextListener(this);
lblMessage = new Label("Your grade in letter form is:");
add(lblMessage);
txtMessage = new TextField(4);
add(txtMessage);
}
public void textValueChanged(TextEvent objE) {
int varGrade=0;
varGrade = Integer.parseInt(txtGrade.getText());
switch (varGrade) {
case 90: case 91: case 92: case 93: case 94:
case 95: case 96: case 97: case 98: case 99: case 100:
txtMessage.setText("A");break;
case 80: case 81: case 82: case 83: case 84:
case 85: case 86: case 87: case 88: case 89:
txtMessage.setText("B");break;
case 70: case 71: case 72: case 73: case 74:
case 75: case 76: case 77: case 78: case 79:
txtMessage.setText("C");break;
case 60: case 61: case 62: case 63: case 64:
case 65: case 66: case 67: case 68: case 69:
txtMessage.setText("D");break;
case 50: case 51: case 52: case 53: case 54:
case 55: case 56: case 57: case 58: case 59:
txtMessage.setText("F");break;
default:
txtMessage.setText("I");
}
repaint();
}
}

2. Then save the Java applet with the filename: grade3.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:

<html>
<!- Web page written with Java Applet>
<head>
245

<title>grade3</title>
</head>
<body>
<hr>
<applet
code=grade3.class
width=250
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: grade3.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac grade3.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\grade3.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>grade3.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer grade3.htm (then press the Enter key)

Sample Output:
246

Figure 5.6a Applet that converts a grade into


a letter form without a button output

Explanation:

We created a new class named grade3 here in our program. Then we declared the two
text fields which we named txtNumber and txtMessage. We used the txtNumber object
to get the number entered by the user, while the txtMessage object is used to display the
message in the second text field. The label lblNumber is declared using Java Label
class. You can observe that we are using here the TextListener interface instead of the
ActionListener as you can see in our code below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class grade3 extends Applet implements TextListener {
TextField txtGrade, txtMessage;
Label lblGrade,lblMessage;
.
.
.
You will notice that we actually created and add the objects we had declared at the top of
our program in the init( ) method. You will notice that this time we are using here the
addTextListener method instead of the addActionListener as follows:
.
.
.
public void init( ) {
lblGrade = new Label("Enter a grade:");
add(lblGrade);
txtGrade = new TextField(3);
add(txtGrade);
txtGrade.addTextListener(this);
247

lblMessage = new Label("Your grade in letter form is:");


add(lblMessage);
txtMessage = new TextField(4);
add(txtMessage);
}
.
.
.
We can make our program to determine the equivalent letter form grade of the input
numeric grade of the user at text field 1 (txtGrade) by implementing the ItemListener
interface, and connect our text field txtNumber to it. Then finally add the
textValueChanged ( ) method to complete the process:
.
.
.
public void textValueChanged(TextEvent objE) {
int varGrade=0;
varGrade = Integer.parseInt(txtGrade.getText( ));
switch (varGrade) {
case 90: case 91: case 92: case 93: case 94:
case 95: case 96: case 97: case 98: case 99: case 100:
txtMessage.setText("A");break;
case 80: case 81: case 82: case 83: case 84:
case 85: case 86: case 87: case 88: case 89:
txtMessage.setText("B");break;
case 70: case 71: case 72: case 73: case 74:
case 75: case 76: case 77: case 78: case 79:
txtMessage.setText("C");break;
case 60: case 61: case 62: case 63: case 64:
case 65: case 66: case 67: case 68: case 69:
txtMessage.setText("D");break;
case 50: case 51: case 52: case 53: case 54:
case 55: case 56: case 57: case 58: case 59:
txtMessage.setText("F");break;
default:
txtMessage.setText("I");
}
repaint( );
}
}

When the the value of the text field 1 has changed (meaning, the user is entering another
value) , we instruct the computer to read the numeric data entered by the user. To read the
numeric data, we instruct the computer to read the numeric data entered by the user in
text field 1, txtGrade. To read the numeric data from the text field, we apply the getText(
) method such as the following syntax:

txGrade.getText( )
248

This syntax returns the text string in the text field, txtGrade. For example, if the user
inputs the data “94” in txtGrade text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtGrade.getText( ))

In this way, we can now store the entered numeric data from txtGrade and store the
result to variable varGrade. In switch/case conditional statement, we have to pass
varGrade variable to switch statement using the following syntax:

switch (varGrade)

The switch (varGrade) command holds the value of the variable varGrade for testing,
evaluation, or comparison with the given value_expression of each case or group of
cases.
Once the match is found (means the value of variable varGrade is the same with the
value_expression found) then the program pointer will search the associated statement
and execute it. For example, if we enter the value of 94 at the text field txtGrade, the
program pointer will execute the associated statement:

txtMessage.setText("A")

since this value_expression can be found at the first group of case labels. When the value
entered does not match to any value_expression listed, the associated statement of default
is executed instead. If the default is not included (since it is optional), then nothing will
be executed.
You will observe that all the associated statements are followed by the break command.
This break command will trigger the program pointer to break out from the whole
switch/case (statement) block. Meaning, it jumps to the statement that follows the end ( }
) symbol of switch/case statement. This makes our switch/case solution to act and
execute like the way if / else if / else do. It’s like ignoring all the remaining conditional
statements and expressions below when there is already a true-evaluation at the top. In
short, the break
statement causes an immediate exit from the switch/case (statement) block.

Using Option Buttons and Check Boxes Together


(It’s All Together Now!)
Here in our example,we will use the Option buttons together with Check boxes in a
hypothetical application system. Let us learn how to manipulate them together. Well, we
will apply other popular controls too, such as Text fields. Okay, let us see it in action!
249

Example 7:

Design and develop a Java applet that when the user chooses the Hamburger option, the
ingredients to be marked with a check are: Beef and Spices; its corresponding price is
49.25 (to be displayed at the text field). If the user chooses the Cheeseburger option, the
ingredients to be checked are: Beef, Spices, and Cheese; its corresponding price is 69.50.
Now if the user chooses the Baconburger option, all the ingredients are marked with a
check and its corresponding price is 89.75.
Follow the design specification below:

-Burger Choices:- -Ingredients Included:-

Hamburger Beef

Cheeseburger Spices

Baconburger Cheese

Bacon

Price: 69.50

Figure 5.7 An applet for Simple Burger Assessment program

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class burger1 extends Applet implements ItemListener {
Menu Panel1;
Ingredients Panel2;
public void init() {
setLayout(new GridLayout(1,2));
Panel1 = new Menu();
Panel2 = new Ingredients();
add(Panel1);
Panel1.Hamburger.addItemListener(this);
Panel1.Cheeseburger.addItemListener(this);
Panel1.Baconburger.addItemListener(this);
add(Panel2);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==Panel1.Hamburger) {
Panel2.Ingredient1.setState(true);
Panel2.Ingredient2.setState(true);
Panel2.Ingredient3.setState(false);
Panel2.Ingredient4.setState(false);
250

Panel1.txtPrice.setText("Price:49.25");
}
if (objEvent.getItemSelectable()==Panel1.Cheeseburger) {
Panel2.Ingredient1.setState(true);
Panel2.Ingredient2.setState(true);
Panel2.Ingredient3.setState(true);
Panel2.Ingredient4.setState(false);
Panel1.txtPrice.setText("Price:69.50");
}
if (objEvent.getItemSelectable()==Panel1.Baconburger) {
Panel2.Ingredient1.setState(true);
Panel2.Ingredient2.setState(true);
Panel2.Ingredient3.setState(true);
Panel2.Ingredient4.setState(true);
Panel1.txtPrice.setText("Price:89.75");
}
}
}
class Menu extends Panel {
CheckboxGroup CGroup;
Checkbox Hamburger,Cheeseburger,Baconburger;
TextField txtPrice;
Label lblMenu;
Menu() {
CGroup = new CheckboxGroup();
lblMenu = new Label("-Burger Choices:-");
add(lblMenu);
add(Hamburger=new Checkbox("Hamburger",CGroup, false));
add(Cheeseburger=new Checkbox("Cheeseburger",CGroup,false));
add(Baconburger=new Checkbox("Baconburger",CGroup,false));
txtPrice=new TextField(10);
add(txtPrice);
}
}
class Ingredients extends Panel {
Checkbox Ingredient1, Ingredient2, Ingredient3, Ingredient4;
Label lblIngredient;
Ingredients() {
lblIngredient= new Label("-Ingredients Included:-");
add(lblIngredient);
add(Ingredient1 = new Checkbox("Beef"));
add(Ingredient2 = new Checkbox("Spices"));
add(Ingredient3 = new Checkbox("Cheese"));
add(Ingredient4 = new Checkbox("Bacon"));
}
}

2. Then save the Java applet with the filename: burger1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:

<html>
<!- Web page written with Java Applet>
<head>
<title>burger1</title>
</head>
251

<body>
<hr>
<applet
code=burger1.class
width=220
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: burger1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac burger1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\burger1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>burger1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer burger1.htm (then press the Enter key)

Sample Output:
252

Figure 5.7a Applet for Simple Burger Assessment program output

Explanation:

Here in our example, we set up a burger e-business on the Internet. In particular, we want
to embed A program in a Web page giving potential customers the price of various
burgers that we offer. In our applet, the customer selects from one of the three burger
options, and we let the applet to indicate the ingredients in each burger and inform the
customer a price for what they have selected. For example, if the customer clicks the
Hamburger option button, we set the corresponding check boxes of ingredients to
indicate what’s in this burger, then indicate the price in the text field. If the customer
clicks another option button, the other check boxes are checked to indicate a new set of
burger ingredients, and a new price appears in the text field. We can put the controls in
our applet into two panels. Panel1 will be the Burger Choices and the text field for the
Price and Panel2 will be the set of ingredient list.
We design the new panels as we did in our previous examples (about the Panel control
application), by deriving a new class named, for example, Menu or Ingredients, from the
Java language Panel class.First we have to declare a panel for each of the new panel
classes as follows:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class burger1 extends Applet implements ItemListener {
Menu Panel1;
Ingredients Panel2;
.
.
.
Now, we can create and add those panels by initializing them at the init( ) method. To
make it sure that the two panels will appear side by side in our applet, we will apply the
253

GridLayout manager to arrange them (1,2 parameter values here means we will set up
two panels) as we can see in our code below:
.
.
.
public void init( ) {
setLayout(new GridLayout(1,2));
Panel1 = new Menu( );
Panel2 = new Ingredients( );
add(Panel1);

Panel1.Hamburger.addItemListener(this);
Panel1.Cheeseburger.addItemListener(this);
Panel1.Baconburger.addItemListener(this);
add(Panel2);
}
.
.
.
To make this applet functional, we need to connect it up the option buttons. We start the
process by adding the ItemListener interface to our applet: We can reach the option
buttons Hamburger, Cheeseburger, and Baconburger through the Panel1 object using the
Java dot operator (.) as what we can see above.
Then we have to add the itemStateChange( ) method in our program to handle the option-
button clicks. We need to hadle the situation in which the customer clicks the specific
option button using the if condional statement. Now if a specific option button was
indeed clicked, we want the check boxes to indicate what is in the burger. In this
situation, we will set the check boxes appropriately in Panel2. The check boxes are
actually objects internal or belong to the Panel2 object that we have named Ingredient1 to
Ingredient4. So we can reach the check boxes through Panel2 using the dot operator too.
Then we can use the check box method setState( ) to set the check boxes as we want
them, passing a value of true makes them appear checked, and a value of false makes
them appear unchecked. Lastly, we have also place the corresponding price in the text
field as you can observe in our code below:
.
.
.
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable( )==Panel1.Hamburger) {
Panel2.Ingredient1.setState(true);
Panel2.Ingredient2.setState(true);
Panel2.Ingredient3.setState(false);
Panel2.Ingredient4.setState(false);
Panel1.txtPrice.setText("Price:49.25");
}
if (objEvent.getItemSelectable( )==Panel1.Cheeseburger) {
Panel2.Ingredient1.setState(true);
Panel2.Ingredient2.setState(true);
Panel2.Ingredient3.setState(true);
254

Panel2.Ingredient4.setState(false);
Panel1.txtPrice.setText("Price:69.50");
}
if (objEvent.getItemSelectable( )==Panel1.Baconburger) {
Panel2.Ingredient1.setState(true);
Panel2.Ingredient2.setState(true);
Panel2.Ingredient3.setState(true);
Panel2.Ingredient4.setState(true);
Panel1.txtPrice.setText("Price:89.75");
}
}
}
.
.
.
We will now add the controls we need, and since this panel holds option buttons, we will
need a check box group object. Finally, we will add our controls to the constructor of the
new Panel class:
.
.
.
class Menu extends Panel {
CheckboxGroup CGroup;
Checkbox Hamburger,Cheeseburger,Baconburger;
TextField txtPrice;
Label lblMenu;
Menu( ) { Warning! Must be unique from the previous program
CGroup = new CheckboxGroup( );
lblMenu = new Label("-Burger Choices:-");
add(lblMenu);
add(Hamburger=new Checkbox("Hamburger",CGroup, false));
add(Cheeseburger=new Checkbox("Cheeseburger",CGroup,false));
add(Baconburger=new Checkbox("Baconburger",CGroup,false));
txtPrice=new TextField(10);
add(txtPrice);
}
}
class Ingredients extends Panel {
Checkbox Ingredient1, Ingredient2, Ingredient3, Ingredient4;
Label lblIngredient;
Ingredients( ) {
lblIngredient= new Label("-Ingredients Included:-");
add(lblIngredient);
add(Ingredient1 = new Checkbox("Beef"));
add(Ingredient2 = new Checkbox("Spices"));
add(Ingredient3 = new Checkbox("Cheese"));
add(Ingredient4 = new Checkbox("Bacon"));
}
255

Example 8:

Design and develop a Java applet that when the user chooses the Deluxe pizza option,
the ingredients to be marked with a check are: Beef, Spices, and Cheese; its
corresponding price is 149.25 (to be displayed at the text field). If the user inputs 2 in the
Quantity text field, the Amount to be displayed should be 298.5, because 149 * 2 is
equal to 298.5. If the quantity is 3 then the amount to be displayed is 447.75, and so on.
When the user chooses the Special pizza option, the ingredients to be checked are: Beef,
Spices, Cheese and Bacon; its corresponding price is 169.50. If the user inputs 2 at the
Quantity text field, the Amount to be displayed is 339.0. If the input quantity is 3 then the
amount to be displayed is 508.5, and so on. When the user chooses the Hawaiian pizza
option, all ingredients should be marked with a check; its corresponding price is 189.75.
If the user inputs 2 at the Quantity text field, the Amount to be displayed is 379.5. If the
input quantity is 3 then the amount to be displayed is 569.25, and so on.
Follow the design specification below:

-Pizza Fiesta:- -Ingredients Included:-

Deluxe Beef

Special Spices

Hawaiian Cheese

Bacon
Price: 169.50
Pine-apple

Quantity: 2

Amount: 339.00

Figure 5.8 An applet for Simple Pizza Assessment program

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class pizza1 extends Applet implements ItemListener {
Menu1 Panel1;
Ingred Panel2;
public void init() {
256

setLayout(new GridLayout(1,2));
Panel1 = new Menu1();
Panel2 = new Ingred();
add(Panel1);
Panel1.chkDeluxe.addItemListener(this);
Panel1.chkSpecial.addItemListener(this);
Panel1.chkHawaiian.addItemListener(this);
add(Panel2);
}
public void itemStateChanged(ItemEvent objEvent) {
int varQty;
double varAmount;
if (objEvent.getItemSelectable()==Panel1.chkDeluxe) {
Panel2.Ingredient1.setState(true);
Panel2.Ingredient2.setState(true);
Panel2.Ingredient3.setState(true);
Panel2.Ingredient4.setState(false);
Panel2.Ingredient5.setState(false);
Panel1.txtPrice.setText("149.25");
varQty = Integer.parseInt(Panel1.txtQty.getText());
varAmount = varQty * 149.25;
Panel1.txtAmount.setText(String.valueOf(varAmount));
}
else if (objEvent.getItemSelectable()==Panel1.chkSpecial) {
Panel2.Ingredient1.setState(true);
Panel2.Ingredient2.setState(true);
Panel2.Ingredient3.setState(true);
Panel2.Ingredient4.setState(true);
Panel2.Ingredient5.setState(false);
Panel1.txtPrice.setText("169.50");
varQty = Integer.parseInt(Panel1.txtQty.getText());
varAmount = varQty * 169.50;
Panel1.txtAmount.setText(String.valueOf(varAmount));
}
else if (objEvent.getItemSelectable()==Panel1.chkHawaiian) {
Panel2.Ingredient1.setState(true);
Panel2.Ingredient2.setState(true);
Panel2.Ingredient3.setState(true);
Panel2.Ingredient4.setState(true);
Panel2.Ingredient5.setState(true);
Panel1.txtPrice.setText("189.75");
varQty = Integer.parseInt(Panel1.txtQty.getText());
varAmount = varQty * 189.75;
Panel1.txtAmount.setText(String.valueOf(varAmount));
}
}
}
class Menu1 extends Panel {
CheckboxGroup CGroup;
Checkbox chkDeluxe,chkSpecial, chkHawaiian;
TextField txtPrice, txtQty, txtAmount;
Label lblMenu, lblPrice,lblQty,lblAmount;
Menu1() {
lblMenu = new Label("-Pizza Fiesta:-");
add(lblMenu);
CGroup = new CheckboxGroup();
add(chkDeluxe=new Checkbox("Deluxe",CGroup, false));
257

add(chkSpecial=new Checkbox("Special",CGroup,false));
add(chkHawaiian=new Checkbox("Hawaiian",CGroup,false));
lblPrice= new Label("Price:");
add(lblPrice);
txtPrice=new TextField(7);
add(txtPrice);
lblQty = new Label("Quantity:");
add(lblQty);
txtQty = new TextField(7);
add(txtQty);
lblAmount = new Label("Amount:");
add(lblAmount);
txtAmount = new TextField(7);
add(txtAmount);
}
}
class Ingred extends Panel {
Checkbox Ingredient1, Ingredient2, Ingredient3, Ingredient4,
Ingredient5;
Label lblIngredient;
Ingred() {
lblIngredient = new Label("-Ingredients Included:-");
add(lblIngredient);
add(Ingredient1 = new Checkbox("Beef"));
add(Ingredient2 = new Checkbox("Spices"));
add(Ingredient3 = new Checkbox("Cheese"));
add(Ingredient4 = new Checkbox("Bacon"));
add(Ingredient5 = new Checkbox("Pine-apple"));
}
}

2. Then save the Java applet with the filename: pizza1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>pizza1</title>
</head>
<body>
<hr>
<applet
code=pizza1.class
width=220
height=300>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: pizza1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:
258

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac pizza1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\pizza1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>pizza1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer pizza1.htm (then press the Enter key)

Sample Output:
259

Figure 5.8a Applet for Simple Pizza Assessment program output

Explanation:

Try to run this program now by inputting data on the Quantity text field. Then reclick the
option buttons at the Pizza Fiesta options and see what happens. You will notice that the
value at the Amount text field is changing constantly.
Here in our example, we set up a pizza e-business on the Internet. In particular, we want
to embed A program in a Web page giving potential customers the price of various pizza
that we offer. In our applet, the customer selects from one of the three pizza options, and
we let the applet to indicate the ingredients in each pizza and inform the customer a price
for what they have selected. For example, if the customer clicks the Deluxe pizza option
button, we set the corresponding check boxes of ingredients to indicate what’s in this
Deluxe pizza, then indicate the price in the text field. If the customer clicks another
option button, the other check boxes are checked to indicate a new set of pizza
ingredients, and a new price appears in the text field. Unlike in our previous example
about the burger e-business, we include here in our program the option where the
customers can enter how many pizza they can order and how much is the total amount to
pay. In this way, they can weigh if their money is enough to pay the bills. This pizza
assessment program is more flexible than the previous burger assessment program.
We can put the controls in our applet into two panels. Panel1 will be the Pizza Fiesta
choices and the text field for the Price, Quantity, and Amount, then the Panel2 will be the
set of ingredient list.
We design the new panels as we did in our previous examples (about the Panel control
application), by deriving a new class named, for example, Menu or Ingredients, from the
Java language Panel class.First we have to declare a panel for each of the new panel
classes as follows:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class pizza1 extends Applet implements ItemListener {
Menu1 Panel1;
Ingred Panel2;
.
.
.
Now we can create and add those panels by initializing them at the init( ) method. To
make it sure that the two panels will appear side by side in our applet, we will apply the
GridLayout manager to arrange them (1,2 parameter values here means we will set up
two panels) as we can see in our code below:
.
.
.
public void init( ) {
260

setLayout(new GridLayout(1,2));
Panel1 = new Menu1( );
Panel2 = new Ingred( );
add(Panel1);
Panel1.chkDeluxe.addItemListener(this);
Panel1.chkSpecial.addItemListener(this);
Panel1.chkHawaiian.addItemListener(this);
add(Panel2);
}
.
.
.
To make this applet functional, we need to connect it up the option buttons. We start the
process by adding the ItemListener interface to our applet: We can reach the option
buttons Deluxe, Special, and Hawaiian through the Panel1 object using the Java dot
operator (.) as what we can see above.
Then we have to add the itemStateChange( ) method in our program to handle the option-
button clicks. We need to handle the situation in which the customer clicks the specific
option button using the if/else if condional statements. Now if a specific option button
was indeed clicked, we want the check boxes to indicate what is in the pizza, then
compute the corresponding amount. In this situation, we will set the check boxes
appropriately in Panel2. The check boxes are actually objects internal or belong to the
Panel2 object that we have named Ingredient1 to Ingredient4. So we can reach the check
boxes through Panel2 using the dot operator too. Then we can use the check box method
setState( ) to set the check boxes as we want them, passing a value of true makes them
appear checked, and a value of false makes them appear unchecked. Lastly, we have to
place also the corresponding price in the text field as you can observe in our code below:
.
.
.
public void itemStateChanged(ItemEvent objEvent) {
int varQty;
double varAmount;
if (objEvent.getItemSelectable( )==Panel1.chkDeluxe) {
Panel2.Ingredient1.setState(true);
Panel2.Ingredient2.setState(true);
Panel2.Ingredient3.setState(true);
Panel2.Ingredient4.setState(false);
Panel2.Ingredient5.setState(false);
Panel1.txtPrice.setText("149.25");
varQty = Integer.parseInt(Panel1.txtQty.getText( ));
varAmount = varQty * 149.25;
Panel1.txtAmount.setText(String.valueOf(varAmount));
}
else if (objEvent.getItemSelectable( )==Panel1.chkSpecial) {
Panel2.Ingredient1.setState(true);
Panel2.Ingredient2.setState(true);
Panel2.Ingredient3.setState(true);
Panel2.Ingredient4.setState(true);
261

Panel2.Ingredient5.setState(false);
Panel1.txtPrice.setText("169.50");
varQty = Integer.parseInt(Panel1.txtQty.getText());
varAmount = varQty * 169.50;
Panel1.txtAmount.setText(String.valueOf(varAmount));
}
else if (objEvent.getItemSelectable( )==Panel1.chkHawaiian) {
Panel2.Ingredient1.setState(true);
Panel2.Ingredient2.setState(true);
Panel2.Ingredient3.setState(true);
Panel2.Ingredient4.setState(true);
Panel2.Ingredient5.setState(true);
Panel1.txtPrice.setText("189.75");
varQty = Integer.parseInt(Panel1.txtQty.getText( ));
varAmount = varQty * 189.75;
Panel1.txtAmount.setText(String.valueOf(varAmount));
}
}
}
.
.
.
Now, we will go to the details on how our program calculates the amount of pizza
choosen by the customer. We have this discussion. To read the numeric data from the
Quantity text field (txtQty), we apply the getText( ) method such as the following syntax:

Panel1.txtQty.getText( )

This syntax returns the text string in the text field, txtQty. For example, if the user inputs
the data “2” in txtQty text field, this is actually a text string value. We need to convert it
to its equivalent numeric value using the parseInt( ) method under the Integer class of the
Java language such as the following syntax:

Integer.parseInt(Panel1.txtQty.getText( )

In this way, we can now store the entered numeric data from txtQty and store the result
to variable varQty. This time, we can use the numeric data from varQty variable for our
equation to compute the Amount of pizza with the following syntax:

varAmount = varQty * 149.25;

Now we need to convert back the numeric value stored in the varAmount into its
equivalent text string so that we can display it to the text field txtAmount using the
valueOf( ) method under the String class of the Java language. Here is its command
syntax below:

Panel1.txtAmount.setText(String.valueOf(varAmount))
262

We will now add the controls we needed, and since this panel holds option buttons, we
will need a check box group object. Finally, we will add our controls to the constructor of
the new Panel class:
.
.
.
class Menu1 extends Panel {
CheckboxGroup CGroup;
Checkbox chkDeluxe,chkSpecial, chkHawaiian;
TextField txtPrice, txtQty, txtAmount;
Label lblMenu, lblPrice,lblQty,lblAmount;
Menu1( ) { Warning! Must be unique from the previous program
lblMenu = new Label("-Pizza Fiesta:-");
add(lblMenu);
CGroup = new CheckboxGroup( );
add(chkDeluxe=new Checkbox("Deluxe",CGroup, false));
add(chkSpecial=new Checkbox("Special",CGroup,false));
add(chkHawaiian=new Checkbox("Hawaiian",CGroup,false));
lblPrice= new Label("Price:");
add(lblPrice);
txtPrice=new TextField(7);
add(txtPrice);
lblQty = new Label("Quantity:");
add(lblQty);
txtQty = new TextField(7);
add(txtQty);
lblAmount = new Label("Amount:");
add(lblAmount);
txtAmount = new TextField(7);
add(txtAmount);
}
}
class Ingred extends Panel {
Checkbox Ingredient1, Ingredient2, Ingredient3, Ingredient4,
Ingredient5;
Label lblIngredient;
Ingred( ) {
lblIngredient = new Label("-Ingredients Included:-");
add(lblIngredient);
add(Ingredient1 = new Checkbox("Beef"));
add(Ingredient2 = new Checkbox("Spices"));
add(Ingredient3 = new Checkbox("Cheese"));
add(Ingredient4 = new Checkbox("Bacon"));
add(Ingredient5 = new Checkbox("Pine-apple"));
}
}

That’s the end of our discussion in this chapter. And I’m sure, you are now ready to
answer the Lab Activity Test that will follow. Good luck!
263

Warning!
We have to rename the class name of our Menu to Menu1 in pizza e-business program to prevent a conflict
in our previous burger e-business program which already contains the Menu class. With the Panel class
application, we have to take note that the Menu class name must be unique for each program that we make,
so that the previous class name cannot be used by the second program. This is the main reason why our
second program is a “look-a-like” in our previous program because of the similar class name that we
accidentally and repeatedly used.
264

LAB ACTIVITY
TEST 5

1. Design and develop a Java applet that determines if the input number at Text
field 1 is ODD or EVEN. The EVEN numbers are divisible by 2. Therefore, if
we get a remainder of zero (0) after dividing a number by 2, then that is an
EVEN number. The syntax to get the remainder in Java (or C and C++
programming languages) is using the % operator. For example, the equation:
varEven = InputNumber % 2 will return the remainder value. With the following
hint, you can successfully solve this LAB Activity test. I am sure of that. Follow
the design specification below:

Text field 1

Enter a number: 1000

Execute Button

It is an EVEN number! Text field 2

2. Design and develop a Java applet that determines if the input number at Text field 1 is
ODD or EVEN. The EVEN numbers are divisible by 2. Therefore, if we get a remainder
of zero (0) after dividing a number by 2, then that is an EVEN number. The syntax to get
the remainder in Java (or C and C++ programming languages) is using the % operator.
For example, the equation: varEven = InputNumber % 2 will return the remainder
value. With the following hint, you can successfully solve this LAB Activity test. I am
sure of that. This time, develop your program without the use of command button
control, instead you have to use the TextListener interface and addTextListener method
to accomplish the task.
Follow the design specification below:

Text field 1

Enter a number: 1000

It is an EVEN number! Text field 2


265

3. Design and develop a Java program to display the high school level of a student, based
on its year-entry number. For example, the year-entry 1 means the student is freshman, 2
for sophomore, and so on. This time, develop your program without the use of command
button control, instead you have to use the TextListener interface and addTextListener
method to accomplish the task.
Here is the given criteria:

Year-entry number High-School Level


5 Freshman
6 Sophomore
7 Junior
8 Senior
5 Out-Of-Range

Follow the design specification below:

Text field 1

2
Enter the Year-entry level:

The High-School Level is: Sophomore Text field 2

1st Solution: Use the If / Else If conditional statement


2nd Solution: Use the Switch/Case conditional statement

4. Design and develop a Java applet that examines the input value of a variable nTemp
(Temperature) at text field 1 (Text1). Then display the following messages at text field 2
(Text2) depending on the value assigned to nTemp variable.

Temperature Message

Less than 0 ICE


Between 0 and 100 WATER
Exceeds 100 STEAM

Follow the design specification below:


266

Enter the temperature:


70 Text field 1

Text field 2
WATER!

Solution: Use only the If / Else If conditional statement

5.Design and develop a Java applet for the Air Force to label an aircraft as military or
civilian. The program is to be given the plane’s observed speed in km/h (kilometer per
hour).The speed will serve as its input at text box 1 (Text1). For planes traveling in
excess of 1100 km/h, you should label them as “civilian” aircraft; between 500 km/h to
1100 km/h, label them as “military” aircraft and for planes traveling at more slower
speed - less than 500 km/h, you should label them as an “Unknown Aircraft” message.
The labeled message should be displayed at text field 2. Follow the given design
specification below:

Text field 1
Enter the aircraft speed in km/h: 700

It’s a military aircraft! Text field 2

Solution: Use only the If / Else If conditional statement

6.Design and develop a Java applet that adds, subtracts, multiplies, or divides two input
numbers using the option buttons. Follow the given figure below in designing and
developing the application program:
267

5
-- Compute:-- 1st no.

Add 2nd no. 2 Text fields

Subtract
=
Multiply
Answer: 7
Divide

Option buttons

Hint:
For the Divide operation, you can apply the Explicit Casting method where you force the integer data value
to be converted into its equivalent double data type value. For example, you want to divide n1 from n2
(n1/n2) which are declared as both integers. You can apply explicit casting of data type by the following
syntax:

dividing = (double) n1 /n2;

Try it!

7. Design and develop a Java applet that adds, subtracts, multiplies, or divides two input
numbers using a group of command buttons. Follow the given design specification
below:

-- Compute: --

1st no. 5
Add

Text fields
Subtract 2nd no. 2

Multiply =
7
Divide Answer:

Command buttons
268

Hint:
For the Divide operation, you can apply the Explicit Casting method where you force the integer data value
to be converted into its equivalent double data type value. For example, you want to divide n1 from n2
(n1/n2) which are declared as both integers. You can apply explicit casting of data type by the following
syntax:

dividing = (double) n1 /n2;

Try it!

8.Design and develop a Java program so that when the user chooses the Economy
accommodation, the Toilet and Meals amenities should be marked with a check and
the fare is 1,500. When the user chooses the Tourist accommodation, the Toilet,
Aircon, Bed sheets, and Meals amenities should be marked with a check and the fare
is 1,700. When the user chooses the Cabin accommodation, all amenities should be
marked with a check and the fare is 2,000 . Follow the given design specification
below:

-- Amenities:--
- - Accommodation: -- Toilet

Economy Aircon

Tourist Television

Cabin Bed sheets

Meals
Fare:
P 1500
VIP Lounge

Text field

9.Design and develop this Java program. We will input the tuition fee in the applet. In our
sample input data, we enter 30,000 in text field 1, now it is 5% (percent) interest is
1,500. Thus, the output at text field 2 is 31,500 (30,000 + 1,500).
Now for example we enter a tuition fee of 20,000 and then we select the Cash as the
mode of payment, the output at text field 2 should be 18,000 since there is a 10 %
(percent) discount for paying a Cash tuition fee. Follow the given design specification
below:
269

-- Mode of Payments :--


Enter tuition fee:
Cash (10% discount)
30000 Text field 1
Two Payments
(5% interest)

Three Payments
(10% interest) Your total tuition fee:

31500
Text field 2

10.Design and develop a Java applet that when the user selects CT-Scan, only the
Head body parts is marked with a check. If X-Ray is chosen, only the Body will
be marked with a check. And if the Physical exam is chosen, then all the body
parts are marked with a check. In our example, we chose the X-ray as the Medical
exam selected, and since the number of Medical exam is 2, therefore, the Bill is
2000 (1000 * 2). Follow the given design specification below:

-- Medical Exam:-- -- Body Parts :--

CT-Scan (12,000) Head

X-Ray (1,000) Mouth

Physical Exam (700) Body

No. of M. Exam: Urine


2
Bill:
2000

Text field 1 Text field 2


270

Chapter 7
Using Controls with Looping Statements

The looping statement is a program instruction that repeats some statement or sequence
of statements in a specified number of times. Looping statement allows a set of
instructions to be performed all over again until a certain condition is reached, met, or
proven and tested as false.
The three looping statements of Java programming language are:

1. for loop
2. while loop
3. do/while loop

The syntax of the for loop statement is:

for ( init; condition; inc/dec) {


statement(s) statements that do something repetitively (body of the loop)
}

The three parts of the for loop are the initialization (init) part , the condition part, and the
increment (inc) or decrement (dec) part. The initialization part of the loop statement is
the first value where the loop starts. For example, we can start our loop with the value of
zero (0) or one (1). Usually, we use 0 since most of the Java array (or C & C++
languages) starts at zero-th position. The condition part is where we say when to stop the
looping process. The loop continues to execute so long as the condition which the
program is evaluating (or checking) is true. Once it is no longer true, the loop terminates.
Now if in the first time the program check the condition and find out it is false, the loop is
never executed at all.
The incrementation part is where we say by how much to increase the loop counter on
each pass through the loop. Usually, we add one to variable i each time through using ++
symbol. This is opposite in decrementation process because we subtract one to variable
i each time through using -- symbol. The sample of incrementation formula is i++ or ++i,
while the decrementation formula is --i or i-- .

The syntax of the while loop statement is:

init;
while (condition) {
statements;
inc/dec;
}

The syntax of the do/while loop statement is different from other looping statements,
because the checking or evaluating of conditional part for continuing the loop is at the
end of the loop instead of at the top. This means that the loop will always execute at least
271

once. There are real-world system applications that need to be executed at least once, so
do/while loop statement is fitted to this kind of situation. And in some cases, the
do/while loop is easier to implement in these real-world system applications compared to
other looping statements.

init;
do {
statements;
inc/dec
} while (condition);

Incrementation, Decrementation, and Accumulator Formulas

These three formulas are oftenly used in looping statements operation:

Examples of Incrementation Formula:

i++ or ++i
++n or n++

Examples Decrementation Formula:

i-- or --i
--n or n--

Examples of Accumulator Formula: (Sample Implementation)

acc=acc+n (acc = acc + 20 or a shortcut method: acc =+20 )


sum=sum+n (sum = sum + 5 or a shortcut method: sum+=5 )
total=total+n (total=total +1000 or a shortcut method: total+=1000)

The variable initialization (init) specifies the first value where the loop starts. The
conditional part specifies conditions to be evaluated or tested. If the condition is false,
then no action is taken and the program pointer proceeds to the next statement after the
loop. If the conditional expression is evaluated to be true, then all the statements within
the body of the loop are executed. This looping process (iteration) is repeated as long as
the conditional expression remains true. After each iteration, the
incrementation/decrementation (inc/dec) part is executed, then the conditional expression
is reevaluated. In a simple for loop statement, the initialization part is executed only once.
This happens during the first time the program pointer points to the loop. But in nested
loop, the inner loop’s initialization part could be reexecuted many times depending on
the condition set at the outer loop. This will happen every time the program pointer
reevaluates the condition of the outer loop to True.
For the sake of simplicity and easy understanding about looping statement, we will focus
our discussion on the simple looping statement construct only.
272

Example 1:

Design and develop a Java applet that generates the given sequence numbers using
looping statements. Follow the given design specification below:

Figure 6.1 An applet that generates sequence numbers in vertical format

1st Solution: (using for loop statement)

1. At the Microsoft NotePad, write the following code:


import java.awt.Graphics;
public class forl1 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varRow=0;
for (int i=1; i<=5; i++) {
strNo = String.valueOf(i);
varRow=varRow+20;
objG.drawString(strNo,60,varRow);
}
}
}

2. Then save the Java applet with the filename: forl1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>forl1</title>
</head>
<body>
<hr>
<applet
273

code=forl1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: forl1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac forl1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\forl1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>forl1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer forl1.htm (then press the Enter key)

Sample Output:
274

Figure 6.1a Applet that generates sequence numbers in vertical format output

Explanation:

The difference between the for loop and other looping statements (while and do-while) is
that in the for loop statement; the initialization, condition, and
incrementation/decrementation parts are placed on the same line. In while and do-while
loops, the initialization part is placed before the loop, while the
incrementation/decrementation part is placed within the body of the loop. This makes
them very different!
This arrangement on the same line of the for loop makes our analysis of how it works,
confusing. For example, which of the three expressions is the first to be executed and
how many times it is executed? Well, obviously, our answer is the initialization part.
That is correct! However, the question “how many times” is very hard to answer, since in
looping operation the possibility of repeated execution is a norm. Now, remember that in
an ordinary for loop statement (meaning not a nested for loop), the initialization part is
executed only once throughout the looping operation and it happened during the first time
the program pointer points to the for loop statement.
How about the second expression to be executed? The answer for this one is the
conditional expression. Remember also that the initialization is executed first, then the
conditional expression follows to be evaluated (whether True or False). If the evaluation
is tested or proven true, the statements within the body of the loop are executed. After
executing all the statements, the program pointer loops again and will execute this time
the incrementation/decrementation part, then the conditional expression is evaluated
again. If the condition is proven or tested true, then all the statements within the body of
the loop are reexecuted. This looping process (the execution of
incrementation/decrementation and reevaluation of condition) are repeated or iterated
until the conditional expression is evaluated to false.
First we declared two ordinary variables here in our program as follows:
275

import java.awt.Graphics;
public class forl1 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varRow=0;
.
.
.

Then we initialize our loop’s variable i with 1, so that the first generated sequence
number is 1. Now we have the condition: i<=5 , meaning the loop will continue iterating
as long as the value of variable i is less than or equal to 5. The role of the incrementation
formula: i++ , means we add one to the value of variable i each time the loop iterates
until such time its value becomes 6 which in turn terminates the loop operation.
.
.
.
for (int i=1; i<=5; i++) {
strNo = String.valueOf(i);
varRow=varRow+20;
objG.drawString(strNo,60,varRow);
}
}

We need to convert the numeric value of variable i to its equivalent string value by using
the valueOf( ) method under the String class and store it to strNo variable as follows:

strNo = String.valueOf(i);

In this way, we can display it properly at the drawString( ) method. The drawString( )
method has three parameters; the first one is the string value to display, then the numeric
value of the column and lastly the row that indicates what line to display the string value.
In our row parameter, we use the accumulator formula: varRow=varRow+20; so
that the string data will be diplayed 20 pixels away from each other. Without doing so,
our string data will be overwritten on the same pixel location, giving us the illusion that
only one string value is generated and displayed.

2nd Solution: (using while loop statement)

1. At the Microsoft NotePad, write the following code:


import java.awt.Graphics;
public class whilel1 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varRow=0;
int i=1;
276

while (i<=5) {
strNo = String.valueOf(i);
varRow=varRow+20;
objG.drawString(strNo,60,varRow);
i++;
}
}
}

2. Then save the Java applet with the filename: whilel1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>whilel1</title>
</head>
<body>
<hr>
<applet
code=whilel1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: whilel1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac whilel1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\whilel1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>while1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:
277

C:\javaprog>appletviewer while1.htm (then press the Enter key)

Sample Output:

Figure 6.1b Applet that generates sequence numbers in vertical format output

Explanation:

First we declared two ordinary variables here in our program as follows:

import java.awt.Graphics;
public class whilel1 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varRow=0;
.
.
.
The initial value of i variable is 1. So when the program pointer evaluates or tests the
condition: i<=5, it is evaluated to True, since the value of variable i is less than 5.
Because the condition is evaluated to true, all statements within the body of the loop are
executed:

int i=1;
while (i<=5) {
strNo = String.valueOf(i);
varRow=varRow+20; statements within the body of the loop
objG.drawString(strNo,60,varRow);
i++;
278

}
}
}

The execution of all the statements within the body of the loop are repeated until the
evaluation of the condition becomes False.
We need to convert the numeric value of variable i to its equivalent string value by using
the valueOf( ) method under the String class and store it to strNo variable as follows:

strNo = String.valueOf(i);

In this way, we can display it properly at the drawString( ) method. The drawString( )
method has three parameters; the first one is the string value to display, then the numeric
value of the column and lastly the row that indicates what line to display the string value.
In our row parameter, we use the accumulator formula: varRow=varRow+20; so
that the string data will be diplayed 20 pixels away from each other. Without doing so,
our string data will be overwritten on the same pixel location, giving us the illusion that
only one string value is generated and displayed.

3rd Solution: (using do/while loop statement)

1. At the Microsoft NotePad, write the following code:

import java.awt.Graphics;
public class dol1 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varRow=0;
int i=1;
do {
strNo = String.valueOf(i);
varRow=varRow+20;
objG.drawString(strNo,60,varRow);
i++;
} while (i<=5);
}
}

2. Then save the Java applet with the filename: dol1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>dol1</title>
</head>
<body>
<hr>
<applet
279

code=dol1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: dol1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac dol1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\dol1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>dol1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer dol1.htm (then press the Enter key)

Sample Output:
280

Figure 6.1c Applet that generates sequence numbers in vertical format output

Explanation:

First we declared two ordinary variables here in our program as follows:

import java.awt.Graphics;
public class dol1 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varRow=0;
.
.
.
The initial value of i variable is 1. So when the program pointer evaluates or tests the
condition: i<=5 (at the bottom part of the loop), it is evaluated to True, since the value of
variable i is less than 5. You will notice that in the do/while loop solution, the condition is
tested at the last part of our loop. This ensures that even if the condition is evaluated or
tested as False, the statements within the body of the loop will be executed at least once:
.
.
.
int i=1;
do {
strNo = String.valueOf(i);
varRow=varRow+20; statements within the body of the loop
objG.drawString(strNo,60,varRow);
i++;
} while (i<=5);
}
}
281

We need to convert the numeric value of variable i to its equivalent string value by using
the valueOf( ) method under the String class and store it to strNo variable as follows:

strNo = String.valueOf(i);

In this way, we can display it properly at the drawString( ) method. The drawString( )
method has three parameters; the first one is the string value to display, then the numeric
value of the column and lastly the row that indicates what line to display the string value.
In our row parameter, we use the accumulator formula: varRow=varRow+20; so
that the string data will be diplayed 20 pixels away from each other. Without doing so,
our string data will be overwritten on the same pixel location, giving us the illusion that
only one string value is generated and displayed.

Example 2:

Design and develop a Java applet that generates the given sequence numbers using
looping statements. This time, it is in horizontal format. Follow the given design
specification below:

1 2 3 4 5

Figure 6.2 An applet that generates sequence numbers in horizontal format

1st Solution: (using for loop statement)

1. At the Microsoft NotePad, write the following code:


import java.awt.Graphics;
public class forl4 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varCol=0;
for (int i=1; i<=5; i++) {
strNo = String.valueOf(i);
varCol=varCol+20;
objG.drawString(strNo,varCol,20);
}
}
}
282

2. Then save the Java applet with the filename: forl4.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>forl4</title>
</head>
<body>
<hr>
<applet
code=forl4.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: dol1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac forl4.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\forl4.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>for14.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer for14.htm (then press the Enter key)

Sample Output:
283

Figure 6.1a Applet that generates sequence numbers in


horizontal format output

Explanation:

First we declared two ordinary variables here in our program as follows:

import java.awt.Graphics;
public class forl4 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varCol=0;
.
.
.
Then we initialize our loop’s variable i with 1, so that the first generated sequence
number is 1. Now we have the condition: i<=5 , meaning the loop will continue iterating
as long as the value of variable i is less than or equal to 5. The role of the incrementation
formula: i++ , means we add one to the value of variable i each time the loop iterates
until such time its value becomes 6 which in turn terminates the loop operation.
.
.
.
for (int i=1; i<=5; i++) {
strNo = String.valueOf(i);
varCol=varCol+20;
objG.drawString(strNo,varCol,20);
}
}
}
284

We need to convert the numeric value of variable i to its equivalent string value by using
the valueOf( ) method under the String class and store it to strNo variable as follows:

strNo = String.valueOf(i);

In this way, we can display it properly at the drawString( ) method. The drawString( )
method has three parameters; the first one is the string value to display, then the numeric
value of the column and lastly the row that indicates what line to display the string value.
In our column parameter, we use the accumulator formula: varCol = varCol+20; so
that the string data will be diplayed 20 pixels away from each other. Without doing so,
our string data will be overwritten on the same pixel location, giving us the illusion that
only one string value is generated and displayed. You will notice in our code above that
we simply put the accumulator formula to the column parameter of the drawString( )
method so that we can display the generated sequence numbers in horizontal format.

2nd Solution: (using while loop statement)

1. At the Microsoft NotePad, write the following code:


import java.awt.Graphics;
public class whilel4 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varCol=0;
int i=1;
while (i<=5) {
strNo = String.valueOf(i);
varCol=varCol+20;
objG.drawString(strNo,varCol,20);
i++;
}
}
}

2. Then save the Java applet with the filename: whilel4.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>whilel4</title>
</head>
<body>
<hr>
<applet
code=whilel4.class
width=200
height=200>
</applet>
<hr>
285

</body>
</html>

4. Now save the HTML script with the filename: whilel4.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac whilel4.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\whilel4.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>whilel4.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer whilel4.htm (then press the Enter key)

Sample Output:

Figure 6.1b Applet that generates sequence numbers in


286

horizontal format output

Explanation:

First we declared two ordinary variables here in our program as follows:

import java.awt.Graphics;
public class whilel4 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varCol=0;
.
.
.
The initial value of i variable is 1. So when the program pointer evaluates or tests the
condition: i<=5, it is evaluated to True, since the value of variable i is less than 5.
Because the condition is evaluated to true, all statements within the body of the loop are
executed:

int i=1;
while (i<=5) {
strNo = String.valueOf(i);
varCol=varCol+20; statements within the body of the loop
objG.drawString(strNo,varCol,20);
i++;
}
}
}

The execution of all the statements within the body of the loop are repeated until the
evaluation of the condition becomes False.
We need to convert the numeric value of variable i to its equivalent string value by using
the valueOf( ) method under the String class and store it to strNo variable as follows:

strNo = String.valueOf(i);

In this way, we can display it properly at the drawString( ) method. The drawString( )
method has three parameters; the first one is the string value to display, then the numeric
value of the column and lastly the row that indicates what line to display the string value.
In our column parameter, we use the accumulator formula: varCol=varCol+20; so
that the string data will be diplayed 20 pixels away from each other. Without doing so,
our string data will be overwritten on the same pixel location, giving us the illusion that
only one string value is generated and displayed.
You will notice in our code above that we simply put the accumulator formula to the
column parameter of the drawString( ) method so that we can display the generated
sequence numbers in horizontal format.
287

3rd Solution: (using do/while loop statement)

1. At the Microsoft NotePad, write the following code:


import java.awt.Graphics;
public class dol4 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varCol=0;
int i=1;
do {
strNo = String.valueOf(i);
varCol=varCol+20;
objG.drawString(strNo,varCol,20);
i++;
} while (i<=5);
}
}

2. Then save the Java applet with the filename: dol4.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>dol4</title>
</head>
<body>
<hr>
<applet
code=dol4.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: dol4.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac dol4.java (then press the Enter key)


288

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\dol4.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>dol4.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer dol4.htm (then press the Enter key)

Sample Output:

Figure 6.1c Applet that generates sequence numbers in horizontal format output

Explanation:

First we declared two ordinary variables here in our program as follows:

import java.awt.Graphics;
public class dol4 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varCol=0;
.
.
.
The initial value of i variable is 1. So when the program pointer evaluates or tests the
condition: i<=5 (at the bottom part of the loop), it is evaluated to True, since the value of
289

variable i is less than 5. You will notice that in the do/while loop solution, the condition is
tested at the last part of our loop. This ensures that even if the condition is evaluated or
tested as False, the statements within the body of the loop will be executed at least once:
.
.
.
int i=1;
do {
strNo = String.valueOf(i);
varCol=varCol+20; statements within the body of the loop
objG.drawString(strNo,varCol,20);
i++;
} while (i<=5);
}
}

We need to convert the numeric value of variable i to its equivalent string value by using
the valueOf( ) method under the String class and store it to strNo variable as follows:

strNo = String.valueOf(i);

In this way, we can display it properly at the drawString( ) method. The drawString( )
method has three parameters; the first one is the string value to display, then the numeric
value of the column and lastly the row that indicates what line to display the string value.
In our column parameter, we use the accumulator formula: varCol=varCol+20; so
that the string data will be diplayed 20 pixels away from each other. Without doing so,
our string data will be overwritten on the
same pixel location, giving us the illusion that only one string value is generated and
displayed.
You will notice in our code above that we simply put the accumulator formula to the
column parameter of the drawString( ) method so that we can display the generated
sequence numbers in horizontal format.

In our next example, we will learn the inverse number generation. Meaning, the number
will start from the highest down to the lowest.

Example 3:

Design and develop a Java applet that generates the given inverse sequence numbers
using for loop statement. Follow the given design specification below:

1
290

Figure 6.3 An applet that generates an inverse sequence numbers

Solution: (using for loop statement only)

1. At the Microsoft NotePad, write the following code:


import java.awt.Graphics;
public class forl2 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varRow=0;
for (int i=5; i>=1; i--) {
strNo = String.valueOf(i);
varRow=varRow+20;
objG.drawString(strNo,60,varRow);
}
}
}

2. Then save the Java applet with the filename: for2.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>forl2</title>
</head>
<body>
<hr>
<applet
code=forl2.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: for2.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)
291

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac for2.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\for2.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>for2.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer for2.htm (then press the Enter key)

Sample Output:

Figure 6.3a Applet that generates an inverse sequence numbers output

Explanation:

First we declared two ordinary variables here in our program as follows:

import java.awt.Graphics;
public class forl2 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varRow=0;
.
292

.
.
Then we initialize our loop’s variable i with 5, so that the first generated sequence
number is 5. Now we have the condition: i>=1 , meaning the loop will continue iterating
as long as the value of variable i is greater than or equal to 1. The role of the
decrementation formula: i-- , means we decrease one to the value of variable i each time
the loop iterates until such time its value becomes 0 which in turn terminates the loop
operation.
.
.
.
for (int i=5; i>=1; i--) {
strNo = String.valueOf(i);
varRow=varRow+20;
objG.drawString(strNo,60,varRow);
}
}
}

We need to convert the numeric value of variable i to its equivalent string value by using
the valueOf( ) method under the String class and store it to strNo variable as follows:

strNo = String.valueOf(i);

In this way, we can display it properly at the drawString( ) method. The drawString( )
method has three parameters; the first one is the string value to display, then the numeric
value of the column and lastly the row that indicates what line to display the string value.
In our row parameter, we use the accumulator formula: varRow=varRow+20; so
that the string data will be diplayed 20 pixels away from each other. Without doing so,
our string data will be overwritten on the same pixel location, giving us the illusion that
only one string value is generated and displayed.

Example 4:

Design and develop a Java applet that generates the given inverse sequence numbers
using while loop statement. This time, it is in horizontal format. Follow the given design
specification below:

5 4 3 2 1
293

Figure 6.4 An applet that generates an inverse sequence numbers in horizontal format

Solution: (using while loop statement only)

1. At the Microsoft NotePad, write the following code:


import java.awt.Graphics;
public class whilel5 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varCol=0;
int i=5;
while (i>=1) {
strNo = String.valueOf(i);
varCol=varCol+20;
objG.drawString(strNo,varCol,20);
i--;
}
}
}

2. Then save the Java applet with the filename: while5.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>whilel5</title>
</head>
<body>
<hr>
<applet
code=whilel5.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: whilel5.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)
294

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac whilel5.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\whilel5.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>whilel5.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer whilel5.htm (then press the Enter key)

Sample Output:

Figure 6.4a Applet that generates an inverse sequence


numbers in horizontal format

Explanation:

First we declared two ordinary variables here in our program as follows:

import java.awt.Graphics;
public class whilel5 extends java.applet.Applet {
public void paint(Graphics objG) {
295

String strNo;
int varCol=0;
.
.
.
The initial value of i variable is 5. So when the program pointer evaluates or tests the
condition: i>=1, it is evaluated to True, since the value of variable i is greater than 1.
Because the condition is evaluated to true, all statements within the body of the loop are
executed:
.
.
.
int i=5;
while (i>=1) {
strNo = String.valueOf(i);
varCol=varCol+20; statements within the body of the loop
objG.drawString(strNo,varCol,20);
i--;
}
}
}

The execution of all the statements within the body of the loop are repeated until the
evaluation of the condition becomes False.
We need to convert the numeric value of variable i to its equivalent string value by using
the valueOf( ) method under the String class and store it to strNo variable as follows:

strNo = String.valueOf(i);

In this way, we can display it properly at the drawString( ) method. The drawString( )
method has three parameters; the first one is the string value to display, then the numeric
value of the column and lastly the row that indicates what line to display the string value.
In our row parameter, we use the accumulator formula: varCol=varCol+20; so that
the string data will be diplayed
20 pixels away from each other. Without doing so, our string data will be overwritten on
the same pixel location, giving us the illusion that only one string value is generated and
displayed.

Example 5:

Design and develop a Java applet that generates the given sequence numbers which is
incremented by 5 using do/while loop statement. Follow the given design specification
below:
296

5
10
15
20
25
30
35
40
45
50

Figure 6.5 An applet that generates sequence numbers incremented by 5

Solution: (using do/while loop statement only)

1. At the Microsoft NotePad, write the following code:


import java.awt.Graphics;
public class dol5 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varRow=0;
int i=5;
do {
strNo = String.valueOf(i);
varRow=varRow+20;
objG.drawString(strNo,60,varRow);
i+=5;
} while (i<=50);
}
}

2. Then save the Java applet with the filename: dol5.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>dol5</title>
</head>
<body>
<hr>
<applet
code=dol5.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: dol5.htm.


5. This time, activate the Java compiler batch file with the following steps:
297

Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac dol5.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\dol5.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>dol5.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer dol5.htm (then press the Enter key)

Sample Output:

Figure 6.5a Applet that generates sequence


numbers incremented by 5 output
298

Explanation:

First we declared two ordinary variables here in our program as follows:

import java.awt.Graphics;
public class dol5 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varRow=0;
.
.
.
The initial value of i variable is 5. So when the program pointer evaluates or tests the
condition: i<=50 (at the bottom part of the loop), it is evaluated to True, since the value
of variable i is less than 50. You will notice that in the do/while loop solution, the
condition is tested at the last part of our loop. This ensures that even if the condition is
evaluated or tested as False, the statements within the body of the loop will be executed
at least once:
.
.
.
int i=5;
do {
strNo = String.valueOf(i);
varRow=varRow+20;
objG.drawString(strNo,60,varRow);
i+=5;
} while (i<=50);
}
}

The loop will be incremented by 5 because we applied the accumulator formula: i +=5;
here in our program.
We need to convert the numeric value of variable i to its equivalent string value by using
the valueOf( ) method under the String class and store it to strNo variable as follows:

strNo = String.valueOf(i);

In this way, we can display it properly at the drawString( ) method. The drawString( )
method has three parameters; the first one is the string value to display, then the numeric
value of the column and lastly the row that indicates what line to display the string value.
In our row parameter, we use the accumulator formula: varRow=varRow+20; so
that the string data will be diplayed 20 pixels away from each other. Without doing so,
our string data will be overwritten on the same pixel location, giving us the illusion that
only one string value is generated and displayed.
299

Example 6:

Design and develop a Java applet that generates the given sequence numbers which is
decremented by 5 using while loop statement. Follow the given design specification
below:

50 45 40 35 30 25 20 15 10 5

Figure 6.6 An applet that generates sequence numbers decremented by 5

Solution: (using while loop statement only)

1. At the Microsoft NotePad, write the following code:


import java.awt.Graphics;
public class whilel6 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varCol=0;
int i=50;
while (i>=5) {
strNo = String.valueOf(i);
varCol=varCol+20;
objG.drawString(strNo,varCol,20);
i-=5;
}
}
}

2. Then save the Java applet with the filename: whilel6.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>whilel6</title>
</head>
<body>
<hr>
<applet
code=whilel6.class
width=300
height=200>
</applet>
300

<hr>
</body>
</html>

4. Now save the HTML script with the filename: whilel6.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac whilel6.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\whilel6.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>whilel6.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer whilel6.htm (then press the Enter key)

Sample Output:

Figure 6.6a Applet that generates sequence


numbers decremented by 5 output
301

Explanation:

First we declared two ordinary variables here in our program as follows:

import java.awt.Graphics;
public class whilel6 extends java.applet.Applet {
public void paint(Graphics objG) {
String strNo;
int varCol=0;
.
.
.
The initial value of i variable is 50. So when the program pointer evaluates or tests the
condition: i>=5, it is evaluated to True, since the value of variable i is greater than 5.
Because the condition is evaluated to true, all statements within the body of the loop are
executed:
.
.
.
int i=50;
while (i>=5) {
strNo = String.valueOf(i);
varCol=varCol+20;
objG.drawString(strNo,varCol,20);
i-=5;
}
}
}

The execution of all the statements within the body of the loop are repeated until the
evaluation of the condition becomes False.
We need to convert the numeric value of variable i to its equivalent string value by using
the valueOf( ) method under the String class and store it to strNo variable as follows:

strNo = String.valueOf(i);

In this way, we can display it properly at the drawString( ) method. The drawString( )
method has three parameters; the first one is the string value to display, then the numeric
value of the column and lastly the row that indicates what line to display the string value.
In our row parameter, we use the accumulator formula: varCol=varCol+20; so that
the string data will be diplayed
20 pixels away from each other. Without doing so, our string data will be overwritten on
the same pixel location, giving us the illusion that only one string value is generated and
displayed.
302

Example 7:

Design and develop a Java applet that generates the given sequence @ symbol using the
three looping statements. The number of displayed @ symbol depends on the number
specified or entered at the text field. Follow the given design specification below:

Input a number, then press Enter:


4

@@@@

Figure 6.7 An applet that generates an @ symbol

1st Solution: (using for loop statement )

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class forl3 extends Applet implements ActionListener {
TextField txtNumber;
Label lblNumber;
int varNumber= -1;
public void init() {
lblNumber = new Label("Input a number, then press Enter:");
add(lblNumber);
txtNumber = new TextField(4);
add(txtNumber);
txtNumber.addActionListener(this);
}
public void paint(Graphics objG) {
String strSymbol=" ";
int i;
for (i=0;i<varNumber;i++) {
strSymbol=strSymbol+"@";
objG.drawString(strSymbol,20,60);
}
}
public void actionPerformed(ActionEvent objE) {
if (objE.getSource() instanceof TextField)
varNumber = Integer.parseInt(txtNumber.getText());
repaint();
}
303

2. Then save the Java applet with the filename: forl3.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>forl3</title>
</head>
<body>
<hr>
<applet
code=forl3.class
width=300
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: forl3.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac forl3.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\forl3.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>forl3.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer forl3.htm (then press the Enter key)

Sample Output:
304

Figure 6.7a Applet that generates an @ symbol output

Explanation:

We created a new class named forl3 here in our program. Then we declared one text field
which we named txtNumber. We used the txtNumber object to get the number entered
by the user. The label lblNumber is declared using Java Label class, then we declare one
ordinary variable, the varNumber which is initialized with the value of -1 (negative one)
as you can see in our code below:

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class forl3 extends Applet implements ActionListener {
TextField txtNumber;
Label lblNumber;
int varNumber= -1;
.
.
.
You will notice that we actually created and add the objects we had declared at the top of
our program here in the init( ) method:
.
.
.
public void init( ) {
lblNumber = new Label("Input a number, then press Enter:");
add(lblNumber);
txtNumber = new TextField(4);
add(txtNumber);
txtNumber.addActionListener(this);
305

}
.
.
.
We can make the program to listen to the inputted number by implementing the
ActionListener interface, and connect our text field (txtNumber) to it using the
addActionListener( ) method. Then finally, we add the actionPerformed ( ) method to
complete the process:
.
.
.
public void paint(Graphics objG) {
String strSymbol=" ";
int i;
for (i=0;i<varNumber;i++) {
strSymbol=strSymbol+"@";
objG.drawString(strSymbol,20,60);
}
}
public void actionPerformed(ActionEvent objE) {
if (objE.getSource() instanceof TextField)
varNumber = Integer.parseInt(txtNumber.getText( ));
repaint( );
}
}

We are using here the strSymbol variable to increment for the specified number of @
symbol to display. Then, we finally display the @ symbol on the applet using the
drawString( ) method.
To read the numeric data from the text field, we apply the getText( ) method such as the
following syntax:

txtNumber.getText( )

This syntax returns the text string in the text field, txtNumber. For example, if the user
inputs the data “4” in txtNumber text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtNumber.getText( ))

In this way, we can now store the entered numeric data from txtNumber and store the
result to variable varNumber. This time, we can use the numeric data from varNumber in
the conditional part of our for loop statement:

for (i=0;i<varNumber;i++)

We have now finished our discussion.


306

2nd Solution: (using while loop statement )

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class whilel3 extends Applet implements ActionListener {
TextField txtNumber;
Label lblNumber;
int varNumber= -1;
public void init() {
lblNumber = new Label("Input a number, then press Enter:");
add(lblNumber);
txtNumber = new TextField(4);
add(txtNumber);
txtNumber.addActionListener(this);
}
public void paint(Graphics objG) {
String strSymbol=" ";
int i;
i=0;
while (i<varNumber) {
strSymbol=strSymbol+"@";
objG.drawString(strSymbol,20,60);
i++;
}
}
public void actionPerformed(ActionEvent objE) {
if (objE.getSource() instanceof TextField)
varNumber = Integer.parseInt(txtNumber.getText());
repaint();
}
}

2. Then save the Java applet with the filename: whilel3.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>whilel3</title>
</head>
<body>
<hr>
<applet
code=whilel3.class
width=300
height=200>
</applet>
<hr>
307

</body>
</html>

4. Now save the HTML script with the filename: whilel3.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac whilel3.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\whilel3.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>whilel3.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer whilel3.htm (then press the Enter key)

Sample Output:

Figure 6.7b Applet that generates an @ symbol output


308

Explanation:

We created a new class named whilel3 here in our program. Then we declared one text
field which we named txtNumber. We used the txtNumber object to get the number
entered by the user. The label lblNumber is declared using Java Label class, then we
declare one ordinary variable, the varNumber which is initialized with the value of -1
(negative one) as you can see in our code below:

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class whilel3 extends Applet implements ActionListener {
TextField txtNumber;
Label lblNumber;
int varNumber= -1;
.
.
.
You will notice that we actually created and add the objects we had declared at the top of
our program here in the init( ) method:
.
.
.

public void init( ) {


lblNumber = new Label("Input a number, then press Enter:");
add(lblNumber);
txtNumber = new TextField(4);
add(txtNumber);
txtNumber.addActionListener(this);
}
.
.
.
We can make the program to listen to the inputted number by implementing the
ActionListener interface, and connect our text field (txtNumber) to it using the
addActionListener( ) method. Then finally, we add the actionPerformed ( ) method to
complete the process:
.
.
.
public void paint(Graphics objG) {
String strSymbol=" ";
int i;
i=0;
while (i<varNumber) {
strSymbol=strSymbol+"@";
objG.drawString(strSymbol,20,60);
i++;
}
309

}
public void actionPerformed(ActionEvent objE) {
if (objE.getSource( ) instanceof TextField)
varNumber = Integer.parseInt(txtNumber.getText( ));
repaint( );
}
}

We are using here the strSymbol variable to increment for the specified number of @
symbol to display. Then, we finally display the @ symbol on the applet using the
drawString( ) method.
To read the numeric data from the text field, we apply the getText( ) method such as the
following syntax:

txtNumber.getText( )

This syntax returns the text string in the text field, txtNumber. For example, if the user
inputs the data “4” in txtNumber text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtNumber.getText( ))

In this way, we can now store the entered numeric data from txtNumber and store the
result to variable varNumber. This time, we can use the numeric data from varNumber in
the conditional part of our while loop statement:

while (i<varNumber)

This is again the way we end our discussion.

3rd Solution: (using do/while loop statement )

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class dol3 extends Applet implements ActionListener {
TextField txtNumber;
Label lblNumber;
int varNumber= -1;
public void init() {
lblNumber = new Label("Input a number, then press Enter:");
add(lblNumber);
txtNumber = new TextField(4);
add(txtNumber);
txtNumber.addActionListener(this);
310

}
public void paint(Graphics objG) {
String strSymbol=" ";
int i;
i=0;
do {
strSymbol=strSymbol+"@";
objG.drawString(strSymbol,20,60);
i++;
} while (i<varNumber);
}
public void actionPerformed(ActionEvent objE) {
if (objE.getSource() instanceof TextField)
varNumber = Integer.parseInt(txtNumber.getText());
repaint();
}
}

2. Then save the Java applet with the filename: dol3.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>dol3</title>
</head>
<body>
<hr>
<applet
code=dol3.class
width=300
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: dol3.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac dol3.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:
311

C:\javaprog\dol3.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>dol3.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer dol3.htm (then press the Enter key)

Sample Output:

Figure 6.7c Applet that generates an @ symbol output

Explanation:

What is very noticeable here in our program is that it always display one @ symbol every
time we run it, eventhough we haven’t specified yet how many @ symbols to display.
This is the main reason why the do/while loop is different from other looping statements,
because it is always executed at least once. In other words, whether the condition is
evaluated to true or false, the statements within the body of the loop will be performed
inspite of, since its conditional statement is positioned at the bottom part of the loop.
We created a new class named dol3 here in our program. Then we declared one text field
which we named txtNumber. We used the txtNumber object to get the number entered
by the user. The label lblNumber is declared using Java Label class, then we declare one
ordinary variable, the varNumber which is initialized with the value of -1 (negative one)
as you can see in our code below:

import java.awt.*;
import java.applet.Applet;
312

import java.awt.event.*;
public class dol3 extends Applet implements ActionListener {
TextField txtNumber;
Label lblNumber;
int varNumber= -1;
.
.
.
You will notice that we actually created and add the objects we had declared at the top of
our program here in the init( ) method:
.
.
.
public void init( ) {
lblNumber = new Label("Input a number, then press Enter:");
add(lblNumber);
txtNumber = new TextField(4);
add(txtNumber);
txtNumber.addActionListener(this);
}
.
.
.
We can make the program to listen to the inputted number by implementing the
ActionListener interface, and connect our text field (txtNumber) to it using the
addActionListener( ) method. Then finally, we add the actionPerformed ( ) method to
complete the process:
.
.
.
public void paint(Graphics objG) {
String strSymbol=" ";
int i;
i=0;
do {
strSymbol=strSymbol+"@";
objG.drawString(strSymbol,20,60);
i++;
} while (i<varNumber);
}
public void actionPerformed(ActionEvent objE) {
if (objE.getSource( ) instanceof TextField)
varNumber = Integer.parseInt(txtNumber.getText( ));
repaint( ;
}
}

We are using here the strSymbol variable to increment for the specified number of @
symbol to display. Then, we finally display the @ symbol on the applet using the
drawString( ) method.
313

To read the numeric data from the text field, we apply the getText( ) method such as the
following syntax:

txtNumber.getText( )

This syntax returns the text string in the text field, txtNumber. For example, if the user
inputs the data “4” in txtNumber text field, this is actually a text string value. We need to
convert it to its equivalent numeric value using the parseInt( ) method under the Integer
class of the Java language such as the following syntax:

Integer.parseInt(txtNumber.getText( ))

In this way, we can now store the entered numeric data from txtNumber and store the
result to variable varNumber. This time, we can use the numeric data from varNumber in
the conditional part of our do/while loop statement:

while (i<varNumber)

This time, I am sure you have already gained enough technical foundation about how the
looping statements work. The knowledge and skills that you have learned from the
preceding examples are essential to understand how they can be applied with controls or
objects.

Some Famous Mathematical Programs


In the history of programming, there is always a legend. This legend usually are some
mathematical formulas or equations to solve mathematical problems. Some of these are
the programs for calculating the factorial value of N! (where N is a number) and the
power value of the base number with its corresponding exponent. We can solve these two
mathematical problems using the looping statement. Without using the looping statement
in our program, solving these problems could be impossible to accomplish. Let us start
solving them now.

Example 8:

Design and develop a Java applet that computes the factorial value of N! (as input) and
displays the result. Follow the given design specification below:
314

Compute
Enter a number: 5

The Factorial value: 120

Text fields Command button

Figure 6.8 An applet that calculates the factorial value

Text field 1 Text field 2 Button

Solution: (using while loop statement )

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class factor1 extends Applet implements ActionListener {
TextField txtNum, txtFactor;
Label lblNum, lblFactor;
Button cmdCompute;
public void init() {
lblNum = new Label("Enter a number:");
add(lblNum);
txtNum = new TextField(4);
add(txtNum);
cmdCompute= new Button("Compute");
add(cmdCompute);
cmdCompute.addActionListener(this);
lblFactor = new Label("The Factorial value:");
add(lblFactor);
txtFactor = new TextField(8);
add(txtFactor);
}
public void actionPerformed(ActionEvent objEvent) {
int varNum;
int varIterate;
long varFactor;
if (objEvent.getSource() == cmdCompute) {
varNum=Integer.parseInt(txtNum.getText());
varFactor = 1;
varIterate = varNum;
while (varIterate>=1) {
varFactor=varFactor*varIterate;
varIterate-=1;
}
txtFactor.setText(String.valueOf(varFactor));
}
}
315

2. Then save the Java applet with the filename: factor1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>factor1</title>
</head>
<body>
<hr>
<applet
code=factor1.class
width=250
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: factor1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac factor1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\factor1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>factor1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer factor1.htm (then press the Enter key)

Sample Output:
316

Figure 6.8a An applet that calculates the factorial value output

Explanation:

We created a new class named factor1 here in our program. Then we declared two text
fields which we named txtNum and txtFactor. We used the txtNum object to get the
number entered by the user and the txtFactor to display the factorial value. We are
declaring one command button which we named cmdCompute using the Button class.
The labels lblNum and lblFactor are declared using the Label class. We can see its
implementation below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class factor1 extends Applet implements ActionListener {
TextField txtNum, txtFactor;
Label lblNum, lblFactor;
Button cmdCompute;
.
.
.
You will notice that we actually created and add the objects we had declared at the top of
our program here in the init( ) method:
.
.
.
public void init( ) {
lblNum = new Label("Enter a number:");
add(lblNum);
txtNum = new TextField(4);
add(txtNum);
cmdCompute= new Button("Compute");
add(cmdCompute);
317

cmdCompute.addActionListener(this);
lblFactor = new Label("The Factorial value:");
add(lblFactor);
txtFactor = new TextField(8);
add(txtFactor);
}
.
.
.
Here in our sample input/output dialogue, the factorial value of 5 is 120. Here is the
detailed computation:

5! = 5*4*3*2*1
= 120

This kind of computation is best suited using the decrementation formula: I:= I - 1; since
the iteration (I) will decrease by 1 each time the loop operation is being performed. We
can also reverse the computation such as the following:

5! = 1*2*3*4*5
= 120

Since the product of the value is multiplied to its succeeding iteration number until the
value of N is reached, then the incrementation formula: I: I + 1 is best suited for this kind
of computation. In our program below, we apply the decrementation formula using the
shortcut format:

I - =1

Here in our program, the variable I is replaced by more programmer-friendly name which
is varIterate, thus our shortcut formula is:

varIterate - = 1

A shortcut for the decrementation formula: varIterate = varIterate - 1.


We initialize the variable varFactor with the value of 1 so that the computer would know
its first value that it is 1 not zero (since usually we initialize the variable with a 0 value).
The data type of varFactor variable is long so that it can accommodate bigger numbers. In
this way, the computed value of the factorial is accurate all the time.
To compute the value of N(!): multiply the product of N to its preceding number until the
iteration (varIterate) reaches the value of 1. We can accomplish this task by using the
while loop statement that states:

while (varIterate>=1) {
varFactor=varFactor*varIterate;
varIterate-=1;
}
318

Finally, we have displayed the calculated factorial value using the valueOf( ) method of
the String class to properly display the numeric value at the text field. You will also
notice that we use the parseInt( ) method so that the number entered by the user at the
text field can be converted to its numeric format, since by default, any data entered at
the text field will be treated or formatted as text string. In this way, the computation of
data in our equation will be correct.
Finally, we add the actionPerformed( ) method to complete the process:
.
.
.
public void actionPerformed(ActionEvent objEvent) {
int varNum;
int varIterate;
long varFactor;
if (objEvent.getSource( ) == cmdCompute) {
varNum=Integer.parseInt(txtNum.getText( ));
varFactor = 1;
varIterate = varNum;
while (varIterate>=1) {
varFactor=varFactor*varIterate;
varIterate-=1;
}
txtFactor.setText(String.valueOf(varFactor));
}
}
}

It’s pretty cool, isn’t it? That’s it in Java, we can accomplish the solution for this kind of
mathematical problem, like the way we do in other programming languages. Let us go to
the next popular mathematical program which is called: power value.

Example 9:

Design and develop a Java applet that computes the power value of the input base and
exponent numbers. Then display the result. Follow the given design specification below:

Enter the base and exponent numbers:


Command button
5 3 Compute

Text field 3
The Power value: 125
319

Figure 6.9 An applet that computes the power value

Solution: (using do-while loop statement )

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class power1 extends Applet implements ActionListener {
TextField txtBase, txtExponent, txtPower;
Label lblBase, lblPower;
Button cmdCompute;
public void init() {
lblBase=new Label("Enter the base and exponent numbers:");
add(lblBase);
txtBase = new TextField(4);
add(txtBase);
txtExponent = new TextField(2);
add(txtExponent);
cmdCompute= new Button("Compute");
add(cmdCompute);
cmdCompute.addActionListener(this);
lblPower = new Label("The Power value:");
add(lblPower);
txtPower = new TextField(10);
add(txtPower);
}
public void actionPerformed(ActionEvent objEvent) {
int varBase, varExponent;
int varIterate;
long varPower;
if (objEvent.getSource() == cmdCompute) {
varBase=Integer.parseInt(txtBase.getText());
varExponent=Integer.parseInt(txtExponent.getText());
varPower = 1;
varIterate = varExponent;
do {
varPower= varPower*varBase;
varIterate-=1;
} while (varIterate!=0);
txtPower.setText(String.valueOf(varPower));
}
}
}

2. Then save the Java applet with the filename: power1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
320

<html>
<!- Web page written with Java Applet>
<head>
<title>power1</title>
</head>
<body>
<hr>
<applet
code=power1.class
width=200
height=150>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: power1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac power1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\power1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>power1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer power1.htm (then press the Enter key)

Sample Output:
321

Figure 6.9a An applet that computes the power value output

Explanation:

We created a new class named power1 here in our program. Then we declared three text
fields which we named txtBase, txtExponent, and txtPower. We used the txtBase and
txtExponent objects to get the numbers entered by the user and the txtPower to display
the power value. We are declaring one command button which we named cmdCompute
using the Button class. The labels lblBase and lblPower are declared using the Label
class. We can see its implementation below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class power1 extends Applet implements ActionListener {
TextField txtBase, txtExponent, txtPower;
Label lblBase, lblPower;
Button cmdCompute;
.
.
.
You will notice that we actually created and add the objects we had declared at the top of
our program here in the init( ) method:
.
.
.
public void init( ) {
lblBase=new Label("Enter the base and exponent numbers:");
add(lblBase);
txtBase = new TextField(4);
add(txtBase);
txtExponent = new TextField(2);
322

add(txtExponent);
cmdCompute= new Button("Compute");
add(cmdCompute);
cmdCompute.addActionListener(this);
lblPower = new Label("The Power value:");
add(lblPower);
txtPower = new TextField(10);
add(txtPower);
}
.
.
.
Here in our sample input/output dialogue, the power value of base number 5 and
exponent number 3 is 125. Here is the detailed computation:

53 = 5*5*5
= 125

We can use the incrementation or decrementation formula here in this mathematical


program to control the loop. We can observe that the loop iteration is controlled by the
exponent number (in this case, the loop will be performed 3 times to compute the power
value). Since the exponent number determines how many times the loop is being
performed, therefore we store the value of exponent number (entered by the user) to the
variable that controls the loop (the varIterate variable):

varIterate = varExponent;

Here in our program, the variable I (for Incrementation) is replaced by more programmer-
friendly name which is varIterate, thus our shortcut formula is:

varIterate - = 1

A shortcut for the decrementation formula: varIterate = varIterate - 1.

We initialize the variable varPower with the value of 1 so that the computer would know
its first value that it is 1 not zero (since usually we initialize the variable with a 0 value).
The data type of varPower variable is intentionally declared as long so that it can
accommodate bigger numbers. In this way, the computed power value is accurate all the
time.
To compute the power value is to simply multiply the base number times the exponent
number. In this case, the base number 5 is multiplied 3 times, since the exponent is 3. We
can accomplish this task by using the do-while loop statement that states:

do {
varPower= varPower*varBase;
varIterate-=1;
} while (varIterate!=0);
323

The code above means the equation varPower=varPower*varBase is executed as long as


the variable varIterate is not equal to zero. The zero will only be reached through the
decrementation formula: varIterate -= 1. In this case, the entered exponent number 3 is
reduced by 1 every time the loop is performed. On the third time the loop is executed, the
value of varIterate variable reaches to 0. This is the only time the loop operation will be
terminated or stopped.
Finally, we have displayed the calculated power value using the valueOf( ) method of the
String class to properly display the numeric value at the text field. You will also notice
that we use the parseInt( ) method so that the number entered by the user at the text field
can be converted to its numeric format, since by default, any data entered at the text field
will be treated or formatted as text string. In this way, the computation of data in our
equation will be correct.
Finally, we add the actionPerformed( ) method to complete the process:
.
.
.
public void actionPerformed(ActionEvent objEvent) {
int varBase, varExponent;
int varIterate;
long varPower;
if (objEvent.getSource( ) == cmdCompute) {
varBase=Integer.parseInt(txtBase.getText( ));
varExponent=Integer.parseInt(txtExponent.getText( ));
varPower = 1;
varIterate = varExponent;
do {
varPower= varPower*varBase;
varIterate-=1;
} while (varIterate!=0);
txtPower.setText(String.valueOf(varPower));
}
}
}

Using Scrolling List ( List Box) Controls


The Scrolling List (List box) control is an ideal way of presenting a list of data to the
user. In fact, the Scrolling list is an effective way to present a large number of data to the
user in a limited amount of space. The user can browse the data in the scrolling list or
select one or more items for processing purposes. The process could be transferring the
chosen items from the scrolling list to a cart (or a transfer of items from one scrolling list
to another). The transfer can also be from a scrolling list to a text field or to a Choice
control.We will discuss the Choice control later. In the computerized grocery store
system, the items could be the products which the buyer can select and buy.
324

Example 10:

Design and develop a Java applet that demonstrates how to preload a collection of items
to a Scrolling list. Follow the given design specification below:

Preloaded Items:

Milan
Paris
Madrid
Tokyo Scrolling list
Manila
New Delhi
Kuala Lumpur
San Francisco

Figure 6.10 An applet that uses Scrolling list with preloaded items

Solution:

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class listbox2 extends Applet {
Label lblMessage;
List lstBox1;
public void init() {
lblMessage = new Label("Preloaded Items:");
add(lblMessage);
lstBox1 = new List(8,true);
lstBox1.add("Milan");
lstBox1.add("Paris");
lstBox1.add("Madrid");
lstBox1.add("Tokyo");
lstBox1.add("Manila");
lstBox1.add("New Delhi");
lstBox1.add("Kuala Lumpur");
lstBox1.add("San Francisco");
add(lstBox1);
}
}
325

2. Then save the Java applet with the filename: listbox2.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>listbox2</title>
</head>
<body>
<hr>
<applet
code=listbox2.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: listbox2.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac listbox2.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\listbox2.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>listbox2.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer listbox2.htm (then press the Enter key)

Sample Output:
326

Figure 6.10a Applet that uses Scrolling list with preloaded items

Explanation:

In this simple example about Scrolling list, we just simply pre-loaded the Scrolling list
box with items which we want to display. So we just use the following code:
.
.
.
public void init( ) {
lblMessage = new Label("Preloaded Items:");
add(lblMessage);
lstBox1 = new List(8,true);
lstBox1.add("Milan");
lstBox1.add("Paris");
lstBox1.add("Madrid");
lstBox1.add("Tokyo");
lstBox1.add("Manila");
lstBox1.add("New Delhi");
lstBox1.add("Kuala Lumpur");
lstBox1.add("San Francisco");
add(lstBox1);
}
}

The List(8,true) declaration at the init( ) method simply means we want to display the 8
items and indicate that we allow multiple selections by passing a second parameter and
set it to true. The Scrolling list has built-in methods for adding, removing and retrieving
collection of items or data. In this case, we applied the built-in method for adding an item
327

into the Scrolling list using the add( ) method. Now, how about choosing an item from
the Scrolling list and display it into the text field? Let us have an example about this
particular requirement.

Example 11:

Design and develop a Java applet that demonstrates how to preload a collection of items
to a Scrolling list. When the user chooses an item at the Scrolling list by double-clicking
it, that particular item will be displayed at the text field. Follow the given design
specification below:

Cities to Choose:
Milan
Paris
Madrid Scrolling list
Tokyo

Manila Text field

Figure 6.11 An applet that uses Scrolling list and Text field

Note:
When the user scrolls-down the scrolling list, the Manila item can be selected by double-clicking it, then
the item “Manila” will be displayed at the text field.

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class listbox6 extends Applet implements ActionListener {
Label lblMessage;
TextField txtText1;
List lstBox1;

public void init() {


lblMessage = new Label("Cities to Choose:");
328

add(lblMessage);
lstBox1 = new List(4,false);
lstBox1.add("Milan");
lstBox1.add("Paris");
lstBox1.add("Madrid");
lstBox1.add("Tokyo");
lstBox1.add("Manila");
lstBox1.add("New Delhi");
lstBox1.add("Kuala Lumpur");
lstBox1.add("San Francisco");
add(lstBox1);
lstBox1.addActionListener(this);
txtText1 = new TextField(20);
add(txtText1);
}

public void actionPerformed(ActionEvent objEvent) {


if (objEvent.getSource()==lstBox1)
txtText1.setText(((List)objEvent.getSource()).getSelectedItem());
}
}

2. Then save the Java applet with the filename: listbox6.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>listbox6</title>
</head>
<body>
<hr>
<applet
code=listbox6.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: listbox6.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac listbox6.java (then press the Enter key)


329

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\listbox6.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>listbox6.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer listbox6.htm (then press the Enter key)

Sample Output:

Figure 6.11a Applet that uses Scrolling list and Text field output

Explanation:

In this example, the user chooses the Manila item by double-clicking it using the mouse.
That is why the item Manila is displayed at the text field. In our applet, the Manila item
is not yet displayed, because we limit the displayed items into 4. So the user needs to
scroll-down the scrolling list to see the remaining items below.
.
.
.
public void init( ) {
lblMessage = new Label("Cities to Choose:");
add(lblMessage);
330

lstBox1 = new List(4,false);


lstBox1.add("Milan");
lstBox1.add("Paris");
lstBox1.add("Madrid");
lstBox1.add("Tokyo");
lstBox1.add("Manila");
lstBox1.add("New Delhi");
lstBox1.add("Kuala Lumpur");
lstBox1.add("San Francisco");
add(lstBox1);
lstBox1.addActionListener(this);
txtText1 = new TextField(20);
add(txtText1);
}

What is more noticeable to this example is that we change the scrolling list declaration to
List(4, false) compared to the previous example. Actually, this parameter value:4
indicates that we want to display only the top 4 items in our scrolling list, and the user
can only choose one item at a time, since we set the second parameter to false. This is
also the reason why we can see the up and down arrow objects at the right side of our
scrolling list.
You will also notice that we connect the addActionListener( ) method to the scrolling list
lstBox1 so that whatever the user selected, it will be displayed at the text field. And this
event will be accomplished by applying the actionPerformed( ) function, as we can see on
the following code:
.
.
.
public void actionPerformed(ActionEvent objEvent) {
if (objEvent.getSource( )==lstBox1)
txtText1.setText(((List)objEvent.getSource( )).getSelectedItem( ));
}
}

This is how we end our discussion for this second example about scrolling list. I hope
you enjoyed it!

Example 12:

Design and develop a Java applet that demonstrates how to preload a collection of items
to a Scrolling list and with the capability to remove the item by double-clicking it.
Follow the given design specification below:
331

Choose Cities to Remove:

Milan
Paris
Madrid Scrolling list
Tokyo
Manila
New Delhi
Kuala Lumpur
San Francisco

Figure 6.12 An applet that uses Scrolling list with Remove item capability

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class listbox7 extends Applet implements ActionListener {
Label lblMessage;
List lstBox1;
public void init() {
lblMessage = new Label("Choose Cities to Remove:");
add(lblMessage);
lstBox1 = new List(8,false);
lstBox1.add("Milan");
lstBox1.add("Paris");
lstBox1.add("Madrid");
lstBox1.add("Tokyo");
lstBox1.add("Manila");
lstBox1.add("New Delhi");
lstBox1.add("Kuala Lumpur");
lstBox1.add("San Francisco");
add(lstBox1);
lstBox1.addActionListener(this);
}
public void actionPerformed(ActionEvent objEvent) {
if (objEvent.getSource()==lstBox1)
lstBox1.remove(lstBox1.getSelectedIndex());
}
}

2. Then save the Java applet with the filename: listbox7.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
332

<html>
<!- Web page written with Java Applet>
<head>
<title>listbox7</title>
</head>
<body>
<hr>
<applet
code=listbox7.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: listbox7.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac listbox7.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\listbox7.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>listbox7.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer listbox7.htm (then press the Enter key)

Sample Output:
333

Figure 6.12a Applet that uses Scrolling list with


Remove item capability output

Explanation:

In this example about Scrolling list, we just simply pre-loaded the Scrolling list box with
items which we want to display. So we just use the following code:
.
.
.
public void init( ) {
lblMessage = new Label("Choose Cities to Remove:");
add(lblMessage);
lstBox1 = new List(8,false);
lstBox1.add("Milan");
lstBox1.add("Paris");
lstBox1.add("Madrid");
lstBox1.add("Tokyo");
lstBox1.add("Manila");
lstBox1.add("New Delhi");
lstBox1.add("Kuala Lumpur");
lstBox1.add("San Francisco");
add(lstBox1);
lstBox1.addActionListener(this);
}
.
.
.
The List(8, false) declaration at the init( ) method simply means we want to display the 8
items and indicate that we allow single selection only by passing a second parameter and
334

set it to false. The Scrolling list has built-in methods for adding, removing and retrieving
collection of items or data. In this case, we applied the built-in method for adding an item
into the Scrolling list using the add( ) method.
Now to remove the selected item, we applied the remove( int ) method which we embed
within the actionPerformed( ) function, as you can see in our code below:

public void actionPerformed(ActionEvent objEvent) {


if (objEvent.getSource( )==lstBox1)
lstBox1.remove(lstBox1.getSelectedIndex( ));
}
}

Now we need to determine the selected item by getting its selected index (we need this
as an integer value to be passed as a parameter to the remove ( ) method ). So we applied
here the getSelectedIndex( ) method of the Scrolling list class.

Example 13:

Design and develop a Java applet that demonstrates how to preload a collection of items
to a Scrolling list and with the capability to remove the item. First, the user should select
the item to remove by just clicking it.Then the user should click the Remove command
button to finally delete the item from the list . Follow the given design specification
below:

Choose Cities to Remove:

Milan
Paris
Scrolling list
Madrid
Tokyo
Manila
Remove Button
New Delhi
Kuala Lumpur
San Francisco

Figure 6.13 An applet that uses Scrolling list with Remove command button

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
335

public class listbox8 extends Applet implements


ItemListener,ActionListener {
Label lblMessage;
List lstBox1;
Button cmdRemove;
int varListIndex;

public void init() {


lblMessage = new Label("Choose Cities to Remove:");
add(lblMessage);
lstBox1 = new List(8,false);
lstBox1.add("Milan");
lstBox1.add("Paris");
lstBox1.add("Madrid");
lstBox1.add("Tokyo");
lstBox1.add("Manila");
lstBox1.add("New Delhi");
lstBox1.add("Kuala Lumpur");
lstBox1.add("San Francisco");
add(lstBox1);
lstBox1.addItemListener(this);
cmdRemove = new Button("Remove");
add(cmdRemove);
cmdRemove.addActionListener(this);

public void itemStateChanged(ItemEvent objE) {


if (objE.getItemSelectable()==lstBox1)
varListIndex = lstBox1.getSelectedIndex();
}

public void actionPerformed(ActionEvent objEvent) {


if (objEvent.getSource()==cmdRemove)
lstBox1.remove(varListIndex);

}
}

2. Then save the Java applet with the filename: listbox8.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>listbox8</title>
</head>
<body>
<hr>
<applet
code=listbox8.class
width=200
height=200>
</applet>
336

<hr>
</body>
</html>

4. Now save the HTML script with the filename: listbox8.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac listbox8.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\listbox8.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>listbox8.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer listbox8.htm (then press the Enter key)

Sample Output:
337

Figure 6.13a Applet that uses Scrolling list with


Remove command button output

Explanation:

What we can observe here in our code is the two implementations of ItemListener and
ActionListner interfaces. We need these two implementations for both the Scrolling list
and Command button controls, wherein we instruct the Scrolling list object to listen to
the selection of item and to listen also when the user clicks the command button.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class listbox8 extends Applet implements ItemListener,ActionListener {


Label lblMessage;
List lstBox1;
Button cmdRemove;
int varListIndex;
.
.
.
We declared the varListIndex ordinary variable at the top of our program so that it can be
seen globally by the functions that need it. In this example, the itemStateChanged and
actionPerformed functions both used it.
The List(8, false) declaration at the init( ) method simply means we want to display the 8
items and indicate that we allow single selection only by passing a second parameter and
set it to false. The Scrolling list has built-in methods for adding, removing and retrieving
338

collection of items or data. In this case, we applied the built-in method for adding an item
into the Scrolling list using the add( ) method.
.
.
.
public void init( ) {
lblMessage = new Label("Choose Cities to Remove:");
add(lblMessage);
lstBox1 = new List(8,false);
lstBox1.add("Milan");
lstBox1.add("Paris");
lstBox1.add("Madrid");
lstBox1.add("Tokyo");
lstBox1.add("Manila");
lstBox1.add("New Delhi");
lstBox1.add("Kuala Lumpur");
lstBox1.add("San Francisco");
add(lstBox1);
lstBox1.addItemListener(this);
cmdRemove = new Button("Remove");
add(cmdRemove);
cmdRemove.addActionListener(this);

}
.
.
.
You will notice that we need to connect the addItemListener( ) method to the lstBox1 and
addActionListener( ) method to the cmdRemove button. The addItemListener( ) is
applied when the user selects an item in the scrolling list, while the addActionListener( )
is used to listen when the user clicks the command button, cmdRemove. They can be
finally accomplished through the following functions:
.
.
.
public void itemStateChanged(ItemEvent objE) {
if (objE.getItemSelectable( )==lstBox1)
varListIndex = lstBox1.getSelectedIndex( );
}

public void actionPerformed(ActionEvent objEvent) {


if (objEvent.getSource( )==cmdRemove)
lstBox1.remove(varListIndex);

}
}

We are determining here if there is a change in the state of an item in the scrolling list
(there is a change if the user selects one of them). Now if there is, we simply get the
index of the selected item and store it to the variable varListIndex. We need the index
339

number of the selected item for passing it as a parameter to the remove( ) method of the
Scrolling list class. In this way, we can remove the selected item.

Example 14:

Design and develop a Java applet that demonstrates how to preload a collection of items
to a Scrolling list and with the capability of adding more items into it. Follow the given
design specification below:

Add more colors, then press Enter:


Text field
Blue

Violet
Gray
Scrolling list

Figure 6.14 An applet that uses Scrolling list with add an item capability

Solution:

1. At the Microsoft NotePad, write the following code:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class listbox9 extends Applet implements ActionListener {


Label lblMessage;
TextField txtText1;
List lstBox1;
String strColor=" ";

public void init() {


lblMessage = new Label("Add more colors,then press Enter:");
add(lblMessage);
txtText1 = new TextField(15);
add(txtText1);
txtText1.addActionListener(this);
lstBox1 = new List(10,false);
lstBox1.add("Violet");
340

lstBox1.add("Gray");
add(lstBox1);

public void actionPerformed(ActionEvent objE) {


strColor = txtText1.getText();
lstBox1.add(strColor);
repaint();
}
}

2. Then save the Java applet with the filename: listbox9.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>listbox9</title>
</head>
<body>
<hr>
<applet
code=listbox9.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: listbox9.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac listbox9.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\listbox9.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>listbox9.htm (then press the Enter key)


341

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer listbox9.htm (then press the Enter key)

Sample Output:

Figure 6.14a Applet that uses Scrolling list with


add an item capability output

Explanation:

We declared here a string variable strColor to hold the text string entered by the user at
the text field. This strColor variable will also serve as the parameter for the add( )
method of the Scrolling list class, later on in our program.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class listbox9 extends Applet implements ActionListener {


Label lblMessage;
TextField txtText1;
List lstBox1;
String strColor=" ";
.
.
.
342

You will notice in our code below that we preloaded only two items to our scrolling list.
This is because we want the users to add more colors they know into the scrolling list:
.
.
.
public void init( ) {
lblMessage = new Label("Add more colors,then press Enter:");
add(lblMessage);
txtText1 = new TextField(15);
add(txtText1);
txtText1.addActionListener(this);
lstBox1 = new List(10,false);
lstBox1.add("Violet");
lstBox1.add("Gray");
add(lstBox1);

}
.
.
.

We instruct the computer to add the item entered by the user at the text field into the
scrolling list as show in the ActionPerfored( ) function below:
.
.
.

public void actionPerformed(ActionEvent objE) {


strColor = txtText1.getText( );
lstBox1.add(strColor);
repaint( );
}
}

Example 15:

Design and develop a Java applet that demonstrates how to preload a collection of items
to a Scrolling list. The program should be able to display one or more selected items on
another scrolling list. Follow the given design specification below:
343

Choose the food you like:

Hamburger
Cheeseburger
Baconburger Scrolling list 1
French Fries
Macaroni Salad
Spaghetti

French Fries
Spaghetti Scrolling list 2

Figure 6.15 An applet with two Scrolling lists

Solution:

1. At the Microsoft NotePad, write the following code:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class listbox10 extends Applet implements ActionListener {


Label lblMessage;
List lstBox1, lstBox2;
String strFood=" ";
public void init( ) {
lblMessage = new Label("Choose the food you like:");
add(lblMessage);
lstBox1 = new List(8,false);
lstBox1.add("Hamburger");
lstBox1.add("Cheeseburger");
lstBox1.add("Baconburger");
lstBox1.add("French Fries");
lstBox1.add("Macaroni Salad");
lstBox1.add("Spaghetti");
add(lstBox1);
lstBox1.addActionListener(this);
lstBox2 = new List(8,false);
add(lstBox2);
}
344

public void actionPerformed(ActionEvent objE) {


if (objE.getSource() == lstBox1) {
strFood = lstBox1.getSelectedItem();
lstBox2.add(strFood);
repaint();
}

}
}

2. Then save the Java applet with the filename: listbox10.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>listbox10</title>
</head>
<body>
<hr>
<applet
code=listbox10.class
width=200
height=300>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: listbox10.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac listbox10.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\listbox10.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>listbox10.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:
345

C:\javaprog>appletviewer listbox10.htm (then press the Enter key)

Sample Output:

Figure 6.15a An applet with two Scrolling lists output

Explanation:

Here in our example, the user selected and double-clicked the items “French Fries” and
“Spaghetti” in scrolling list 1. That is why they are displayed at scrolling list 2. When the
user selects and double-clicks other items from scrolling list 1, these items will be
displayed at the scrolling list box 2.
We declared here a string variable strFood to hold the item selected by the user from the
first scrolling list. This strFood variable will also serve as the parameter for the add( )
method of the scrolling list 2 , later on in our program.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class listbox10 extends Applet implements ActionListener {


Label lblMessage;
List lstBox1, lstBox2;
String strFood=" ";
.
.
346

.
We connect the addActionListener( ) method to lstBox1 control, so that it would learn
once an item is being selected:
.
.
.
public void init( ) {
lblMessage = new Label("Choose the food you like:");
add(lblMessage);
lstBox1 = new List(8,false);
lstBox1.add("Hamburger");
lstBox1.add("Cheeseburger");
lstBox1.add("Baconburger");
lstBox1.add("French Fries");
lstBox1.add("Macaroni Salad");
lstBox1.add("Spaghetti");
add(lstBox1);
lstBox1.addActionListener(this);
lstBox2 = new List(8,false);
add(lstBox2);
}
.
.
.
The selection of an item in scrolling list 1 will trigger the actionPerformed function to
execute, thus the selected item will be stored to the variable strFood and will be passed at
the same time as a parameter to the add( ) method of lstBox2 control.
.
.
.
public void actionPerformed(ActionEvent objE) {
if (objE.getSource() == lstBox1) {
strFood = lstBox1.getSelectedItem( );
lstBox2.add(strFood);
repaint( );
}

}
}

Example 16:

Design and develop a Java applet that demonstrates how to preload a collection of items
to a Scrolling list. The program should be able to transfer one or more selected items to
and from another scrolling list. Follow the given design specification below:
347

Double-click to transfer to other Scrolling list:


Scrolling list 2
Milan Madrid
Tokyo Paris
Manila
San Francisco
Kuala Lumpur
New Delhi

Figure 6.16 An applet with two scrolling lists with transfer of item capability

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class listbox11 extends Applet implements ItemListener {


Label lblMessage;
List lstBox1, lstBox2;
public void init() {
lblMessage = new Label("Double-click to transfer to other Scrolling
list:");
add(lblMessage);
lstBox1 = new List(8,false);
lstBox1.add("Milan");
lstBox1.add("Paris");
lstBox1.add("Madrid");
lstBox1.add("Tokyo");
lstBox1.add("Manila");
lstBox1.add("New Delhi");
lstBox1.add("Kuala Lumpur");
lstBox1.add("San Francisco");
add(lstBox1);
lstBox1.addItemListener(this);
lstBox2 = new List(8,false);
add(lstBox2);
lstBox2.addItemListener(this);
}

public void itemStateChanged(ItemEvent objE) {


if (objE.getItemSelectable()==lstBox1) {
lstBox2.add(lstBox1.getSelectedItem());
lstBox1.remove(lstBox1.getSelectedIndex());
348

repaint();
}
else if (objE.getItemSelectable()==lstBox2) {
lstBox1.add(lstBox2.getSelectedItem());
lstBox2.remove(lstBox2.getSelectedIndex());
repaint();
}
}
}

2. Then save the Java applet with the filename: listbox11.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>listbox11</title>
</head>
<body>
<hr>
<applet
code=listbox11.class
width=350
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: listbox11.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac listbox11.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\listbox11.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>listbox11.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:
349

C:\javaprog>appletviewer listbox11.htm (then press the Enter key)

Sample Output:

Figure 6.16a Applet with two scrolling lists with


transfer of item capability output

Explanation:

Here in our example, the user double-clicks the items “Madrid” and “Paris” in scrolling
list 1. That is why these items are transferred to scrolling list 2, as what we can see in the
figure. Now if the user double-clicks again an item in scrolling list 1, this particular item
will be transferred to scrolling list 2. In the case where the user double-clicks an item in
scrolling list 2, this particular item will be transferred to scrolling list 1. You can try it, to
see for yourself how this program works.
Like the way we have done previously, to preload the scrolling list with items, we use the
following code:
.
.
.
public void init( ) {
lblMessage = new Label("Double-click to transfer to other Scrolling list:");
add(lblMessage);
lstBox1 = new List(8,false);
lstBox1.add("Milan");
lstBox1.add("Paris");
lstBox1.add("Madrid");
lstBox1.add("Tokyo");
350

lstBox1.add("Manila");
lstBox1.add("New Delhi");
lstBox1.add("Kuala Lumpur");
lstBox1.add("San Francisco");
add(lstBox1);
lstBox1.addItemListener(this);
lstBox2 = new List(8,false);
add(lstBox2);
lstBox2.addItemListener(this);
}
.
.
.
You will notice that we connect the addItemListener( ) method to lstBox1 and lstBox2,
because we want them to be able to know if one of the items belonged to them is selected
by the user.
.
.
.
public void itemStateChanged(ItemEvent objE) {
if (objE.getItemSelectable( )==lstBox1) {
lstBox2.add(lstBox1.getSelectedItem( ));
lstBox1.remove(lstBox1.getSelectedIndex( ));
repaint( );
}
else if (objE.getItemSelectable( )==lstBox2) {
lstBox1.add(lstBox2.getSelectedItem( ));
lstBox2.remove(lstBox2.getSelectedIndex( ));
repaint( );
}
}
}

As you will observe in our code above, if the item in the lstBox1 (Scrolling list 1) is
currently selected, that item will be added to lstBox2 (Scrolling list 2). At the same time,
we have to remove that selected item from Scrolling list 1 using the remove( ) and
getSelectedIndex( ) methods of the List class.
You will also observe that both lstBox1 and lstBox2 have similar code so that they will
work and produce the same result such as when we transfer an item from scrolling list 1
into scrolling list 2, the selected item will also be deleted from scrolling list 1. Now if we
want to transfer an item from scrolling list 2 into scrolling list 1, the selected item will
also be deleted from scrolling list 2.

Example 17:

Design and develop a Java applet that should apply the add( ), remove( ), and clear( )
methods of the scrolling list object. Follow the given design specification below:
351

Item to add:
Add Delete Wipe 3 Buttons
Text field 1

Scrolling list

No. of Items:

Text field 2
Figure 6.17 An applet that can add, delete or wipe out the items

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class listbox12 extends Applet implements ActionListener {
Box1 Panel1;
Button1 Panel2;
public void init() {
setLayout(new GridLayout(1,2));
Panel1 = new Box1();
Panel2 = new Button1();
add(Panel1);
Panel2.cmdAdd.addActionListener(this);
Panel2.cmdDelete.addActionListener(this);
Panel2.cmdWipe.addActionListener(this);
add(Panel2);
}
public void actionPerformed(ActionEvent objE) {
int varNumItem,varIndex;
if (objE.getSource()==Panel2.cmdAdd) {
Panel1.strColor = Panel1.txtText1.getText();
Panel1.lstBox1.add(Panel1.strColor);
varNumItem = Panel1.lstBox1.getItemCount();
352

Panel1.txtNumItem.setText(String.valueOf(varNumItem));
repaint();
}
else if (objE.getSource()==Panel2.cmdDelete) {
varIndex = Panel1.lstBox1.getSelectedIndex();
Panel1.lstBox1.remove(varIndex);
varNumItem = Panel1.lstBox1.getItemCount();
Panel1.txtNumItem.setText(String.valueOf(varNumItem));
repaint();
}
else if (objE.getSource()==Panel2.cmdWipe) {
Panel1.lstBox1.removeAll();
varNumItem = Panel1.lstBox1.getItemCount();
Panel1.txtNumItem.setText(String.valueOf(varNumItem));
repaint();
}
}
}
class Box1 extends Panel {
Label lblMessage,lblNumItem;
TextField txtText1, txtNumItem;
List lstBox1;
String strColor=" ";
Box1() {
lblMessage = new Label("Item to add:");
add(lblMessage);
txtText1 = new TextField(15);
add(txtText1);
lstBox1 = new List(10,false);
add(lstBox1);
lblNumItem = new Label("No. of Items:");
add(lblNumItem);
txtNumItem= new TextField(3);
add(txtNumItem);
}
}
class Button1 extends Panel {
Button cmdAdd, cmdDelete, cmdWipe;
Button1() {
cmdAdd= new Button("Add");
add(cmdAdd);
cmdDelete = new Button("Delete");
add(cmdDelete);
cmdWipe = new Button("Wipe");
add(cmdWipe);
}
}

2. Then save the Java applet with the filename: listbox12.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>listbox12</title>
353

</head>
<body>
<hr>
<applet
code=listbox12.class
width=300
height=300>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: listbox12.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac listbox12.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\listbox12.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>listbox12.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer listbox12.htm (then press the Enter key)

Sample Output:
354

Figure 6.17 An applet that can add, delete or wipe out the items

Explanation:

In this situation, we have to apply the Panel class to organize the controls in our applet.
You will notice that we can arrange our controls into two panels. The first panel contains
the text fields and scrolling list, while the second panel contains the group of command
buttons. By the way, to review about the Panel class, it is a rectangular region that
contains controls. We can think of a panel as a new control that contains other controls.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class listbox12 extends Applet implements ActionListener {
Box1 Panel1;
Button1 Panel2;
.
.
.
Here at the init( ) method, we initialized the two panels and set its laylout. We also add an
ActionListener to the three buttons so that they will respond appropriately to the user’s
interaction.
.
.
.
public void init( ) {
setLayout(new GridLayout(1,2));
Panel1 = new Box1( );
355

Panel2 = new Button1( );


add(Panel1);
Panel2.cmdAdd.addActionListener(this);
Panel2.cmdDelete.addActionListener(this);
Panel2.cmdWipe.addActionListener(this);
add(Panel2);
}
.
.
.
We apply an if/else if conditional statements to determine what button the user is
clicking. If the user clicks the Add button, then we let the program to execute the
statement that adds an item to the scrolling list by applying the add( ) method. Now if the
user clicks the Delete button, the program will execute the statement that removes the
selected item in the scrolling list by applying the remove( ) method. In the case where the
user clicks the Wipe button, the program will execute the statement that removes all the
items in the scrolling list by applying the removeAll( ) method as you can observe in our
code below:

public void actionPerformed(ActionEvent objE) {


int varNumItem,varIndex;
if (objE.getSource( )==Panel2.cmdAdd) {
Panel1.strColor = Panel1.txtText1.getText( );
Panel1.lstBox1.add(Panel1.strColor);
varNumItem = Panel1.lstBox1.getItemCount( );
Panel1.txtNumItem.setText(String.valueOf(varNumItem));
repaint( );
}
else if (objE.getSource( )==Panel2.cmdDelete) {
varIndex = Panel1.lstBox1.getSelectedIndex( );
Panel1.lstBox1.remove(varIndex);
varNumItem = Panel1.lstBox1.getItemCount( );
Panel1.txtNumItem.setText(String.valueOf(varNumItem));
repaint( );
}
else if (objE.getSource( )==Panel2.cmdWipe) {
Panel1.lstBox1.removeAll( );
varNumItem = Panel1.lstBox1.getItemCount( );
Panel1.txtNumItem.setText(String.valueOf(varNumItem));
repaint( );
}
}

As usual, we applied here the valueOf( ) method from the String class, to properly format
and display the numeric data into the text field.
Here in the panel class implementation, we have to declare the objects in its respective
panel sub-class. Like for example, in our panel 1 (Box1), we declared the objects
(controls) that are specific to panel 1. Then we do the same with panel 2. This is how we
356

organized the controls in each respective panels. You have to take note that we were able
to accomplish this task by applying the extends Panel statement.
.
.
.
class Box1 extends Panel {
Label lblMessage,lblNumItem;
TextField txtText1, txtNumItem;
List lstBox1;
String strColor=" ";
Box1( ) {
lblMessage = new Label("Item to add:");
add(lblMessage);
txtText1 = new TextField(15);
add(txtText1);
lstBox1 = new List(10,false);
add(lstBox1);
lblNumItem = new Label("No. of Items:");
add(lblNumItem);
txtNumItem= new TextField(3);
add(txtNumItem);
}
}
class Button1 extends Panel {
Button cmdAdd, cmdDelete, cmdWipe;
Button1( ) {
cmdAdd= new Button("Add");
add(cmdAdd);
cmdDelete = new Button("Delete");
add(cmdDelete);
cmdWipe = new Button("Wipe");
add(cmdWipe);
}
}

Whew! At last, we are able to dissect our program in a comprehensible manner. What do
you think?

Example 18:

Design and develop a Java applet that takes the items that the users has chosen in the first
scrolling list and displays them in the second scrolling list. Follow the given design
specification below:
357

An American Places:

Portland
Alabama
Florida Scrolling list 1
Alaska
Seattle
California

Scrolling list 2

Figure 6.18 An applet that can copy an item from one scrolling list to another

Solution:

1. At the Microsoft NotePad, write the following code:


import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class dlistbox1 extends Applet implements ItemListener {


List lstList1, lstList2;

public void init() {


lstList1 = new List(6,true);
add(new Label ("American Places:"));
lstList1.add("Portland");
lstList1.add("Alabama");
lstList1.add("Florida");
lstList1.add("Alaska");
lstList1.add("Seattle");
lstList1.add("California");
lstList1.add("Nevada");
lstList1.add("Maryland");
lstList1.add("New Jersey");
lstList1.add("Chicago");
lstList1.add("Arizona");
lstList1.add("Washington");
lstList1.add("Illinois");
lstList1.add("Oregon");
add(lstList1);
358

lstList1.addItemListener(this);
lstList2 = new List(12,true);
add(lstList2);
}
public void itemStateChanged(ItemEvent objE) {
String[] strAddPlaces = lstList1.getSelectedItems();
lstList2.removeAll();
for (int i=0; i<strAddPlaces.length; i++) {
lstList2.add(strAddPlaces[i]);
}
repaint();
}
}

2. Then save the Java applet with the filename: dlistbox1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>dlistbox1</title>
</head>
<body>
<hr>
<applet
code=dlistbox1.class
width=200
height=300>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: dlistbox1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac dlistbox1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\dlistbox1.htm

Or, alternatively, you can type the following line at the MS-DOS command:
359

C:\javaprog>dlistbox1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer dlistbox1.htm (then press the Enter key)

Sample Output:

Figure 6.18a Applet that can copy an item from one scrolling list to another output

Explanation:

We declared here two scrolling lists, the lstList1, and lstList2 as you can observe in our
code below:

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class dlistbox1 extends Applet implements ItemListener {


List lstList1, lstList2;
.
.
.
360

Next, we preloaded the lstList1 scrolling list with the items (the American places), and
make only 6 items to be visible at the first list (lstList1), and make it acceptable for
someone to choose more than one item from the list by declaring true as our second
parameter .
.
.
.
public void init( ) {
lstList1 = new List(6,true);
add(new Label ("American Places:"));
lstList1.add("Portland");
lstList1.add("Alabama");
lstList1.add("Florida");
lstList1.add("Alaska");
lstList1.add("Seattle");
lstList1.add("California");
lstList1.add("Nevada");
lstList1.add("Maryland");
lstList1.add("New Jersey");
lstList1.add("Chicago");
lstList1.add("Arizona");
lstList1.add("Washington");
lstList1.add("Illinois");
lstList1.add("Oregon");
add(lstList1);
lstList1.addItemListener(this);
lstList2 = new List(12,true);
add(lstList2);
}
.
.
.
You will also notice that in our second scrolling list (lstList2), we declared 12 for the first
parameter of the List control, and true as the second parameter. These declarations cause
our second scrolling list to make at least 12 items to be visible at the same time, and the
user can click one or more items on it. You will know it if you can choose one or more
items in the scrolling list by seeing that the items previously clicked are being
highlighted.
.
.
.
public void itemStateChanged(ItemEvent objE) {
String[] strAddPlaces = lstList1.getSelectedItems( );
lstList2.removeAll( );
for (int i=0; i<strAddPlaces.length; i++) {
lstList2.add(strAddPlaces[i]);
}
repaint( );
}
}
361

What is more noticeable here in our code above is that whenever an item is selected or
deselected in the first list (lstList1), this code gets a list of all of lstList1’s selected items
and stores it in the strAddPlaces string array variable. Next, the second list (lstList2), is
emptied and then rebuilt with the list from add( ) method. You can try this one, by
deselecting your selections at the first list. You will see that the items in the second list
will be erased one after the other. To navigate the entire array values, we apply the for
loop statement. We have to remember that the array index started at 0, thus we initialize
our variable i with a value of 0. Using the length method of the String class, we can
determine the array’s size. By the way, an array is a special type of variable that can
contain or hold one or more values of the same data type. In our case, it a string data type.
The data stored in an array can be easily manipulated using a looping statement, because
its respective values are arranged sequentially. In this example, we are applying the for
loop statement.
With this laborious discussions of the scrolling list, I’m sure you had already gained an
enough strength to learn more of the other control that looks similar to scrolling list. This
control is called: choice control.

Using Choice Control


The Choice control is just a drop-down list box. In a choice control, the user would see
the first item in the Choice control and an arrow button next to it. When the user clicks
the arrow button, the list of items will be openned. When the user selects a particular item
in the choice control, we can display it in a text field or scrolling list.

Example 19:

Design and develop a Java applet that when the user selects an item in the Choice control
by clicking it, you can display the result in a text field. Follow the given design
specification below:

Choice control
Select your color: Red

Text field

Figure 6.19 An applet that displays the selected item from the Choice control to the text field
362

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class combobox2 extends Applet implements ItemListener {
Label lblMessage;
Choice cboBox1;
TextField txtBox1;
public void init() {
lblMessage = new Label("Select your color:");
add(lblMessage);
cboBox1 = new Choice();
cboBox1.add("Red");
cboBox1.add("Blue");
cboBox1.add("Green");
cboBox1.add("Orange");
cboBox1.add("Brown");
cboBox1.add("White");
cboBox1.add("Black");
cboBox1.add("Pink");
cboBox1.add("Violet");
cboBox1.add("Gray");
cboBox1.add("Yellow");
add(cboBox1);
cboBox1.addItemListener(this);
txtBox1 = new TextField(15);
add(txtBox1);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==cboBox1) {
txtBox1.setText(((Choice)objEvent.getSource()).
getSelectedItem());
}
}
}

2. Then save the Java applet with the filename: combobox2.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>combobox2</title>
</head>
<body>
<hr>
<applet
code=combobox2.class
width=200
height=200>
363

</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: combobox2.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac combobox2.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\combobox2.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>combobox2.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer combobox2.htm (then press the Enter key)

Sample Output:
364

Figure 6.19a Applet that displays the selected item from the
Choice control to the text field output

Explanation:

At the top of our program, we declared the object cboBox1 for our Choice class. We will
use this object (control) to manipulate the items we stored into it.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class combobox2 extends Applet implements ItemListener {
Label lblMessage;
Choice cboBox1;
TextField txtBox1;
.
.
.
As usual, we will initialize all the objects we declared from the top of our program into
the init( ) method and add all the items in the Choice control as you can observe in our
code below:
.
.
.
public void init( ) {
lblMessage = new Label("Select your color:");
add(lblMessage);
cboBox1 = new Choice( );
cboBox1.add("Red");
cboBox1.add("Blue");
cboBox1.add("Green");
cboBox1.add("Orange");
cboBox1.add("Brown");
cboBox1.add("White");
cboBox1.add("Black");
cboBox1.add("Pink");
cboBox1.add("Violet");
cboBox1.add("Gray");
cboBox1.add("Yellow");
add(cboBox1);
cboBox1.addItemListener(this);
txtBox1 = new TextField(15);
add(txtBox1);
}
.
.
.
365

Whichever item the user selects in the list of our Choice control, this particular item will
be displayed in the text field. This can be accomplished under the itemStateChanged( )
function:
.
.
.
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable( )==cboBox1) {
txtBox1.setText(((Choice)objEvent.getSource( )).
getSelectedItem( ));
}
}
}

The code above is familiar to you just because it is similar in implementation with our
previous example that deals with the Scrolling list control. So it is easier for you to adapt
and code. Isn’t it?

Example 20:

Design and develop a Java applet that when the user selects an item in the Choice control
by clicking it, you can display the result in a Scrolling list . Follow the given design
specification below:

Select a day: Choice control


Monday

Scrolling list

Figure 6.20 An applet that displays the selected item from the Choice control to the Scrolling list

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
366

public class combobox3 extends Applet implements ItemListener {


Label lblMessage;
Choice cboBox1;
List lstBox1;
public void init() {
lblMessage = new Label("Select a day:");
add(lblMessage);
cboBox1 = new Choice();
cboBox1.add("Monday");
cboBox1.add("Tuesday");
cboBox1.add("Wednesday");
cboBox1.add("Thursday");
cboBox1.add("Friday");
cboBox1.add("Saturday");
cboBox1.add("Sunday");
add(cboBox1);
cboBox1.addItemListener(this);
lstBox1 = new List(5,false);
add(lstBox1);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==cboBox1) {
lstBox1.add(((Choice)objEvent.getSource()).
getSelectedItem());
}
}
}

2. Then save the Java applet with the filename: combobox3.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:

<html>
<!- Web page written with Java Applet>
<head>
<title>combobox3</title>
</head>
<body>
<hr>
<applet
code=combobox3.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: combobox3.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


367

C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac combobox3.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\combobox3.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>combobox3.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer combobox3.htm (then press the Enter key)

Sample Output:

Figure 6.20a Applet that displays the selected item from the
Choice control to the Scrolling list output

Explanation:

At the top of our program, we declared the object cboBox1 for our Choice class and
lstBox1 for our List class. We will use these objects (controls) to manipulate the items we
stored into them.
368

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class combobox3 extends Applet implements ItemListener {
Label lblMessage;
Choice cboBox1;
List lstBox1;
.
.
.
As usual, we will initialize all the objects we declared from the top of our program into
the init( ) method and add all the items in the Choice control as you can observe in our
code below:
.
.
.
public void init( ) {
lblMessage = new Label("Select a day:");
add(lblMessage);
cboBox1 = new Choice( );
cboBox1.add("Monday");
cboBox1.add("Tuesday");
cboBox1.add("Wednesday");
cboBox1.add("Thursday");
cboBox1.add("Friday");
cboBox1.add("Saturday");
cboBox1.add("Sunday");
add(cboBox1);
cboBox1.addItemListener(this);
lstBox1 = new List(5,false);
add(lstBox1);
}
.
.
.
You will notice at the above code that we pass a value of 5 to the first parameter for the
List class of the lstBox1 object and a logical false for its second parameter. This means
that there are only 5 items to be visible at the control list, and the user can choose an item
on it one at a time only.
Whichever item the user selects in the list of our Choice control, this particular item will
be displayed in the Scrolling list. This can be accomplished under the itemStateChanged(
) function:
.
.
.
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==cboBox1) {
lstBox1.add(((Choice)objEvent.getSource( )).
getSelectedItem( ));
369

}
}
}

Example 21:

Design and develop a Java applet that when the user selects an item in the Choice control
by clicking it, you can display the result in a Text field. This time the items will be taken
from the HTML source script. In other words, the items shall not be initialized at the
init( ) method in the Java applet. Follow the given design specification below:

Scrolling list
Item One

Text field

Figure 6.21 An applet that displays the selected item from


the Scrolling list using the getParameter

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class combobox1 extends Applet implements ItemListener {
Choice cboBox1;
TextField txtBox1;
public void init() {
txtBox1 = new TextField(20);
add(txtBox1);
cboBox1 = new Choice();
cboBox1.add(getParameter("selection1"));
cboBox1.add(getParameter("selection2"));
cboBox1.add(getParameter("selection3"));
cboBox1.add(getParameter("selection4"));
cboBox1.add(getParameter("selection5"));
370

cboBox1.add(getParameter("selection6"));
cboBox1.add(getParameter("selection7"));
add(cboBox1);
cboBox1.addItemListener(this);
}
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==cboBox1) {
txtBox1.setText(((Choice)objEvent.getSource()).
getSelectedItem());
}
}
}

2. Then save the Java applet with the filename: combobox1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>combobox1</title>
</head>
<body>
<hr>
<applet
code=combobox1.class
width=200
height=200>
<param name=selection1 value="Item One">
<param name=selection2 value="Item Two">
<param name=selection3 value="Item Three">
<param name=selection4 value="Item Four">
<param name=selection5 value="Item Five">
<param name=selection6 value="Item Six">
<param name=selection7 value="Item Seven">
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: combobox1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac combobox1.java (then press the Enter key)


371

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\combobox1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>combobox1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer combobox1.htm (then press the Enter key)

Sample Output:

Figure 6.21a Applet that displays the selected item from the
Scrolling list using the getParameter

Explanation:

At the top of our program, we declared the object cboBox1 for our Choice class. We will
use this object (control) to manipulate the items we stored into it.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class combobox1 extends Applet implements ItemListener {
Choice cboBox1;
TextField txtBox1;
.
.
.
372

The big difference here in this applet is that, we initialized the items of the Choice control
through the HTML source script, not here in the init( ) method as you can observe below:
.
.
.
public void init( ) {
txtBox1 = new TextField(20);
add(txtBox1);
cboBox1 = new Choice( );
cboBox1.add(getParameter("selection1"));
cboBox1.add(getParameter("selection2"));
cboBox1.add(getParameter("selection3"));
cboBox1.add(getParameter("selection4"));
cboBox1.add(getParameter("selection5"));
cboBox1.add(getParameter("selection6"));
cboBox1.add(getParameter("selection7"));
add(cboBox1);
cboBox1.addItemListener(this);
}
.
.
.
We are using here the parameters which we named selection1 up to selection7 which are
the corresponding parameters of the Choice control items we declared in our HTML
source script, as you can see here below:
.
.
.
<title>combobox1</title>
</head>
<body>
<hr>
<applet
code=combobox1.class
width=200
height=200>
<param name=selection1 value="Item One">
<param name=selection2 value="Item Two">
<param name=selection3 value="Item Three">
<param name=selection4 value="Item Four">
<param name=selection5 value="Item Five">
<param name=selection6 value="Item Six">
<param name=selection7 value="Item Seven">
</applet>
<hr>
</body>
</html>

We applied here the getParameter( ) method within our applet’s code to get the items
initialized from the HTML source script.
373

Whichever item the user selects in the list of our Choice control, this particular item will
be displayed in the Text field. This can be accomplished under the itemStateChanged( )
function:
.
.
.
public void itemStateChanged(ItemEvent objEvent) {
if (objEvent.getItemSelectable()==cboBox1) {
txtBox1.setText(((Choice)objEvent.getSource( )).
getSelectedItem());
}
}
}

Finally, we have ended our lengthy discussion of Chapter 6 with a bang! Whatever skills
we learned in this chapter will surely add another ready-to-apply knowledge in our
programming development endeavor in the near future. What I can say more but good
luck to you, buddy!
374

LAB ACTIVITY
TEST 6

1. Design and develop a Java applet that generates the given inverse sequence numbers
using loop statements. Follow the given design specification below:

1st Solution: Use while loop statement


2nd Solution: Use do-while loop statement

2. Design and develop a Java applet that generates the given inverse sequence numbers
using loop statements. This time, it is in horizontal format. Follow the given design
specification below:

5 4 3 2 1

1st Solution: Use for loop statement


2nd Solution: Use do-while loop statement

3. Design and develop a Java applet that generates the given sequence numbers which is
incremented by 5 using loop statement. Follow the given design specification below:
375

5
10
15
20
25
30
35
40
45
50

1st Solution: Use for loop statement


2nd Solution: Use while loop statement

4. Design and develop a Java applet that generates the given sequence numbers which is
decremented by 5 using loop statements. Follow the given design specification below:

50 45 40 35 30 25 20 15 10 5

1st Solution: Use for loop statement


2nd Solution: Use do-while loop statement

5.Design and develop a Java applet that computes the factorial value of N! (as input) and
displays the result. Follow the given design specification below:

Enter a number: Compute


5

The Factorial value:


120

Text fields Button


376

1st Solution: Use for loop statement


2nd Solution: Use do-while loop statement

6. Design and develop a Java applet that computes the power value of the input base and
exponent numbers. Then display the result. Follow the given design specification below:

Enter the base and exponent numbers:


Command button
5 3 Compute

Text field 3
The Power value: 125

1st Solution: Use for loop statement


2nd Solution: Use while loop statement

7. Design and develop a Java applet that demonstrates how to preload a collection of
items to a Scrolling list. When the user chooses an item at the Scrolling list by double-
clicking it, that particular item will be displayed at the text field. Follow the given design
specification below:

Cities to Choose:

Hamburger
Spaghetti Scrolling list
Chicken
Steak
Macaroni

Coleslaw Text field


377

Note:

When the user scrolls-down the scrolling list, the Coleslaw item can be selected by double-clicking it, then
the item “Coleslaw” will be displayed at the text field. Add the following items into the Scrolling list:

Hamburger
Spaghetti
Chicken
Steak
Macaroni
Coleslaw
Cherry

8. Design and develop a Java applet that demonstrates how to preload a collection of
items to a Scrolling list and with the capability to remove the item by double-clicking it.
Follow the given design specification below:

Hot Drinks Menu:


Cappuccino
Macchiato
Americano
Chocolate
Tea Scrolling list
Café Au Lait
Espresso
Brewed Coffee
Nescafe

Double-click a hot drink to remove it!

9. Design and develop a Java applet that demonstrates how to preload a collection of
items to a Scrolling list and with the capability to remove the item. First, the user should
select the item to remove by just clicking it.Then the user should click the Remove
command button to finally delete the item from the list . Follow the given design
specification below:

Cold Drinks Menu:


Iced Coffee
Scrolling list
Iced Cappuccino
Iced Mocha
Iced Latte
Iced Tea Remove
Chilled Milk Button
Coffee Float
Choco Smoothie
Nestea Iced
378

10. Design and develop a Java applet that demonstrates how to preload a collection of
items to a Scrolling list and with the capability of adding more items into it. Follow the
given design specification below:

Add more months, then press Enter:

March Text field

January
February
Scrolling list

11. Design and develop a Java applet that demonstrates how to preload a collection of
items to a Scrolling list. The program should be able to display one or more selected
items on another scrolling list. Follow the given design specification below:

Figaro Frost Menu:

Strawberry
Chocolate Vanilla
Cappuccino Decaf Scrolling list 1
Coffee Float
Evian
Viva
Orangina
Snapple
Sola

Snapple Scrolling list 2


Viva
Evian
379

12. Design and develop a Java applet that demonstrates how to preload a collection of
items to a Scrolling list. The program should be able to transfer one or more selected
items to and from another scrolling list. Follow the given design specification below:

Double-click to transfer to other Scrolling list:

Muffin Zebra Brownies Scrolling list 2


Banana Muffin Carrot Cake
Carrot Loaf Marzipan Danish
Banana Crunch Butter Cake
Cookies
Pecan Bar
Figaro Bar
Cake Danish

Note:
Add the following items into the Scrolling list:
Muffins
Banana Muffin
Carrot Loaf
Banana Crunch
Cookies
Pecan Bar
Figaro Bar
Cake Danish
Zebra Brownies
Carrot Cake
Marzipan Danish
Butter Cake

13. Design and develop a Java applet that should apply the add( ), remove( ), and clear( )
methods of the scrolling list object. Follow the given design specification below:

Enter product to add: Add Delete Wipe


3 Buttons
Text field 1

Scrolling list

No. of Products:
Text field 2
380

Text field 2

Note:

The user will enter a product first at the text field 1 and then clicks the Add command button to add the
inputted product into the Scrolling list. Now when the user wants to remove the product from the scrolling
list, th user should highlight it first, then clicks the Delete command button to finally delete it. Clicking the
Wipe command button will wipe out all the products in the scrolling list. The number of products should be
updated always after the product is being added or being deleted from the scrolling list.

14. Design and develop a Java applet that when the user selects an item in the Choice
control by clicking it, you can display the result in a Scrolling list . Follow the given
design specification below:

Choice control
Starbucks Café Menu: Cheese Tempura

List of Ordered items:

Scrolling list

Note:

Add the following items into the Choice control:

Cheese Tempura
Caesar’s Salad
Cajun Burger
Citrus Pork
Burger Steak
Café Mocha
Café Latte
Cappuccino
Steamed Milk
Espreso
Brewed Coffee
381

15. Design and develop a Java applet that when the user selects an item in the Choice
control by clicking it, you can display the result in a text field. Use the getParameter( )
method in your program. Follow the given design specification below:

Select your snack: Dilly Bar Choice control

Text field

Note:

Add the following items into the Choice control:

Dilli Bar
Plain Dog
Cheese Dog
Chilimelt Dog
Relish Dog
Bacon n Cheese
Fudge Brownie
Banana Split
Peanut Buster
382

Chapter 8
Other Java Controls

In this chapter, we will learn how to use some other important controls of Java
programming language. The controls we will cover in this chapter are rarely used in real-
world application, thus they are not as popular as those controls that we have already
covered. Nonetheless, we will learn how to use them so that when the need arises, we are
already equipped with the skills required to accomplish the task.

Using Scroll Bars


There are two types of scroll bars that we can apply into our program. The first one is the
horizontal scroll bar and the other one is the vertical scroll bar. A scroll bar is typically
used to increase or decrease a value such as when we want to change the color setting of
our computer’s monitor through the Control Panel’s Display object or to increase or
decrease the volume of our computer’s digital speaker. The scroll bar acts as a sliding
scale with a starting point and ending point, including the values in between. Let us
explore this unpopular control in our example.

Example 1:

Design and develop a Java applet that demonstrates how to use a horizontal scroll bar.
Follow the given design specification below:

Horizontal position: 85

Figure 7.1 An applet with a horintal scroll bar

Solution:

1. At the Microsoft NotePad, write the following code:


383

import java.applet.Applet;
import java.awt.event.*;
import java.awt.*;
public class hscroll1 extends Applet implements AdjustmentListener {
TextField txtTbox1;
Scrollbar sclHscroll1;
public void init() {
txtTbox1 = new TextField(21);
add(txtTbox1);
sclHscroll1= new Scrollbar(Scrollbar.HORIZONTAL,1,10,1,150);
add(sclHscroll1);
sclHscroll1.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent objEvent) {
if (objEvent.getAdjustable() == sclHscroll1) {
sclHscroll1.setValue(sclHscroll1.getValue());
txtTbox1.setText("Horizontal position:"+ sclHscroll1.getValue());
}
}
}

2. Then save the Java applet with the filename: hscroll1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>hscroll1</title>
</head>
<body>
<hr>
<applet
code=hscroll1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: hscroll1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac hscroll1.java (then press the Enter key)


384

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\hscroll1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>hscroll1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer hscroll1.htm (then press the Enter key)

Sample Output:

Figure 7.1a Applet with a horintal scroll bar output

Explanation:

We are declaring the scroll bar using Scrollbar class:

import java.applet.Applet;
import java.awt.event.*;
import java.awt.*;
public class hscroll1 extends Applet implements AdjustmentListener {
TextField txtTbox1;
Scrollbar sclHscroll1;
.
.
.
In the init( ) method, we will add scroll bar and text field to the applet:
.
385

.
.
public void init( ) {
txtTbox1 = new TextField(21);
add(txtTbox1);
sclHscroll1= new Scrollbar(Scrollbar.HORIZONTAL,1,10,1,150);
add(sclHscroll1);
sclHscroll1.addAdjustmentListener(this);
}

.
.
.
The parameters of the Scrollbar method specify the initial value, the location of the scroll
box in the scroll bar - called the thumb, the size of the scroll thumb in pixels,and the
scroll bar’s minimum possible value which in this example is 1 and its maximum possible
value is 150.
.
.
.
public void adjustmentValueChanged(AdjustmentEvent objEvent) {
if (objEvent.getAdjustable() == sclHscroll1) {
sclHscroll1.setValue(sclHscroll1.getValue( ));
txtTbox1.setText("Horizontal position:"+ sclHscroll1.getValue( ));
}
}
}

We can determine which scroll bar caused the event by applying the getAdjustable( )
method of the AdjustableEvent class.
To set the location of the thumb , we apply the setValue( ) method. And to get its current
value, we apply the getValue( ) method. We concatenate the strings in Java programming
language using the + (plus) operator. Thus, we apply it here in the txtTbox1.setText
object; our last line of the code above.

Example 2:

Design and develop a Java applet that demonstrates how to use a vertical scroll bar.
Follow the given design specification below:
386

Vertical location: 15

Figure 7.2 An applet with a vertical scroll bar

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.event.*;
import java.awt.*;
public class vscroll1 extends Applet implements AdjustmentListener {
TextField txtTbox1;
Scrollbar sclVscroll1;
public void init() {
txtTbox1 = new TextField(28);
add(txtTbox1);
sclVscroll1= new Scrollbar(Scrollbar.VERTICAL,1,0,1,50);
add(sclVscroll1);
sclVscroll1.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent objEvent) {
if (objEvent.getAdjustable() == sclVscroll1) {
sclVscroll1.setValue(sclVscroll1.getValue());
txtTbox1.setText("Vertical location:"+ sclVscroll1.getValue());
}
}
}

2. Then save the Java applet with the filename: vscroll1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
387

<title>vscroll1</title>
</head>
<body>
<hr>
<applet
code=vscroll1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: vscroll1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac vscroll1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\vscroll1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>vscroll1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer vscroll1.htm (then press the Enter key)

Sample Output:
388

Figure 7.2a Applet with a vertical scroll bar output

Explanation:

We are declaring the scroll bar using Scrollbar class:

import java.applet.Applet;
import java.awt.event.*;
import java.awt.*;
public class vscroll1 extends Applet implements AdjustmentListener {
TextField txtTbox1;
Scrollbar sclVscroll1;
.
.
.
In the init( ) method, we will add scroll bar and text field to the applet:
.
.
.
public void init( ) {
txtTbox1 = new TextField(28);
add(txtTbox1);
sclVscroll1= new Scrollbar(Scrollbar.VERTICAL,1,0,1,50);
add(sclVscroll1);
sclVscroll1.addAdjustmentListener(this);
}
.
.
.
The parameters of the Scrollbar method specify the initial value, the location of the scroll
box in the scroll bar - called the thumb, the size of the scroll thumb in pixels,and the
scroll bar’s minimum possible value which in this example is 1 and its maximum possible
value is 50.
389

.
.
.
public void adjustmentValueChanged(AdjustmentEvent objEvent) {
if (objEvent.getAdjustable( ) == sclVscroll1) {
sclVscroll1.setValue(sclVscroll1.getValue( ));
txtTbox1.setText("Vertical location:"+ sclVscroll1.getValue( ));
}
}
}

We can determine which scroll bar caused the event by applying the getAdjustable( )
method of the AdjustableEvent class.
To set the location of the thumb , we apply the setValue( ) method. And to get its current
value, we apply the getValue( ) method. We concatenate the strings in Java programming
language using the + (plus) operator. Thus, we apply it here in the txtTbox1.setText
object; our last line of the code above.

Example 3:

Design and develop a Java applet that demonstrates how to use a scrollpane. Follow the
given design specification below:

After Bianca got a b

Figure 7.3 An applet with a scrollpane

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
public class scrollpane1 extends Applet {
ScrollPane sclSpane1;
TextField txtTbox1;
390

public void init() {


sclSpane1 = new ScrollPane();
txtTbox1 = new TextField("After Bianca got a boyfriend,
I love Dimple, instead!");
sclSpane1.add(txtTbox1);
add(sclSpane1);
}
}

2. Then save the Java applet with the filename: scrollpane1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>scrollpane1</title>
</head>
<body>
<hr>
<applet
code=scrollpane1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: scrollpane1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac scrollpane1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\scrollpane1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>scrollpane1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:
391

C:\javaprog>appletviewer scrollpane1.htm (then press the Enter key)

Sample Output:

Figure 7.3a Applet with a scrollpane output

Explanation:

The scrollpane will enable us to place a control in the middle of a container object and
display it. The scroll bars will simply appear around the edges of this container as
needed. We are declaring the scrollpane using ScrollPane class:

import java.applet.Applet;
import java.awt.*;
public class scrollpane1 extends Applet {
ScrollPane sclSpane1;
TextField txtTbox1;
.
.
.
We will create a new control and add it to our ScrollPane object. This control is a new
text field which we will add into the ScrollPane object such as the following:
.
.
.
public void init( ) {
sclSpane1 = new ScrollPane( );
txtTbox1 = new TextField("After Bianca got a boyfriend,
I love Dimple, instead!");
sclSpane1.add(txtTbox1);
add(sclSpane1);
392

}
}

We are able to accomplish the task of developing a scrollpane right at the init( ) method.

Using the GridBagLayout Manager


The GridBagLayout manager enables us to specify the position of our controls more
exactly than any other layout manager we have learned. Like for example, using the
GridBagLayout manager, we can design and develop An applet that provides the user
with a list of names. We can display the names in command buttons at the top of the
applet. When the user clicks a button, we can display the corresponding characteristic in a
text area. Let us have our example for this unusual control.

Example 4:

Design and develop a Java applet that demonstrates how to use a GridBagLayout
manager. Follow the given design specification below:

Tara Bianca Jacque Dimple

Model, Muse and First Honor

Figure 7.4 An applet with a GridBagLayout manager application

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class gridbag1 extends Applet implements ActionListener {
Button cmdTara, cmdBianca, cmdJaque, cmdDimple;
TextArea txtTarea1;
393

public void init() {


GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
setLayout(gridbag);

constraints.weighty = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1;
cmdTara = new Button("Tara");
gridbag.setConstraints(cmdTara,constraints);
add(cmdTara);
cmdTara.addActionListener(this);

constraints.weightx = 1;
cmdBianca = new Button("Bianca");
gridbag.setConstraints(cmdBianca,constraints);
add(cmdBianca);
cmdBianca.addActionListener(this);

constraints.weightx = 1;
cmdJaque = new Button("Jaque");
gridbag.setConstraints(cmdJaque,constraints);
add(cmdJaque);
cmdJaque.addActionListener(this);

constraints.weightx = 1;
cmdDimple = new Button("Dimple");
constraints.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(cmdDimple,constraints);
add(cmdDimple);
cmdDimple.addActionListener(this);

txtTarea1= new TextArea();


constraints.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(txtTarea1,constraints);
add(txtTarea1);
}
public void actionPerformed(ActionEvent objEvent) {
if (objEvent.getSource() == cmdTara) {
txtTarea1.setText("Beauty Queen and Class President");
}
if (objEvent.getSource() == cmdBianca) {
txtTarea1.setText("Muse and Model");
}
if (objEvent.getSource() == cmdJaque) {
txtTarea1.setText("Body Beautiful and Cute");
}
if (objEvent.getSource() == cmdDimple) {
txtTarea1.setText("Model, Muse and First Honor");
}
}
}

2. Then save the Java applet with the filename: gridbag1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
394

<html>
<!- Web page written with Java Applet>
<head>
<title>gridbag1</title>
</head>
<body>
<hr>
<applet
code=gridbag1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: gridbag1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac gridbag1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\gridbag1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>gridbag1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer gridbag1.htm (then press the Enter key)

Sample Output:
395

Figure 7.4a Applet with a GridBagLayout manager


application output

Explanation:

We add the controls we need - command buttons cmdTara, cmdBianca, cmdJacque, and
cmdDimple. Then we add also the text area which we named txtTarea1:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class gridbag1 extends Applet implements ActionListener {
Button cmdTara, cmdBianca, cmdJaque, cmdDimple;
TextArea txtTarea1;
.
.
.
Let us now set up our new GridBagLayout manager in the init( ) method. We can specify
how we want our controls to be arranged under the GridBagLayout manager using an
object of the Java class GridBagConstraints. We use this object to arrange the controls in
a GridBagLayout:
.
.
.
public void init( ) {
GridBagLayout gridbag = new GridBagLayout( );
GridBagConstraints constraints = new GridBagConstraints( );
setLayout(gridbag);

constraints.weighty = 1;
constraints.fill = GridBagConstraints.BOTH;
396

constraints.weightx = 1;
cmdTara = new Button("Tara");
gridbag.setConstraints(cmdTara,constraints);
add(cmdTara);
cmdTara.addActionListener(this);

constraints.weightx = 1;
cmdBianca = new Button("Bianca");
gridbag.setConstraints(cmdBianca,constraints);
add(cmdBianca);
cmdBianca.addActionListener(this);

constraints.weightx = 1;
cmdJaque = new Button("Jaque");
gridbag.setConstraints(cmdJaque,constraints);
add(cmdJaque);
cmdJaque.addActionListener(this);

constraints.weightx = 1;
cmdDimple = new Button("Dimple");
constraints.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(cmdDimple,constraints);
add(cmdDimple);
cmdDimple.addActionListener(this);

txtTarea1= new TextArea( );


constraints.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(txtTarea1,constraints);
add(txtTarea1);
}
.
.
.
The GridBagLayout works with the relative weights of controls in the x and y axis
directions. Like for example, since all of these command buttons have the same width,
they each have the same x weight which we specify as 1. We can specify x and y weights
with the weightx and weighty members of the GridBagConstraints object we named
constraints. Since all of our command buttons have the same height, they have the same
value of weighty which we set also as 1.
Now to display the correct characteristic of the name when the user clicks a command
button in our applet, we implement the actionPerformed( ) method with the conditional if
statement application as follows:
.
.
.
public void actionPerformed(ActionEvent objEvent) {
if (objEvent.getSource( ) == cmdTara) {
txtTarea1.setText("Beauty Queen and Class President");
}
397

if (objEvent.getSource( ) == cmdBianca) {
txtTarea1.setText("Muse and Model");
}
if (objEvent.getSource( ) == cmdJaque) {
txtTarea1.setText("Body Beautiful and Cute");
}
if (objEvent.getSource( ) == cmdDimple) {
txtTarea1.setText("Model, Muse and First Honor");
}
}
}

Our discussion now is complete. Try clicking some of the command buttons now. And
you will see that the name’s corresponding characteristic will appear. Wanna beat?
398

LAB ACTIVITY
TEST 7

1. Design and develop a Java applet that demonstrates how to use a horizontal scroll bar.
Follow the given design specification below:

Horizontal position: 85

2. Design and develop a Java applet that demonstrates how to use a vertical scroll bar.
Follow the given design specification below:

Vertical location: 15
399

3. Design and develop a Java applet that demonstrates how to use the horizontal and
vertical scroll bars at the same time. Follow the given design specification below:

Horizontal location: 49

4. Design and develop a Java applet that demonstrates how to use a scrollpane. Follow
the given design specification below:

If Dimple is a dream, I
don’t want to wake up
anymore.

5. Design and develop a Java applet that demonstrates how to use a GridBagLayout
manager. Follow the given design specification below:
400

John Matthew Luke Peter

John’s number: 0919-104523

Note:
When the user clicks the command button, the name’s corresponding cellphone number should appear.
Here are their respective numbers:
Matthew’s number: 0918-102113
Luke’s number: 0917-987564
Peter’s number: 0920-211345
401

Chapter 9
Designing Window and Simple Menu

Window and PopUp Menu


We can design a free-floating window in Java programming language with a message in
it. We can design and develop a popup menu too. A popup menu is usually triggered by
right-clicking the mouse button. Let us have examples on these two last controls that we
will cover in this book. Are you ready now?

Example 1:

Design and develop a Java applet that demonstrates how to design and develop a
window. Follow the given design specification below:

Show Window Hide Window

Display Window

Tara, Bianca, Jacque & Dimple!

Warning: Applet Window

Figure 8.1 An applet with a window control

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class window1 extends Applet implements ActionListener {
Button cmdShow, cmdHide;
frmFrame1 winWindow1;
public void init() {
402

cmdShow = new Button("Show Window");


add(cmdShow);
cmdShow.addActionListener(this);
cmdHide = new Button("Hide Window");
add(cmdHide);
cmdHide.addActionListener(this);
winWindow1 = new frmFrame1("Display Window");
winWindow1.setSize(200,100);
}
public void actionPerformed(ActionEvent objEvent) {
if (objEvent.getSource() == cmdShow) {
winWindow1.setVisible(true);
}
if (objEvent.getSource() == cmdHide) {
winWindow1.setVisible(false);
}
}
}
class frmFrame1 extends Frame {
Label lblLabel1;
frmFrame1(String strMessage) {
super(strMessage);
setLayout(new GridLayout(1,1));
lblLabel1 = new Label("Tara, Bianca, Jacque & Dimple!");
add(lblLabel1);
}
}

2. Then save the Java applet with the filename: window1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>window1</title>
</head>
<body>
<hr>
<applet
code=window1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: window1.htm.


5. This time, activate the Java compiler batch file with the following steps:

Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


403

C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac window1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\window1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>window1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer window1.htm (then press the Enter key)

Sample Output:

Figure 8.1a Applet with a window control output

Explanation:

Our window object winWindow1 is based on the Java Frame class, which creates a frame
window on the screen.
404

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class window1 extends Applet implements ActionListener {
Button cmdShow, cmdHide;
frmFrame1 winWindow1;
.
.
.
We are now initializing all our objects within the init( ) method as you can see in our
code below:
.
.
.
public void init( ) {
cmdShow = new Button("Show Window");
add(cmdShow);
cmdShow.addActionListener(this);
cmdHide = new Button("Hide Window");
add(cmdHide);
cmdHide.addActionListener(this);
winWindow1 = new frmFrame1("Display Window");
winWindow1.setSize(200,100);
}
.
.
.
We can also give the new window an initial size in pixels by using the setSize( ) method.
We use the setVisible(true) method so that we can show the window, and to hide it, we
use the setVisible(false) method.
.
.
.
public void actionPerformed(ActionEvent objEvent) {
if (objEvent.getSource( ) == cmdShow) {
winWindow1.setVisible(true);
}
if (objEvent.getSource( ) == cmdHide) {
winWindow1.setVisible(false);
}
}
}
.
.
.
The super( ) method is used in any derived class’s constructor to call the base class
constructor. Since windows and dialog boxes in Java programming language have no
default layout manager, thus we apply here the GridLayout manager:
.
405

.
.
class frmFrame1 extends Frame {
Label lblLabel1;
frmFrame1(String strMessage) {
super(strMessage);
setLayout(new GridLayout(1,1));
lblLabel1 = new Label("Tara, Bianca, Jacque & Dimple!");
add(lblLabel1);
}
}

Example 2:

Design and develop a Java applet that demonstrates how to design and develop a popup
menu. Follow the given design specification below:

You select menu item 2 Text field

Menu item 1
Menu item 2 Popup menu

Menu item 3
Right-click the mouse now!

Figure 8.2 An applet with a popup menu

Solution:

1. At the Microsoft NotePad, write the following code:


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
public class popup1 extends Applet implements ActionListener,
MouseListener {
TextField text1;
PopupMenu popup1;
MenuItem menuitem1, menuitem2, menuitem3;
public void init() {
406

popup1 = new PopupMenu ("Popup Menu");


menuitem1 = new MenuItem("Menu item 1");
menuitem1.addActionListener(this);
menuitem2 = new MenuItem("Menu item 2");
menuitem2.addActionListener(this);
menuitem3 = new MenuItem("Menu item 3");
menuitem3.addActionListener(this);
popup1.add(menuitem1);
popup1.add(menuitem2);
popup1.addSeparator();
popup1.add(menuitem3);
add(popup1);
text1 = new TextField(20);
add(text1);
addMouseListener(this);
}
public void mousePressed(MouseEvent e) {
if (e.getModifiers() != 0) {
popup1.show(this, e.getX(), e.getY());
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}

public void paint(Graphics objLabel)


{
objLabel.drawString("Right-click the mouse now!",50,120);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == menuitem1) {
text1.setText("You chose menu item 1");
}
if (event.getSource() == menuitem2) {
text1.setText("You select menu item 2");
}
if (event.getSource() == menuitem3) {
text1.setText("You click menu item 3");
}
}
}

2. Then save the Java applet with the filename: popup1.java.


3. This time, open a new file at the NotePad to write the HTML script needed for the
applet and type the following code:
<html>
<!- Web page written with Java Applet>
<head>
<title>popup1</title>
</head>
407

<body>
<hr>
<applet
code=popup1.class
width=200
height=200>
</applet>
<hr>
</body>
</html>

4. Now save the HTML script with the filename: popup1.htm.


5. This time, activate the Java compiler batch file with the following steps:
Type the word cmd at the Run menu of Windows operating system, then at the C:\>
prompt, type:

C:\>cd javaprog (then press the Enter key)


C:\JAVAPROG>jpath (then press the Enter key)

6. Finally, you can now compile your program with the following MS-DOS command:

C:\JAVAPROG>javac popup1.java (then press the Enter key)

7. When no error is encountered during the compilation process, you can now type the
following at your Web browser:

C:\javaprog\popup1.htm

Or, alternatively, you can type the following line at the MS-DOS command:

C:\javaprog>popup1.htm (then press the Enter key)

Or, we can use the Java Appletviewer to run or test our applet:

C:\javaprog>appletviewer popup1.htm (then press the Enter key)

Sample Output:
408

Figure 8.2a Applet with a popup menu output

Explanation:

We can declare the popup1 object using the PopupMenu class as you can see in our code
below:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
public class popup1 extends Applet implements ActionListener,
MouseListener {
TextField text1;
PopupMenu popup1;
.
.
.
We are declaring here also the text field text1 so that we can report what menu item was
selected by the user.
.
.
.
public void init( ) {
popup1 = new PopupMenu ("Popup Menu");
menuitem1 = new MenuItem("Menu item 1");
menuitem1.addActionListener(this);
menuitem2 = new MenuItem("Menu item 2");
menuitem2.addActionListener(this);
menuitem3 = new MenuItem("Menu item 3");
409

menuitem3.addActionListener(this);
popup1.add(menuitem1);
popup1.add(menuitem2);
popup1.addSeparator( );
popup1.add(menuitem3);
add(popup1);
text1 = new TextField(20);
add(text1);
addMouseListener(this);
}
.
.
.
We create a new object of class PopupMenu which we named popup1. We add three
menu items here: Menu item 1, Menu item 2, and Menu item 3. We applied the
addSeparator( ) method here to separate the menu item 3 from the above two menu items
(it is like a white line that separates the menu items). We also add an ActionListener to
make these menu items active. Moreover, we implement the MouseListener interface to
handle mouse events.
We add five methods to implement mouse handling. They are mousePressed( ),
mouseClicked( ), mouseRead( ), mouseEntered( ), and mouseExited( ).
.
.
.
public void mousePressed(MouseEvent e) {
if (e.getModifiers( ) != 0) {
popup1.show(this, e.getX( ), e.getY( ));
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
.
.
.
In the mousePressed( ) method, we apply an if conditional statement that checks whether
the right mouse button was clicked (this button brings up the popup menu). If the right
mouse button was indeed clicked, the program will show the popup menu with its show( )
method at the present mouse location. We can get the mouse location by using the getX( )
and getY( ) MouseEvent methods.
We are applying here the paint( ) method to prompt the user to right-click the mouse.
This method will simply display this prompt message at the applet.
.
.
410

.
public void paint(Graphics objLabel)
{
objLabel.drawString("Right-click the mouse now!",50,120);
}
.
.
.
We applied here the actionPerformed( ) method to handle menu selections:
.
.
.
public void actionPerformed(ActionEvent event) {
if (event.getSource( ) == menuitem1) {
text1.setText("You chose menu item 1");
}
if (event.getSource( ) == menuitem2) {
text1.setText("You select menu item 2");
}
if (event.getSource( ) == menuitem3) {
text1.setText("You click menu item 3");
}
}
}

In this book, we have learned the fundamental skills needed to program Java applet. I
hope that the knowledge you gained will motivate you to study more about the other side
of Java programming language. Java programming language is so enormous to study
with. Its potential is limitless, its power is far beyond what we have learned. Enjoy your
journey to Java programming excellence!
411

LAB ACTIVITY
TEST 8

1. Design and develop a Java applet that demonstrates how to design and develop a
window. Follow the given design specification below:

Hide Window Display Window

Display Window

It is time to rumble!

Warning: Applet Window

2. Design and develop a Java applet that demonstrates how to design and develop a
popup menu. Follow the given design specification below:

You select Transfer Text field

Cut
Copy Popup menu

Paste
Right-click the mouse now! Transfer
412

Chapter 10
Introduction to Java Enterprise Edition Application

Java Database Connectivity (JDBC) Explained

Most of the Java programs that we design and develop involve the use of data or
information in some form. One of the most common types of application that we are
likely to develop is a data-driven application which operation is usually to retrieve and
process data. The most common relational database software that we will encounter when
developing data-driven application are Oracle, IBM DB2, MySQL, PostgreSQL, and
Microsoft SQL Server.
We need to learn the JDBC because this is at the heart of developing database
applications with the Java language. Moreover, the JDBC application programming
interfaces (API) provide the necessary library of classes that enable us to connect to a
database and to retrieve, manipulate, and update data.
Java is not designed for creating new databases or tables, but rather can be used
for displaying, manipulating, and analyzing the data in existing databases. A database is
simply a systematic way of collecting, organizing, and managing of data. Creating,
managing, and maintaining databases have become an essential task for all companies,
government agencies, and even small businesses.
Data resources such as sales records, ATM accounts, inventory controls, patients
files, payroll system, enrollment system, online reservation system, and many others have
become the lifeblood of the business operation and critical to its survival and prosperity.
JDBC has been designed for Internet database access and manipulation. This means that
it uses the same method for accessing Internet-based or Intranet-based data resources.
Since Oracle Corporation now owns the Sun Microsystems company (the developer of
Java programming language), we will focus our Java Database Connectivity on Oracle
Database all throughout our discussions. Not to mention that Oracle is the world’s
number 1 relational database software and the most widely-used by companies
worldwide. So, what are you waiting for? Dive now (with Java Database Connectivity
programming)!

Connecting Java to Database

The Java Database Connectivity (JDBC) standard is used by Java applications to


access and manipulate data in relational databases such as Oracle, IBM DB2, MySQL,
PostgreSQL, and SQL Server. Furthermore, JDBC is an industry-standard application
programming interface (API) that lets us embed SQL statements in Java program. In
other words, JDBC is a database access protocol that enables us to connect to a database
and run SQL statements and queries on it. The JDBC standard was originally developed
by Sun Microsystems.
413

Software Requirements

We need to install two added software for this topic. The first one is the Oracle
Database 10g Express Edition software as our relational database to use. The second one
is the Oracle JDeveloper 11g as the integrated development environment (IDE) we will
use to design and develop Java Enterprise Edition (J2EE) programs and creating web
pages for users to view and change data on our database. This can be accomplished using
the JavaServer Pages (JSP) technology.

Figure 9.1 Oracle Database Installation Wizard

Figure 9.2 Oracle JDeveloper Startup Menu


414

Note:
The Oracle Database 10g Express Edition and Oracle Jdeveloper 11g software are free and can be
downloaded directly from oracle.com website.

Warning!
The Oracle Database 11g Express Edition which was released in the early month of 2012 is requiring
probably a different configuration than what has been stated in the official manual: Oracle Database 11g 2
Day + Java Developer’s Guide, published as an e-book downloadable from oracle.com. This is the main
reason why we used the previous version – Oracle Database 10g Express Edition for our Java EE
application. Furthermore, we are also using the JDeveloper 11g copyright 2009 because it is compatible
with Oracle Database 10g Express Edition. Latest release of JDeveloper 11g such as the copyright
2011edition is unfortunately not working well with Oracle Database 10g Express Edition.

So, What is Oracle JDeveloper?

Oracle JDeveloper is an integrated development environment (IDE) that contains


all the support and functionalities we need for designing, developing, debugging, and
deploying Java programs and Web services. Furthermore, it provides the features for us
to code and test Java applications that access relational database with SQL statements
embedded in Java programs. With JDeveloper, we can create a connection to a database,
or browse, edit, delete or update it. Not only that, we can create or edit also the Oracle’s
PL/SQL procedures, functions, and packages right within the IDE.

The Graphical-User Interface of JDeveloper

The JDeveloper IDE uses windows for various application development tools. We
can display or hide any of the windows or dock or undock them any time we want to suite
our need or working style. Furthermore, it provides us a range of navigators to help us
organize and view the contents of our projects. For example, the Application and System
navigators show us the files of our projects, while the Structure window shows us the
structure of individual items. Through the View menu, we can open or close the
windows, or arrange them.
415

1 2 3

4 5 6

Figure 9.3 JDeveloper Graphical User Interface

Here are the meanings of the arrows that we point to:

1- Application Navigator
2- Java Source/Visual Editor
3- Component Palette
4- Structure Window
5- Runtime Messages
6- Property Inspector

Let us discuss their respective uses.

Application Navigator – contains the list of .java, .jsp and .css files. The .java files are
usually our JavaBeans, while .jsp and .css are the JavaServer Pages and Cascading Style
Sheet files respectively.

Java Source/Visual Editor – provides extensive features that help us in writing the Java
program, such as distinctive highlighting for syntax or even semantic errors. Furthermore,
it provides assistance to us for adding and sorting important statements, code templates
and as well as the Java Code Insight feature.
The Visual Editor part is used for editing HTML and JSP pages.
416

Component Palette- this is where we select the graphical user interface (GUI)
components such as HTML Button, CheckBox, ComboBox, Form, Radio Button, and
many more which we want to display in our web pages.

Structure Window – provides a tree view of all the elements in the application that are
currently edited, whether it is a Java file, JSP/HTML file, or even XML file.

Runtime Messages – contains the compilation and linking messages, as well as error
messages during the compilation and runtime period.

Property Inspector – gives a simple way of setting properties of user interface (UI)
components such as button, checkbox, combobox, radio button, and many others.

Note:
The Java Code Insight is a special feature of Oracle JDeveloper that provides context-specific, intelligent
input when creating program in the Java Source Editor. Furthermore, it works somewhat like an
IntelliSense feature of Microsoft Visual C#.
Component Palette works like a ToolBox in Microsoft Visual C#.
Property Inspector works like the Properties Window in Microsoft Visual C#.

About Oracle Database Server

To successfully design and develop Java Database Connectivity (JDBC)


application, we need to install Oracle Database Server which contains the HR database.
The HR user account which owns the HR database is initially locked. We have to unlock
the account before we can login and access the database. We need to have a database
administrator (DBA) privileges in order to unlock the account. Here are the steps syntax
to accomplish the task:

At your Windows 8 operating system, go to Oracle Database 11g (or higher) then select
Run SQL Command Line and do the following:

SQL>connect logon as sysdba


Enter Password: mypassword

Where mypassword is the password you had assigned to the SYS (SYSTEM) user during
the time you install the Oracle Database 11g software. For example, the password you
had assigned is mysecretpassword, then this is the password that you have to used when
logging in as a system database administrator (SYSDBA).

SQL> alter user HR account unlock;

Or
417

SQL> alter user HR identified by HR;

To ensure that you successfully unlocked the HR schema account, test the connection by
invoking this syntax to the SQL Plus prompt:

SQL> connect hr/hr @localhost


Connected.

If the unlocking process is successful, you should see a message indicating that you have
connected to the HR database. To know it, the word “Connected.” should appear after
connecting to the localhost using the connect hr/hr command, as you could see in the
above syntax.

If you are using the Oracle Database Express Edition (XE), here are the steps in
unlocking the HR account:

Figure 9.4 Oracle Database Home Page menu

1. Go to the Database Home Page, then enter system for the username.

Warning!
If you will encounter some web page error, select the Start Database option first. Then, select the
Go To Database Home Page option again.

2. Enter the password that you specified when Oracle Database Express Edition was
installed. For example, if you specify the password as mypassword, then enter
it.
3. Click the Administration icon, and then click the Database Users.
4. Now this time, click the HR schema icon to display the user information for HR.
5. Under the Manage Database User, enter hr for the password setting (Password
and Confirm Password).
6. Then select Unlocked for the Account Status setting.
7. Finally, click the Alter User setting.
418

What is a Web Server?


The JDBC application that we design and develop here uses JavaServer Pages
(JSP) technology to display information and accept input data from our target users
through an Internet(or Intranet) connection. To deploy JSP, we need a web server with a
Servlet and JSP container, such as the Apache Tomcat, IBM WebSphere or JBoss
application servers. Since we use the Oracle JDeveloper, we will use the BEA WebLogic
web server which is packaged with it.

Note:
JavaServer Pages (JSP) works like Active Server Pages (ASP) of Microsoft - usually coded (scripted) with
Visual C# programming language.

Connecting to Oracle Database

We can connect to the Oracle Database by using a java.sql.Connection object. Using the
Database Navigator of JDeveloper, we can set up and manage database connection.
Furthermore, it enables our Java application to communicate with external data sources
(relational databases).
We can use the Database Navigator to browse through the connections it displays. For
example, in database schema, we can view database tables, views, objects, and their
respective contents.

How to Create Database Connection ?

We must specify a username and password when we create a database connection.


Here are the steps to create a database connection:

1. At the Oracle Middleware Fusion, select and click the JDeveloper Studio.
2. You will be prompted to select a role. In our example and lab activity, we have to
select the Default Role (which enable all Java and Oracle technologies). Finally,
click the OK button.
3. From the View menu, select Database Navigator. The Database Navigator is
displayed, showing us a list of available connections. Right-click IDE
Connections, and from its shortcut menu, select New Connection. The Create
Database Connection wizard is displayed as shown in Figure 9.5.
419

Figure 9.5 Database Connection Wizard

4. Now, in our example and lab activity purposes, we have to change the Connection
Name, and provide the Username and Password. Just leave all other default values
as they are. So, provide the following database connection information:

Connection Name: DBConnection2


Username: hr
Password: hr

5. We can test whether or not we can successfully connect to the database by


clicking the Test Connection button. Click the Test Connection button now! If
the database connection is successful, the word Success! is displayed at the big
box. Now, you can click the OK button, to complete the process of the database
connection creation.

Now, you can browse the contents of the HR schema. Simply, click the plus symbol (+)
to the left of the connection name to expand the navigation tree. For example, if we
double-click a certain table in the navigator, the structure of that table is displayed in the
main editing area of the window. It includes the details about the columns such as its
Name, Size, and data Type.
Now, if we want to view the data from a table, we will simply select the Data tab below
the table structure. Not only that, we can directly edit the database objects in the Database
Navigator. For example, to edit a table, we will simply right-click the table and select
Edit from the shortcut menu. This will cause the Edit Table dialog box to appear and
allows us to make changes to the selected table. You can see the Database Navigator of
JDeveloper window below:
420
421

Chapter 11
Learning JDBC Programming

Example 1:

Design and develop a JDBC application system which has the following functions and features:

1. Allow users to login to the application with username and password validation.
2. Establish a connection to the Oracle Database server.
3. Query the database table for data and retrieve the data by applying the JavaBean
implementation.
4. Allow the users to add, change, or erase the data records from the table.
5. Display the data by applying the Java Server Pages (JSP) implementation.
6. Lastly, handle some error-trapping code by applying Exception implementation.

Follow the design specification below:

Figure 10.1 System Login Page

MyCompany Inc. : Simple Personnel System

System Login: Unauthorized User Keep Out!

Username: hr

Password: hr

Host: localhost

Login Now!

Button Text fields


422

Figure 10.2 Filtered Search for MyWorkers Page

MyCompany Inc. : Simple Personnel System


MyWorkers Data

Enter (Last or First) Name: Silang Search

LastName FirstName Position Code Salary

Silang Gabriela MESSE 8,000

Silang Diego CLE 9,000

Figure 10.3 List of MyWorkers Page

Last Name First Name Position Code Salary Add


Worker

Change
Silang Gabriela MESSE 8,000 Erase

Cruise Juan SUPE 20,000 Change


Erase

Bonifacio Andres CLE 9,000 Change


Erase

Rizal Jose PRES 99,000 Change


Erase

Purisa Gavino GARDE 5,000 Change


Erase

Silang Diego CLE 9,000 Change


Erase
423

Figure 10.4 Adding Worker Record Page

MyCompany Inc. : Simple Personnel System

Add Worker Record

Use JDBC only to add a new record

Use Stored-Procedure via JDBC to add new record

Silang
Last Name:

First Name: Diego

Job Title Janitor

4,000
Salary

Add Now!

Button Text Fields

Figure 10.5 Edit Worker Record Page

MyCompany Inc. : Simple Personnel System

Change Worker Record

Last Name: Silang

First Name: Diego

Job Title Janitor

4,000
Salary

Change Now!

Button Text Fields


424

Figure 10.6 Page Flow Diagram (PFD) of the Personnel System Web Pages

index.jsp

login.jsp loging.jsp

myworkers.jsp add.jsp adding.jsp

Displays a list of workers


change.jsp changing.jsp
Contains:
* a text field for searching
workers
*a link to add workers
*a link to change record row
erasing.jsp
*a link to erase record row

Note:
The PFD shows you the interrelatedness of each and every web pages used within our Simple Personnel
System (SPS).

Here are the brief descriptions of the Web pages in our Simple Personnel System:

• index.jsp

This is the starting or opening web page of the personnel system. The index.jsp web page
will automatically forward the user to the login page of the system: login.jsp.

• login.jsp

This is the web page that allows the user to log in to the personnel system. The username,
password, and host information are validated for system security purposes. Moreover, the
information is also used to create the connection descriptor to login to the database
schema.

• loging.jsp
425

This is a non-viewable web page that handles the authentication of the user-supplied
login details such as username, password, and host information from login.jsp. If the
authentication is successful, the page forwards the user to myworkers.jsp. Otherwise, it
redisplays the login.jsp web page including an error message.

• myworkers.jsp

This is the main web page of our personnel system. It displays a list of all workers.
Furthermore, it allows the user to search for a particular worker using the worker’s name
(whether last name or first name). This main web page also includes links to add, change,
and erase any worker data.

• add.jsp

The link to add worker record on the myworkers.jsp page redirects the user to this web
page. This includes a form that accepts all the details for a new worker record. The details
entered on this form are processed by the adding.jsp web page.

• adding.jsp

This is a non-viewable web page that handles the adding of data record for a new worker
that is entered on the add.jsp web page.

• change.jsp

The link to change or modify (edit) worker data on the myworkers.jsp page redirects the
user to this web page. This form displays current data of a single worker in text fields,
and the user can edit this information.

• changing.jsp

The submit action (Change Now! button) on the change.jsp page directs the data to this
non-viewable web page, which adds the edited data into the table of the database.

• erasing.jsp

The link to erase a worker record on the myworkers.jsp page is handled by this non-
viewable web page, which erases the worker data and forwards the user back to the
myworkers.jsp web page.

Classes for Personnel System

The Personnel System includes the following classes:

• DataHandling.java
426

This class contains all the methods that are used to implement the important functions of
the personnel system. It includes methods that validate user credentials such as the
username, password, and host information. The other methods that are included are used
to connect to the database schema, retrieve worker data, add data, change (edit) data,
update data, handle exceptions, plus other methods.

• MyWorkers.java

This class is a JavaBean that holds a single worker record. It contains accessor methods
to get and set the values of each of the record fields. Furthermore, it also contains
accessor methods to retrieve and modify worker records.

• TestClient.java

We use this class only for testing the DataHandling class.

Let us now start our solution for this mini-case study which we present in a tutorial
format. In this way, we can easily follow the development of our simple business system
as it unfolds right through our two bare eyes. Are you ready now?
Here are our strategies to accomplish the given problem:

a. First, we will create the database tables, which we will named: MyWorkers and
MyPositions. Now, we need to create also the Primary Key Sequence which we
will named: MyWorker_Sequence.
b. Second, we will input data into our tables. These data are the names of our
workers.
c. Then, lastly, we will develop our Java EE application that is capable of searching,
adding, changing, or erasing a worker’s record.

Creating Database Tables and Primary Key Sequence

Solution:

1. At the Home Page of Oracle Database 10g Express Edition, select and click the
SQL icon. Next, select and click the SQL Commands icon.
2. This time, type the following script at the Script Editor:

CREATE TABLE MyWorkers (


EmpNo NUMBER(4) PRIMARY KEY NOT NULL,
LastName VARCHAR2(15),
FirstName VARCHAR2(15),
PosCode VARCHAR2(10),
Salary NUMBER(8,2)
);
427

3. Then click the Run button at the extreme right corner, to run the SQL script.

After running the SQL script above, you will get the following figure below:

If we had created our table successfully, we can see the following message (Results):

Table created.

4. We have to create the next database table - MyPositions:

CREATE TABLE MyPositions(


PosCode VARCHAR2(10) PRIMARY KEY NOT NULL,
Position VARCHAR2(20)
);

5. Then click the Run button at the extreme right corner, to run the SQL script.

Again, if we had created our table successfully, then we can see again the following
Results:

Table created.

6. Let us now create the MyWorker_Sequence, which is used to generate values for
the primary key (EmpNo) of the MyWorkers table:

CREATE SEQUENCE MyWorker_Sequence


START WITH 1000
INCREMENT BY 1;

7. Then click the Run button at the extreme right corner, to run the SQL script.
428

If we had created our Primary Key Sequence successfully, we can see the following
Results:

Sequence created.

Since, we had already accomplished our first strategy which is to create the two tables
and the primary key sequence, let us now go to the next strategy where we will input data
into our tables.

Managing Primary Key Sequences


A sequence is a database object that generates unique sequential values, often used for
primary and unique keys. Whenever practical, create a sequence number generator to
generate unique numeric values for your primary key values.
We can refer to sequence values in SQL statements with these pseudocolumns:

• CURRVAL – returns the current value of a sequence


• NEXTVAL – increments the sequence and returns the next value

We must qualify CURRVAL and NEXTVAL with the name of the sequence, such as
MyWorker_Sequence.NEXTVAL (or MyWorker_Sequence.CURRVAL).

When we create a sequence, we can define its initial value and the increment between its
values. The first reference to NEXTVAL returns the initial value of the sequence.
Subsequent references to NEXTVAL increment the sequence value by the defined
increment and return the new value. Any reference to CURRVAL returns the current
value of the sequence, which is the value returned by the last reference to NEXTVAL.

Inputting Data into Database Tables

8. Input now the following values into the MyWorkers table:

INSERT INTO MyWorkers (


EmpNo, LastName, FirstName,
PosCode, Salary
)
VALUES (MyWorker_Sequence.NEXTVAL,
'Silang', 'Gabriela', 'MESSE', 8000);

9. Then click the Run button at the extreme right corner, to run the SQL script.

If we were successful in entering a data record into our table, we can see the following
Results:
429

1 row(s) inserted.

Then next, input the following succeeding data records below (one by one) and run them:

INSERT INTO MyWorkers (


EmpNo, LastName, FirstName,
PosCode, Salary
)
VALUES (MyWorker_Sequence.NEXTVAL,
'Cruise','Juan', 'SUPE', 2000);

INSERT INTO MyWorkers (


EmpNo, LastName, FirstName,
PosCode, Salary
)
VALUES (MyWorker_Sequence.NEXTVAL,
'Bonifacio','Andres', 'CLE', 9000);

INSERT INTO MyWorkers (


EmpNo, LastName, FirstName,
PosCode, Salary
)
VALUES (MyWorker_Sequence.NEXTVAL,
'Rizal', 'Jose', 'PRES', 99000);

INSERT INTO MyWorkers (


EmpNo, LastName, FirstName,
PosCode, Salary
)
VALUES (MyWorker_Sequence.NEXTVAL,
'Purisa', 'Gavino', 'GARDE', 5000);

INSERT INTO MyWorkers (


EmpNo, LastName, FirstName,
PosCode, Salary
)
VALUES (MyWorker_Sequence.NEXTVAL,
'Silang','Diego', 'CLE',9000);

10. This time, we will input data into our MyPositions table:

Tip:
If you are using the e-book version of this book, you can copy and paste all the INSERT SQL scripts below
and save it into a Notepad and name it simply as MyPositionScript. Then, Upload and Run the
430

MyPositionScript at the icon of SQL Scripts, so that you don’t have to execute each INSERT SQL
command individually at the SQL Commands icon. Got it?

INSERT INTO MyPositions(PosCode, Position)


VALUES ('MESSE','Messenger');

INSERT INTO MyPositions(PosCode, Position)


VALUES ('SUPE','Supervisor');

INSERT INTO MyPositions(PosCode, Position)


VALUES ('CLE','Clerk');

INSERT INTO MyPositions(PosCode, Position)


VALUES ('PRES','President');

INSERT INTO MyPositions(PosCode, Position)


VALUES ('GARDE','Gardener');

INSERT INTO MyPositions(PosCode, Position)


VALUES ('MANA','Manager');

INSERT INTO MyPositions(PosCode, Position)


VALUES ('GUA','Guard');

INSERT INTO MyPositions(PosCode, Position)


VALUES ('JANI', 'Janitor');

INSERT INTO MyPositions(PosCode, Position)


VALUES ('ACCOU', 'Accountant');

INSERT INTO MyPositions(PosCode, Position)


VALUES ('CAS','Cashier');

INSERT INTO MyPositions(PosCode, Position)


VALUES ('BAGG','Bagger');

INSERT INTO MyPositions(PosCode, Position)


VALUES ('CHEC','Checker');

11. You can check if all the inputted data were stored at MyPositions table by issuing
the following SQL script:

SELECT * FROM MyPositions;

Can you see them all at the MyPositions table? I hope, you do.

12. You can now logout from the Oracle Database, by clicking the Logout link.

Note:
431

In developing Java EE (Enterprise Edition) Application in JDeveloper (or in other IDEs), we need to create
at least one Project in which to store our works.

This time, we are ready constructing our Java EE application program.

Creating the Java EE Application

Solution:

1. At your Windows 8, find and select the Oracle Fusion Middleware 11, then click
the JDeveloper Studio 11.
2. In the File menu of the Oracle JDeveloper 11g, select New to create the New
application program.
3. At the New Gallery dialog box, under the selection of Categories:, then under
the General category, select Applications. Now, under the selection of Items:,
select the Generic Application. Finally, click the OK button below.
4. At the Create Generic Application dialog box (Step 1), enter SPSApp in the
text-field of Application Name:. Then, leave all text-field as they are. You can
see below the partial figure of the Create Generic Application dialog box.
Finally, click the Next button.

5. Still at the Create Generic Application dialog box (Step 2), we have to enter the
name of the project. So, enter the word: view (as the name of our project) in the
text-field of Project Name:. Finally, click the Finish button.

You can now observed, that the SPSApp application is displayed in the Application
Navigator window (extreme upper-left part of the IDE) as you can see it in our partial
figure below:
432

Creating a Class in Java

The first step in developing a Java application program is to construct a Java class. Here,
we will construct the DataHandling class which will contain the methods for querying
the Oracle database and modifying the data in it.

Solution:

1. In the Application Navigator window, right-click the view project, then from the
short-cut menu, select New.
2. In the New Gallery dialog box, select Java under the General category (which in
turn under the selection of Categories:). Now, at the selection of Items:, select
Java Class (which usually the default selection). Finally, click the OK button.

This will display the Create Java Class dialog box below:

3. Enter DataHandling as the class name (at the Name: text-field) and sps as
the package name (at the Package: text-field). Then leave all other default values
as is. Finally, click the OK button.
433

4. Now, save your work by going to the File menu, then select and click the Save
All menu-item.

After clicking the OK button, the skeleton DataHandling class is generated and
displayed at the Source Editor window of the JDeveloper as you can see at the partial
figure below:

You can see here at the skeleton of the DataHandling class (above figure), the package
declaration, the class declaration, and the default constructor which are generated by
default.
434

Using Java Libraries

The Oracle JDeveloper IDE has standard libraries to support our Java application task.
These Oracle libraries include Application Programming Interface (API) support for
JDBC, JSP and Oracle’s ADF (Application Development Framework), and many others.
To use the JDBC libraries and JSP technology, we should import the Oracle JDBC
library and JSP Runtime libraries into our project, respectively.

The Oracle JDBC Library Explained

We have here the three most important packages of the Oracle JDBC library:

• oracle.sql
This package supports direct access to data in SQL format. Furthermore, it consists
primarily of classes that provide Java mappings to SQL data types and their support
classes.

• oracle.jdbc
This package defines the Oracle extensions to the interfaces in the java.sql package.
Furthermore, these extensions provide access to Oracle SQL-format data and other
Oracle-specific features, including Oracle performance enhancements.

• oracle.jdbc.pool
This package includes the OracleDataSource class that is used to get a connection to the
Oracle database. The overloaded method which is called getConnection returns a physical
connection to the Oracle database.

The JSP Runtime Library Explained

This library includes the tag libraries and classes required to interpret and run JSP files on
the Oracle Container for Java (OC4J) server that comes with the JDeveloper IDE.

Adding JDBC and JSP Libraries

Solution:

1. In the Application Navigator window, double-click the view project to display


the Project Properties dialog box.
2. Now at the Project Properties dialog box, select and click the Libraries and
Classpath, and then click the Add Library… button.
3. In the Add Library dialog box, scroll through the list of libraries, then select the
JSP Runtime library. Finally, click the OK button. Now, repeat the procedure for
435

adding the Oracle JDBC library also (and don’t forget to click the OK button to
add it), as shown in the figure below:

If you are successful in adding the JSP Runtime and Oracle JDBC libraries, you can see
them added at your view project’s Classpath Entries:, as shown below:

4. Since, we were successful in adding JSP Runtime and Oracle JDBC libraries into
our view project, let us now click the OK button (to finalize our process) in our
Project Properties dialog box.
436

Importing JDBC Packages and Creating Connection Method

Solution:

1. This time, add and type the following code (bold only) within our DataHandling
class:

package sps;
import java.sql.Connection;
import java.sql.SQLException;
import oracle.jdbc.pool.OracleDataSource;

public class DataHandling {


public DataHandling() {
}
String jdbcUrl = null;
String username = null;
String password = null;
Connection conn;
public void getDBConnection() throws SQLException{
OracleDataSource ds;
ds = new OracleDataSource();
ds.setURL(jdbcUrl);
conn=ds.getConnection(username,password);
}
}

2. Now, this time, we have to compile our DataHandling class to ensure that we
have no syntax error. To accomplish this task, simply right-click the mouse within
the Java Source Editor, then select the Make from the shortcut menu. The
Successful compilation message should be displayed in the Log window which
can be found below the Java Source Editor window, as shown in the figure below:
437

Note:
We can also be assured that our code might be free from syntax errors if we can see the small green box at
the upper side of our Java Source Editor. In contrast, we can also be warned of syntax errors if the small red
boxes are present at the upper side.

Explanation:

The connection information is passed to the connection method by using the following
connection variables: the connection URL, the username, and the corresponding
password, thus we have the following variable declarations:

package sps;
import java.sql.Connection;
import java.sql.SQLException;
import oracle.jdbc.pool.OracleDataSource;

public class DataHandling {


public DataHandling( ) {
}
String jdbcUrl = null;
String username = null;
String password = null;
.
.
The above variables will be used by our Simple Personnel System (SPS) application to
contain values supplied by the user at the Login page to authenticate him or her and as
well as to create a connection to the Oracle database. Furthermore, the jdbcUrl variable is
used to hold the Universal Resource Locator (URL) of the database that we will connect
to, while the username and password variables are used to authenticate the user and
identify the database schema to be used for the session.
Since, we had used the following built-in classes of Oracle JDBC library (in bold) within
our SPS application:
.
.
Connection conn;
public void getDBConnection() throws SQLException{
OracleDataSource ds;
ds = new OracleDataSource();
ds.setURL(jdbcUrl);
conn=ds.getConnection(username,password);
}
}

we need to import their packages, such as follows:


438

package sps;
import java.sql.Connection;
import java.sql.SQLException;
import oracle.jdbc.pool.OracleDataSource;
.
.
You will also notice that we had declared two classes instances: conn (for connection)
and ds (for data source).
In Java programming, we use an instance of the DataSource object (in our case it is the
ds) to get a connection to the database. The DataSource interface provides a complete
replacement for the previous JDBC DriverManager class. The overloaded getConnection
method returns a physical connection to the database. To connect to the Oracle database,
we had created the getDBConnection( ) method.

Note:
Now, remember that the SQLException’s role in our program is specifically for error-handling
mechanism.

Creating A Method For Querying Data

Solution:

1. In the DataHandling class, edit and revise your code using the added script (in
bold only):

package sps;
import java.sql.Connection;
import java.sql.SQLException;
import oracle.jdbc.pool.OracleDataSource;
import java.sql.Statement;
import java.sql.ResultSet;

public class DataHandling {


public DataHandling() {
}
// String jdbcUrl = null;
// String username = null;
// String password = null;
String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:XE";
String username = "hr";
String password = "hr";
Connection conn;
Statement stmt;
ResultSet rset;
String query;
String sqlString;
public void getDBConnection() throws SQLException{
OracleDataSource ds;
ds = new OracleDataSource();
439

ds.setURL(jdbcUrl);
conn=ds.getConnection(username,password);
}

public ResultSet getAllWorkers() throws SQLException{


getDBConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
query = "SELECT * FROM MyWorkers ORDER BY lastname";
System.out.println("\nQuery executed: " + query);
rset = stmt.executeQuery(query);
return rset;
}
}

2. Now, compile your DataHandling class by right-clicking the mouse within the
JavaSource Editor, and select Make from the shortcut menu.

See to it, that there are no syntax errors found in your revised DataHandling class.

Explanation:

You will notice that we had imported two additional packages here:

package sps;
import java.sql.Connection;
import java.sql.SQLException;
import oracle.jdbc.pool.OracleDataSource;
import java.sql.Statement;
import java.sql.ResultSet;
.
.
These packages are needed so that we can use the Statement and ResultSet classes within
the Oracle JDBC library such as the following code:
.
.
public class DataHandling {
public DataHandling() {
}
// String jdbcUrl = null;
// String username = null;
// String password = null;
String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:XE";
String username = "hr";
String password = "hr";
Connection conn;
Statement stmt;
ResultSet rset;
440

String query;
String sqlString;
.
.
We also hardcoded the string value for our connection string (jdbcUrl, username, and
password) so that we can connect successfully to the HR schema. This is temporary
since we used them for testing purposes only. Well, with the combination of the
TestClient class that calls the DataHandling class.
Now, we created a method called getAllWorkers( ), which will be used to retrieve the
workers information from the database:
.
.
public ResultSet getAllWorkers( ) throws SQLException{
getDBConnection( );
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
query = "SELECT * FROM MyWorkers ORDER BY lastname";
System.out.println("\nQuery executed: " + query);
rset = stmt.executeQuery(query);
return rset;
}

We apply the createStatement( ) method of the Connection instance to provide context


for executing the SQL statement and define the ResultSet type. Furthermore, we specify a
read-only, scroll-sensitive ResultSet type. Scroll-sensitive refers to the ability to move
backward as well as forward through a result set. You could also observed that we define
the query and print the trace message by using the System.out.println( ) function of Java
programming language. The ORDER BY command of Oracle Database means we will
arranged the queried data by the worker’s lastname. In this way, we can search a
particular worker easily.

Creating TestClient Class

Solution:

1. In the Application Navigator window, right-click the view project, then from the
short-cut menu, select New.
2. In the New Gallery dialog box, select Java under the General category (which in
turn under the selection of Categories:). Now, at the selection of Items:, select
Java Class. Finally, click the OK button.

This will display the Create Java Class dialog box.

3. Enter TestClient as the class name (at the Name: text-field) and sps as the
package name (at the Package: text-field). Then at the Optional Attributes, click
441

the check box control of the Generate Main Method option. Finally, click the OK
button.

Now, edit your code using the added and revised script below (bold text only):

package sps;
import java.sql.ResultSet;
public class TestClient {
public TestClient() {
}

public static void main(String[] args) throws Exception {


DataHandling datahandling = new DataHandling();
ResultSet rset;

rset = datahandling.getAllWorkers();
System.out.println("\nEMPNO COMPLETE NAME");
System.out.println("----- -------------------");
while (rset.next()) {
System.out.println(rset.getInt(1) + " " +
rset.getString(2) + ", " +
rset.getString(3));
}
}
}

4. Now, compile your TestClient class by right-clicking the mouse within the
JavaSource Editor, and select Make from the shortcut menu.

See to it, that there are no syntax errors found in your revised TestClient class.

Note:
Take note that we have to add and replace some codes in our TestClient program as they are denoted by
bold only scripts within the entire program. They are, “to add - throws Exception, and replace TestClient…
with DataHandling datahandling = new DataHandling( );”. Can you see them?

5. Run now your TestClient by right-clicking the mouse within the JavaSource
Editor, and select the Run from the shortcut menu.

Sample Output:
442

Explanation:

In the main method of our TestClient class, we add an exception handling as you can
observe it in our code below:

package sps;
import java.sql.ResultSet;
public class TestClient {
public TestClient() {
}

public static void main(String[] args) throws Exception {


DataHandling datahandling = new DataHandling( );
ResultSet rset;

rset = datahandling.getAllWorkers();
System.out.println("\nEMPNO COMPLETE NAME");
System.out.println("----- -------------------");
while (rset.next()) {
System.out.println(rset.getInt(1) + " " +
rset.getString(2) + ", " +
rset.getString(3));
}
}
443

Then, we simply replaced the TestClient object created by default with a DataHandling
object.
Next, we defined a ResultSet object to hold the results of the getAllWorkers query, and
iterate through the data rows of the result set (using the while-loop statement), displaying
the first three columns (EmpNo, LastName and FirstName, respectively) of MyWorkers
table. Since the data type of our EmpNo column was declared as NUMBER within our
Oracle Database, that is why we used the getInt( ) method to get it. Now, since the
LastName and FirstName columns were declared as VARCHAR2 within our Oracle
Database, that is why we used the getString( ) method to get it. Got it? I hope so, buddy.

Creating the JSP Pages

Solution:

1. In the Application Navigator window, right-click the view project, then from the
short-cut menu, select New.
2. In the New Gallery dialog box, select JSP under the Web Tier category (which
in turn under the selection of Categories:). Now, at the selection of Items:, select
JSP (but not other options such as JSP Segment, JSP Tag File, or JSP Tag
Library). Finally, click the OK button.

This will display the Create JSP dialog box.

3. Enter myworkers.jsp as the file name at the File Name text-field . Finally,
click the OK button.

You will notice here that you are brought into the new blank web page within the
JSP/HTML Visual Editor for you to design and develop your web page.

Follow the design specification below:

Figure 10.2 Filtered Search for MyWorkers Page

MyCompany Inc. : Simple Personnel System

MyWorkers Data

Enter (Last or First) Name Silang Search

LastName FirstName Position Code Salary

Silang Gabriela MESSE 8,000

Silang Diego CLE 9,000


444

4. Now at the top line of our web page, let us type the heading MyCompany
Inc.: Simple Personnel System. From the list of styles at the top of
the web page (in the Selection Box), select Heading 2, to format our header.
5. With the cursor still on the heading we added, from the Design menu (of
JDeveloper), select Align menu-item, then select the Center menu-item.
6. In a similar way, on a new line, type MyWorkers Data and format it with the
Heading 3 style. Let us position this heading on the left-hand side of the web
page by clicking the Design menu (of JDeveloper), then select the Align menu-
item, and finally, select the Left menu-item.
7. This time, let us choose a Cascading Style-Sheets (CSS) for our web page. Click
the down- arrow at the top right of the Component Palette, then select CSS.
8. From the CSS list, drag JDeveloper item onto our webpage, then click the Save
button, to accept the default File name: jdeveloper.css.

Adding a JSP useBean Tag

Solution:

1. In the Component Palette, let us select the JSP set of components. Scroll through
the list to select UseBean. Then, drag and drop it onto our JSP web page, below
the headings.
2. In the Insert UseBean dialog box, type worksbean as the ID:, and for the
Class:, click the Browse button. Now, click the Search tab, then enlarge the sps
option by clicking the + (plus) symbol and select the DataHandling class. This
time, set the Scope to session, and leave the Type: and BeanName: fields as
blank. Finally, click the OK button.

Here is our UseBean configurations below:


445

3. Select Scriptlet, then drag and drop it onto our JSP web page next to the
representation of the UseBean.
4. In the Insert Scriptlet dialog box, type the following lines of code, which will
call the getAllWorkers method and produce a ResultSet object:

ResultSet rset;
rset = worksbean.getAllWorkers();

5. Then, click the OK button.


6. Select the Source tab at the bottom of the Visual Editor to see the code that has
been created for our web page so far. You can see a wavy line under the ResultSet
as well as at the rset lines of code which indicate that there are errors in our code.

The Structure window on the left –hand side of JDeveloper also indicates any errors in
the web page, as you can observe it in our figure below:
446

7. To solve the errors, we must import the ResultSet package. To accomplish this
task, we have to click the page (page directive) node in the Structure window to
display the page properties in the Property Inspector.
8. Click in the empty box to the right of the Import: property. Then, click the down-
arrow and select the Edit… menu-item. This time, click the Hierarchy tab. The
Edit Property dialog box is displayed, as shown below:

9. In the Edit Property, expand the java node, then the sql node, and then select the
ResultSet. Finally, click the OK button.
447

Warning!
After accomplishing the step 9, the errors in the Structure window should disappear, as well as the
wavy lines in our source code. This means that the Green box at the right side of our Visual Editor
is now displayed instead of the previously displayed Red box.

Adding a Table Control into the JSP

Solution:

1. Select the Design tab at the Visual Editor, then position the cursor after the
scriptlet, and from the HTML Common page of the Component Palette, select
and click the Table component.
2. In the Insert Table dialog box, specify 1 row and 4 columns. Then, leave all
Layout properties as is (defaults), by clicking the OK button.
3. In the table row displayed on the web page, type the following texts as
headings for each of the columns: LAST NAME, FIRST
NAME,POSITION CODE, and SALARY. Use Heading 4 to format all the
column names.
4. Add a scripting element for output, this time to display the values returned for
each of the columns in the table. To accomplish this task, select the table as
follows. Position the cursor on the top border of the table, and click when the
cursor image changes to a table image. From the JSP Component Palette,
select Scriptlet. (You don’t need to drag the Scriptlet component into your
table, because it will be inserted automatically.)
5. In the Insert Scriptlet dialog box, type the following lines of code:

while (rset.next()) {
out.println("<tr>");
out.println("<td>"+
rset.getString("LastName")+"</td><td>"+
rset.getString("FirstName")+"</td><td>"+
rset.getString("PosCode")+"</td><td>"+
rset.getString("Salary")+"</td>");
out.println("</tr>");
}

6. Finally, click the OK button.


448

Creating Methods for Search Filtering

Solution:

1. Open the DataHandling.java class, type the following code (after the
getAllWorkers( ) method) for the search filtering method:

public ResultSet getWorkersByName(String name)


throws SQLException {
name = name.toUpperCase();
getDBConnection();
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
query =
"SELECT * FROM MyWorkers WHERE UPPER(
LastName) LIKE \'%" + name + "%\'" +
"OR UPPER(FirstName) LIKE \'%" + name +
"%\' ORDER BY LastName";
System.out.println("\nQuery executed:"+query);
rset = stmt.executeQuery(query);
return rset;
}

2. Save the DataHandling.java class file and compile it to ensure that there are no
compilation errors. To compile, simply right-click the mouse then select Make
from the short-cut menu.

Warning!
Make sure that there are no compilation errors in your DataHandling.java class. The “Successful
Compilation: 0 errors, 0 warnings” message should be seen at the left-hand and extreme bottom part of
the JDeveloper. The other way to see if there are no bugs in our program is the presence of the small Green
box at the side of our Java Source Editor. Can you see it? I hope so, buddy. In case, there are errors in
coding the SELECT statement, try to put the LastName) LIKE \... code in one line only like the following:

"SELECT * FROM MyWorkers WHERE UPPER(LastName) LIKE \'%" + name + "%\'" +




This solution should make the errors (indicated with a red box at the side of the Java
Source Editor) to disappear. And the Green box will appear instead.

3. Open the TestClient.java class, type the following code (after the } (end) symbol
of the while ( ) statement):

// filtered by Name with "Silang" as value


rset = datahandling.getWorkersByName("Silang");
System.out.println("\n Query results: ");
System.out.println("\nEMPNO LASTNAME FIRSTNAME SALARY");
System.out.println("------ ------- --------- --------");
while (rset.next()) {
System.out.println(rset.getInt(1) + " " +
rset.getString(2) + ", " +
449

rset.getString(3) + " " +


rset.getString(5));
}

4. Test-run the code by right-clicking the mouse then select Run from the short-cut
menu.

Sample Output:

Explanation:

We have here the method within our DataHandling.java that will get the workers by
Name:
.
.

public ResultSet getWorkersByName(String name)


throws SQLException {
name = name.toUpperCase( );
getDBConnection( );
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
450

.
.
The method passes only one parameter called: name. Now, we have to apply the
UpperCase( ) function so that when the user enters all or any capital letters in a given
searched-string, our method will be able to search the data successfully. The
TYPE_SCROLL_SENSITIVE, and CONCUR_READ_ONLY are the object types of
ResultSet which refer to the ability to move backward or forward through a result set.
When creating a scrollable (positionable) result set, we must also specify the sensitivity
which refers to the ability of the result set to detect and reveal changes made to the
underlying database from outside the result set. A result set may be updatable or read-
only. The CONCUR_READ_ONLY means concurrent and read-only result set.
We have the following SQL script to query a group (set) of data:
.
.
query =
"SELECT * FROM MyWorkers WHERE UPPER( LastName)
LIKE \'%" + name + "%\'" + "OR UPPER(FirstName)
LIKE \'%" + name + "%\' ORDER BY LastName";
.
.
Then, finally, we will display the result of the query with the following Java commands:
.
.
System.out.println("\nQuery executed:"+query);
rset = stmt.executeQuery(query);
return rset;

Now, this time let us examine how to call the method from DataHandling.java class
within our TestClient.java:
.
.
// filtered by Name with "Silang" as value
rset = datahandling.getWorkersByName("Silang");
System.out.println("\n Query results: ");
System.out.println("\nEMPNO LASTNAME FIRSTNAME SALARY");
System.out.println("------ ------- --------- --------");
while (rset.next()) {
System.out.println(rset.getInt(1) + " " +
rset.getString(2) + ", " +
rset.getString(3) + " " +
rset.getString(5));
}

The rset.get???(?) function means getting the data from our table. Moreover, the
parameter value of 1 refers to the column 1 of our table, while the value 2 refers to the
column 2, and so on.
451

Since our column 1 is the employee number (EMPNO), then column 2 is the last name
(LASTNAME) and so on, thus our output above reflects these arrangements. What about
the rset.getString(5)? We have to take note that the column Salary is in column number
5, since column number 4 is occupied by the Position Code (POSCODE). Got it?
You can also observe that we filter the search by the LastName: Silang, to test the
filtering functionality of our program. In actual operation, this parameter will be set to the
value provided by the user of our application system to filter the search.

How ResultSet Works?

A ResultSet object contains a table of data representing a database result set. This is
generated by executing a statement that queries the database. A cursor points to the
current row of data in a ResultSet object. This is initially positioned before the first row.
As you could observe in our example, we use the next( ) method of the ResultSet object
to move the cursor to the next row in the result set. The next( ) method returns the
boolean value of false when there are no more rows in the ResultSet object. Ideally, the
contents of the ResultSet object are read by using the next( ) method within a while( )
loop until it returns the boolean value of false.
The ResultSet interface provides accessor methods for retrieving column values from the
current row. The most common accessor methods are getString( ), getInt( ), getLong( ),
getBoolean( ), and much much more. We have to take note that the values can be
retrieved by using either the index number of the column or the name of the column.

Adding Filter Controls to the JSP Page

Figure 10.2 Filtered Search for MyWorkers Page

MyCompany Inc. : Simple Personnel System


MyWorkers Data

Enter (Last or First) Name Silang Search

LastName FirstName Position Code Salary

Silang Gabriela MESSE 8,000

Silang Diego CLE 9,000


452

Solution:

1. Select the Design tab at the Visual Editor, then position the cursor below the
MyWorkers Data (or between the useBean tag and the scriplet) , and from the
HTML Common page of the Component Palette, select and click the Form
component.
2. In the Insert Form dialog box, use the down arrow for the Action field and select
myworkers.jsp. Leave the other fields empty and click the OK button.

You could notice that the Form control is displayed on the page in the Visual Editor,
represented by a dotted-line rectangle.

3. In the HTML Forms page of the Component Palette, scroll to Text Field. Select
then drag and drop it inside the Form component. In the Insert Text Field dialog
box, enter query as the value of the Name field and finally click the OK button.

You could notice that the text field box is displayed within the Form control. This field
allows the user to enter the filter criteria.

4. Position the cursor to the left side of the Text Field and write the following text:

Enter (Last or First) Name:

5. In the HTML Forms page of the Component Palette, scroll to Submit Button.
Select and drop it inside the Form component to the right side of the Text Field.
6. In the Insert Submit Button dialog box, leave the Name field empty and enter
Search as the value of the Value field, then click the OK button.

After you accomplished the given task above, your HTML Form components should look
like the following figure:
453

Explanation:

Here in the task above, we created a text field component on the JSP Page that accepts
user inputs. In this text field, the user can specify a string with which to filter worker
names. We also add a Submit button which we named as Search button.

Displaying Filtered Data in the JSP Page

Solution:

1. Modify the Scriptlet tag on the page, with the following code:

ResultSet rset;
String query = request.getParameter("query");
if (query !=null && query !=null)
rset=worksbean.getWorkersByName(query);
else
rset=worksbean.getAllWorkers();

2. Now, click the OK button, then Save the file.

Explanation:

In the text field above, we can specify a string in which we can filter workers name. We
also added a submit button which we named: Search.
We add code to our scriptlet in the myworkers.jsp file, to enable it to use the
getMyWorkersByName method. This method is used only if we submit a value for
filtering the results. If this filter criterion is not specified, the getAllWorkers method is
used, instead.

Creating a Method to Authenticate Users

Solution:

1. Open the DataHandling.java class in the Source Editor.


2. Create a method that checks if the supplied values for username, password, and
host are valid or correct. Type now the following code (after the
getWorkersByName method):
public boolean authenticateUser(String jdbcUrl, String username,
String password, HttpSession session) throws SQLException {
this.jdbcUrl= jdbcUrl;
this.username = username;
this.password = password;
try {
454

OracleDataSource ds;
ds = new OracleDataSource();
ds.setURL(jdbcUrl);
conn = ds.getConnection(username, password);
return true;
}
catch ( SQLException ex ) {
System.out.println("Unauthorized user credentials!");
session.setAttribute("errmsglogin", "Login Failed. Pls.try
again.");
this.jdbcUrl = null;
this.username = null;
this.password = null;
return false;
}
}

3. For now, just save the DataHandling.java file.

Explanation:

Here we create a method called authenticateUser( ) that checks if the username,


password, and host values supplied by the user are valid:

public boolean authenticateUser(String jdbcUrl, String username, String


password,HttpSession session) throws SQLException {


}

The IDE JDeveloper will prompt us with a wavy underline and a message that we need to
import a class for HttpSession. We can accomplish this by simply pressing the Alt+Enter
keys:


import javax.servlet.http.HttpSession;

Note:
You can see all the import statements at the extreme topmost part of our code.

Within the body of the method, we assign the jdbcUrl, username, and password values
from the call to the attributes of the current object like the following:


this.jdbcUrl= jdbcUrl;
this.username = username;
455

this.password = password;


We attempt to connect to the database using the values supplied by the user, and if
successful, return a value of true. We enclose this in a try block like the following:


try {
OracleDataSource ds;
ds = new OracleDataSource();
ds.setURL(jdbcUrl);
conn = ds.getConnection(username, password);
return true;
}


In order to handle the case where the login credentials do not match, after the try block,
add a catch block. The code in this block prints out a log message and sets up an error
message. This error message can be displayed to the user if a login attempt fails. The
jdbcUrl, username, and password variables are set back to null, and the method returns
the value of false. Here below is our catch block code:
...

catch ( SQLException ex ) {
System.out.println("Unauthorized user credentials!");
session.setAttribute("errmsglogin", "Login Failed. Pls.try again.");
this.jdbcUrl = null;
this.username = null;
this.password = null;
return false;
}

Now, that’s the end of our discussion.

Creating a Login Page

Solution:

1. In the Application Navigator window, right-click the view project, then from the
short-cut menu, select New.
2. In the New Gallery dialog box, select JSP under the Web Tier category (which
in turn under the selection of Categories:). Now, at the selection of Items:, select
JSP (but not other options such as JSP Segment, JSP Tag File, or JSP Tag
Library). Finally, click the OK button.
456

This will display the Create JSP dialog box.

3. Enter login.jsp as the file name at the File Name text-field . Finally, click
the OK button.

You will notice here that you are brought into the new blank web page within the
JSP/HTML Visual Editor for you to design and develop your web page.

Follow the design specification below:

MyCompany Inc. : Simple Personnel System

System Login: Unauthorized User Keep Out!

Username: hr

Password: hr

Host: localhost

Login Now!

Button Text fields

4. Now at the top line of our web page, let us type the heading MyCompany
Inc.: Simple Personnel System. From the list of styles at the top of
the web page (in the Selection Box), select Heading 2, to format our header.
5. With the cursor still on the heading we added, from the Design menu (of
JDeveloper), select Align menu-item, then select the Center menu-item.
6. In a similar way, on a new line, type System Login: Unauthorized
User Keep Out! and format it with the Heading 3 style. Let us position this
heading on the left-hand side of the web page by clicking the Design menu (of
JDeveloper), then select the Align menu-item, and finally, select the Left menu-
item.
7. This time, let us choose a Cascading Style-Sheets (CSS) for our web page. Click
the down- arrow at the top right of the Component Palette, then select CSS.
8. From the CSS list, drag JDeveloper item onto our webpage, then click the Save
button, to accept the default File name: jdeveloper.css.
457

Preparing an Error Message for Failed Logins

Solution:

1. With the login.jsp web page is open in the Visual Editor, position the cursor after
the text on the current web page. Then, from the JSP page of the Component
Palette, let us drag and drop the Scriplet element from the palette on to the page.
2. In the Insert Scriplet dialog box, enter the following code:

String errmsglogin=null;
errmsglogin =(String)session.getAttribute("errmsglogin");
if (errmsglogin !=null) {

Let us add another scriplet in exactly the same way, and this time we enter only a single
closing brace ( } ) in the Insert Scriplet dialog box.
Next, we have to place the cursor between the two scriplets and press the Enter key to
create a new line. Let us apply the Heading 4 style to the new line.

3. Now, click the Expression in the JSP page of the Component Palette, then enter
only this code:

errmsglogin

4. The code in your Scriplet should look like the following:




<%String errmsglogin=null;
errmsglogin =(String)session.getAttribute("errmsglogin");
if (errmsglogin !=null) {
%>
<h4>
<font color="Red">
<blink>
<%=errmsglogin%>
</blink>
</font>
</h4>
<p>
</p>
<%}%>

Explanation:

You could notice that in our script, we add two tags: the color tag- red and blink tag.
This will make our displayed error message as color red and it will also blink. And it is
also formatted as header (H) 4 style.
458

Now at the design view of the web page (by selecting the Design tab), we can start
creating the login interface.


if (errmsglogin !=null) {
%>
<h4>
<font color="Red">
<blink>
<%=errmsglogin%>
</blink>
</font>
</h4>


We have to remember that it will only happen if the login error message is not equal to
null. Meaning, the user was not able to login successfully, maybe because he or she has
the wrong password, username or host name. Now, the other thing to remember is that
the login error message code is coming from our DataHandling.java class:


catch ( SQLException ex ) {
System.out.println("Unauthorized user credentials!");
session.setAttribute("errmsglogin", "Login Failed. Pls. try again.");

The “Unauthorized user credentials!” error message will be displayed at the Messages
window (bottom part) of our JDeveloper IDE, as an error-feedback to our Java EE
application that we design and develop.

Note:
You could notice that in login.jsp, we can see the red box appears at the side of the Visual Editor. This
means that there could be a syntax error in our HTML script for font color and blink tags. However, this is
a false alarm since our login.jsp web page will work according to our expectation, since this is not a syntax
error, it is only a false error message. Strange, isn’t it? This further means, that even IDEs has limitations
too…in determining errors. Got it?

Creating the Login Interface

Solution:

1. Open the login.jsp web page now, then select the Design tab.
2. Position the cursor after the second scriplet, then select the Form under the HTML
Forms web page of the Component Palette. You could notice that the Form is
459

displayed on the web page in the Visual Editor, represented by a rectangle dotted-
line.
3. In the Insert Form dialog box, enter loging.jsp as the value for the Action field.
Just leave the other fields empty, then click the OK button.

The loging.jsp file will be used to process the user input in the login.jsp file. However,
we cannot select this page from a list as it is not created yet.

4. Let us now add a Table to the web page, by positioning it inside the Form. We
have to specify a 3-row and 2-column layout, and just accept other layout
defaults.
5. In the first column of the three rows, enter the following as the text to display for
the users:

Username:
Password:
Host:

6. Now from the HTML page of the Component Palette, drag a Text Field into the
Table cell to the right of the Username: cell. In the Insert Text Field dialog box,
enter username as the value of the Name property. Just leave the other fields
empty, then click the OK button.
7. In the same way, let us add a Text Field to the table cell to the right of the
Password: cell and enter password as the value of the Name property.
Similarly, add a Text Field to the table cell to the right of the Host: cell and enter
host as the value of the Name property.
8. Finally, let us drag a Submit button to the Form below the table. Now, we enter
Login Now! as the Value property of the button.

Our login.jsp web page should look like the following:


460

Creating a JSP Web Page to Handle Login Action

Note:
The loging.jsp is a non-viewable web page that processes our login operation.

Solution:

1. In the Application Navigator window, right-click the view project, then from the
short-cut menu, select New.
2. In the New Gallery dialog box, select JSP under the Web Tier category (which
in turn under the selection of Categories:). Now, at the selection of Items:, select
JSP (but not other options such as JSP Segment, JSP Tag File, or JSP Tag
Library). Finally, click the OK button.

This will display the Create JSP dialog box.

3. Enter loging.jsp as the file name at the File Name text-field . Finally, click
the OK button.

You will notice here that you are brought into the new blank web page within the
JSP/HTML Visual Editor for you to design and develop your web page.

4. From the JSP page of the Component Palette, let us drag a Page Directive
component to the web page. In the Insert Page Directive dialog box, for the
Import field, browse to import java.sql.ResultSet. Finally, click the OK button.

Note:
To accomplish the above task, just simply select the Search tab, then click the java item of the Class and
Package Browser, then next select the sql item. Select the ResultSet item (under the sql item). Finally,
click the OK button. Got it?

5. Drag a UseBean tag onto the web page. Enter worksbean as the ID and
browse to select sps.DataHandling as the Class. Set the Scope to session, then
click the OK button.
6. Let us position the cursor after the UseBean tag and add a Scriplet to the web
page. Enter the following code into the Insert Scriplet dialog box:

boolean userIsValid=false;
String host = request.getParameter("host");
String username = request.getParameter("username");
String password = request.getParameter("password");
String jdbcUrl = "jdbc:oracle:thin:@"+host+":1521:XE";
userIsValid=
worksbean.authenticateUser(jdbcUrl,username,password,session);

7. Then, click the OK button.


8. Add another Scriplet, then add the following code:
461

if (userIsValid) {

9. Then, click the OK button.


10. While you are in the JSP page of the Component Palette, find Forward and drag
it onto the web page. This will add a jsp:forward tag onto the web page. In the
Insert Forward dialog box, enter myworkers.jsp (by browsing it). Then, click the
OK button.
11. Add another Scriplet, then enter the following code:

} else {

12. Add another jsp:forward tag (and this time move forward to login.jsp). In the
Insert Forward dialog box, enter login.jsp (by browsing it). Then, click the OK
button.

13. Add our last Scriplet, and enter a closing brace ( } ).

14. Let us save our work by going to the File menu, then select the Save All item.

The code in your loging.jsp file should look like the following (by selecting its Source
tab):


%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="java.sql.ResultSet"
session="true"
autoFlush="true"
isThreadSafe="true"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252"/>
<title>loging</title>
</head>
<body>

<jsp:useBean id="worksbean" class="sps.DataHandling" scope="session"/>


<%boolean userIsValid=false;
String host = request.getParameter("host");
String username = request.getParameter("username");
String password = request.getParameter("password");
String jdbcUrl = "jdbc:oracle:thin:@"+host+":1521:XE";
userIsValid=
worksbean.authenticateUser(jdbcUrl,username,password,session);
%>
<%if (userIsValid) {%>
<jsp:forward page="/myworkers.jsp"/>
<%} else {%>
<jsp:forward page="/login.jsp"/><%}%>
</body>
</html>
462

So, this is the end of our loging.jsp code.

Testing our JSP Web Page


1. In the Application Navigator, right click the view project, and select Run.

In this particular case of our activity, we will be prompted to specify a Default


Run Target for our project. Just for the purpose of our lab activity today, we will
set this to login.jsp. We can later change the project properties for the
default run target web page to be any webpage of our choice.
2. Just click the Browse button, then click the Project tab.
3. Now, select the public_html folder and click the Open button.
4. This time, select the login.jsp item and click the Open button.
5. Finally, click the OK button.

The login web page that we designed is displayed in our web browser, as shown below:

6. Let us enter the following details for our database, and then click the Login Now!
button.

Username: hr
Password: hr
463

Host: localhost

Note:
In an actual Java EE application in a company, this is the host name of the machine with the Oracle
Database server. In other words, this could be the website where our database server resides (anywhere in
the world!).

The personnel in our MyWorkers table are displayed in our web browser as shown below:

7. We can also enter only the last name of the personnel to filter them. For example,
we can enter lastname: silang in the Search text box. We can now see the
displayed filtered list below:
464

8. Or, if you can only remember his first name, we can enter it. For example, we can
remember his first name as: gavino . Let us try entering it! See? We can make it
happen!

What a splendid experience with Java EE application development! Truly, a very


exhilarating feeling. Isn’t it?
465

Chapter 12
Updating Data in Java EE Application

In this chapter, we will see how we can modify the sample Java EE application and add
functionality that allows our users to change, update, and erase data in Oracle Database.

Creating a JavaBean

Simply, a bean is a Java class that has methods, events, and properties. For each of its
properties, the bean also includes methods called “accessors”. The accessors are the get
and set methods.
In our Java EE application, we used the JavaBean to hold a single worker record. When a
user wants to edit an existing record or append a new one, it is used as a container to hold
the changed or new values for a single row of a table to prepare the row for using to
update the database. The bean contains properties for each field in a worker record, and
then JDeveloper creates the get and set methods (accessors) for each of those properties.

Creating a JavaBean in JDeveloper

Solution:

1. In the Application Navigator window, right-click the view project, then from the
short-cut menu, select New.
2. In the New Gallery dialog box, select Java under the General category (which in
turn under the selection of Categories:). Now, at the selection of Items:, select
Java. Finally, click the OK button.
3. In the Create Bean dialog box, enter MyWorkers as the name, sps as the
package, and ensure that the Extends: field is set to java.lang.Object. At the
Extends field, click the Browse button, then select the java list, then select the
lang item, then finally select the Object item. Finally, click the OK button to
create the bean.
4. Let us now save the MyWorkers.java file. It should contain the following code:

package sps;

public class MyWorkers {


public MyWorkers() {
}
}
466

5. Let us add a field to the MyWorkers class for each of the columns in the
MyWorkers table. Each field should be declared as private, and the field types are
as follows:

private Integer empNo;


private String lastName;
private String firstName;
private Double salary;
private String posCode;

6. Right-click on the Source Editor page and select Generate Accessors from the
shortcut menu. In the Generate Accessors dialog box, select the top-level
MyWorkers node by clicking the check box. You will notice that a check mark is
displayed for that node and for all the fields under it. Finally, click the OK button.

We can see below the Generate Accessors dialog box with all the fields selected:

7. Let us now save the file. The MyWorkers.java file should now contain the
following code:

package sps;
467

public class MyWorkers {


public MyWorkers() {
}
private Integer empNo;
private String lastName;
private String firstName;
private Double salary;
private String posCode;
public void setEmpNo(Integer empNo) {
this.empNo = empNo;
}
public Integer getEmpNo() {
return empNo;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Double getSalary() {
return salary;
}
public void setPosCode(String posCode) {
this.posCode = posCode;
}
public String getPosCode() {
return posCode;
}
}

This time, we need to know the tasks in updating data from a Java class. Here are the
tasks now.

Updating Data from Java Class

Updating a row in a database table from a Java EE application requires us to do the


following tasks:

1. Let us create a method that finds a particular worker row. This is used to display
the values for a particular worker on a change web page.
2. Let us create a method that takes the updated worker data from the bean and
updates the database.
468

3. On the main Java EE application page, in every row of worker data, let us include
a link that allows the user to change the data for that worker. The links take the
user to the change.jsp file with the data for that worker displayed, ready for
changing.
4. Let us create a JSP web page called change.jsp, that includes a form and a table
to display all the data of a single worker and allows a user to change the values.
5. Let us create a JSP web page that processes the Form on the change.jsp web
page, writes the updated values to the MyWorkers.java bean and calls the
updateMyWorkers method.

This time, we have to accomplish each task, one by one.

Creating a Method to Identify a Worker Record

The method we create in these steps is used to find the record for a particular worker. It is
used when a user wants to change or erase a particular worker record, and selects a link
for that worker on the MyWorkers.java web page.

Solution:

1. Open the DataHandling.java class in the Source Editor.


2. In the DataHandling class, let us declare a new method that identifies the worker
record to be updated:

public MyWorkers findMyWorkersById(int empno) throws SQLException {


MyWorkers selectedWorker = new MyWorkers();
getDBConnection();
stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
query = "SELECT * FROM MyWorkers WHERE EmpNo = " + empno;
System.out.println("\n Executing: " + query);
rset = stmt.executeQuery(query);
while (rset.next()) {
selectedWorker.setEmpNo(new Integer(rset.getInt("EmpNo")));
selectedWorker.setLastName(rset.getString("LastName"));
selectedWorker.setFirstName(rset.getString("FirstName"));
selectedWorker.setSalary(new Double(rset.getDouble("Salary")));
selectedWorker.setPosCode(rset.getString("PosCode"));
}
return selectedWorker;
}

We named our new method as findMyWorkersById( int empno).


469

Explanation:

The method we created above is used to find the record for a particular worker. It is used
when a user wants to change (edit) or erase a particular worker record, and selects a link
for that worker on the MyWorkers.java web page.
Within the body of the method, we created a new instance of the MyWorkers bean called
selectedWorker:


MyWorkers selectedWorker = new MyWorkers( );


Then, we connect to the database:


getDBConnection( );

....
We created a Statement object, then we defined a ResultSet type, and formulate the
query. We also add a trace message to assist with our debugging endeavor (using the
System.out.println statement):


stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
query = "SELECT * FROM MyWorkers WHERE EmpNo = " + empno;
System.out.println("\n Executing: " + query);


We run the query and use a ResultSet object to contain the result:


rset = stmt.executeQuery(query);


We use the result set returned in rset to populate the fields of the worker bean using the
set methods of the bean.


while (rset.next( )) {
selectedWorker.setEmpNo(new Integer(rset.getInt("EmpNo")));
selectedWorker.setLastName(rset.getString("LastName"));
selectedWorker.setFirstName(rset.getString("FirstName"));
selectedWorker.setSalary(new Double(rset.getDouble("Salary")));
selectedWorker.setPosCode(rset.getString("PosCode"));
}
470



Finally, we returned the populated object:


return selectedWorker;


This is the end of our discussion for findMyWorkersById( int empno) method.

Creating a Method to Update Worker Data

Solution:

1. In the DataHandling class, let us declare a new method that updates the worker
record:
public String updateMyWorkers(int empno, String lastname,
String firstname, String poscode,
String salary) throws SQLException {

MyWorkers oldWorker = findMyWorkersById(empno);


getDBConnection( );
stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
StringBuffer columns = new StringBuffer(255);
if (lastname != null &&
!lastname.equals(oldWorker.getLastName( ))) {
if ( columns.length() > 0 ) {
columns.append( ", " );
}
columns.append( "LastName = '" + lastname + "'" );
}

if (firstname != null &&


!firstname.equals(oldWorker.getFirstName( )))
{
columns.append( "FirstName = '" + firstname + "'" );
}

if ( poscode != null &&


!poscode.equals(oldWorker.getPosCode( ) ) ) {
if ( columns.length()>0) {
columns.append( ", " );
}
columns.append( "PosCode = '" + poscode + " ' " );
}

if ( salary != null &&


!salary.equals(oldWorker.getSalary().toString( ))) {
471

if (columns.length()>0) {
columns.append( ", " );
}
columns.append( "Salary = '"+salary+"'" );
}

if (columns.length()>0)
{
sqlString = "update MyWorkers SET " + columns.toString() +
"WHERE empno=" + empno;
System.out.println("\nExecuting: " + sqlString);
stmt.execute(sqlString);
}
else
{
System.out.println( "Nothing to do to update Worker Id: "+ empno);
}
return "success";
}

2. Save our DataHandling.java class.

Explanation:

We declared our an updateMyWorkers method as follows:




public String updateMyWorkers(int empno, String lastname,
String firstname, String poscode,
String salary) throws SQLException {


Within the body of this method, we created an instance of the MyWorkers bean,
containing details for the selected worker:


MyWorkers oldWorker = findMyWorkersById(empno);


We connected to the database:


getDBConnection( );


We created a Statement object and specify the ResultSet type:
….
….
stmt =
472

conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
….
….
This time, we created a StringBuffer to accumulate details of the SQL UPDATE statement
that needs to be built:


StringBuffer columns = new StringBuffer(255);


For each field in a worker record, we check whether the user has changed the value and if
so, we add relevant code to the StringBuffer. For each item added after the first one, we
add a comma to separate the items.
For the LastName, before appending the new last name, we check to see whether there
are already some changes in the StringBuffer and if so, append a comma to separate the
new change from the previous one. We use the following code:


if (lastname != null &&
!lastname.equals(oldWorker.getLastName( ))) {
if ( columns.length() > 0 ) {
columns.append( ", " );
}
columns.append( "LastName = '" + lastname + "'" );
}


The following code checks if the FirstName variable changed, and if so, we add details to
the SQL in the StringBuffer that will be used to update the database:


if (firstname != null &&
!firstname.equals(oldWorker.getFirstName( ))) {
columns.append( "FirstName = '" + firstname + "'" );
}


You could notice that we use the same code logic to check for changes made to PosCode:
columns:


if ( poscode != null &&
!poscode.equals(oldWorker.getPosCode( ) ) ) {
if ( columns.length()>0) {
columns.append( ", " );
473

}
columns.append( "PosCode = '" + poscode + " ' " );
}

For the Salary field, we obtain a String value to add to the StringBuffer as follows:


if ( salary != null &&
!salary.equals(oldWorker.getSalary().toString( ))) {
if (columns.length()>0) {
columns.append( ", " );
}
columns.append( "Salary = '"+salary+"'" );
}


When the whole set of changes has been assembled, we check to see whether there are in
fact any changes, that is, whether the StringBuffer contains anything. If so, we construct
an SQL UPDATE statement using the information in the StringBuffer and execute it. If
the StringBuffer does not contain any changes, we output a message saying so:


if (columns.length( )>0)
{
sqlString = "update MyWorkers SET " + columns.toString( ) +
"WHERE empno=" + empno;
System.out.println("\nExecuting: " + sqlString);
stmt.execute(sqlString);
}
else
{
System.out.println( "Nothing to do to update Worker Id: "+ empno);
}


Lastly, we returned the word, “success”.


return "success";


474

Adding a Link to Navigate to an Update Webpage

Figure 10.3 List of MyWorkers Page

Last Name First Name Position Code Salary

Change
Silang Gabriela MESSE 8,000 Erase

Cruise Juan SUPE 20,000 Change


Erase

Bonifacio Andres CLE 9,000 Change


Erase

Rizal Jose PRES 99,000 Change


Erase

Purisa Gavino GARDE 5,000 Change


Erase

Silang Diego CLE 9,000 Change


Erase

Solution:

1. Let us open myworkers.jsp in the Visual Editor, then select the Source tab.
2. This time, we have to add an extra column to the table that displays worker
details. To accomplish this task, add the following script (in bold only):
<tr>
<td width="130">
<h4>
LAST NAME
</h4></td>
<td width="131">
<h4>
FIRST NAME
</h4></td>
<td width="131">
<h4>
POSITION CODE
</h4></td>
<td width="83">
<h4>
SALARY
</h4></td>
<td width="57">
<h4>
475

</h4></td>
</tr>


3. Let us modify the scriptlet to include a link to the change.jsp and erasing.jsp
web pages. The modified scriptlet should contain the following code (in bold
only):


<% while(rset.next()){
out.println("<tr>");
out.println("<td>"+
rset.getString("LastName")+"</td><td>"+
rset.getString("FirstName")+"</td><td>"+
rset.getString("PosCode")+"</td><td>"+
rset.getString("Salary")+
"</td><td> <a href=\"change.jsp?empno=" + rset.getInt(1) +
"\">Change</a> <a href=\"erasing.jsp?empno=" +
rset.getInt(1) + "\">Erase</a></td>");
out.println("</tr>");
} %>


When the change link is clicked for any worker, this code passes the worker ID (empno)
to the change.jsp web page, which will handle the worker record updates. The
change.jsp web page will use this to search for the record of that particular worker in the
database.

4. Now, run the myworkers.jsp to test it on the actual basis.

The figure below shows our myworkers.jsp:


476

Creating a JSP Web Page to Change Worker Data

Solution:

1. In the Application Navigator window, right-click the view project, then from the
short-cut menu, select New.
2. In the New Gallery dialog box, select JSP under the Web Tier category (which
in turn under the selection of Categories:). Now, at the selection of Items:, select
JSP . Finally, click the OK button.

This will display the Create JSP dialog box.

3. Enter change.jsp as the file name at the File Name text-field . Finally, click
the OK button.

You will notice here that you are brought into the new blank web page within the
JSP/HTML Visual Editor for you to design and develop your web page.

4. Now at the top line of our web page, let us type the heading MyCompany
Inc.: Simple Personnel System. From the list of styles at the top of
the web page (in the Selection Box), select Heading 2, to format our header.
477

5. With the cursor still on the heading we added, from the Design menu (of
JDeveloper), select Align menu-item, then select the Center menu-item.
6. In a similar way, on a new line, type Change Worker Record and format it
with the Heading 3 style. Let us position this heading on the left-hand side of the
web page by clicking the Design menu (of JDeveloper), then select the Align
menu-item, and finally, select the Left menu-item.
7. This time, let us choose a Cascading Style-Sheets (CSS) for our web page. Click
the down- arrow at the top right of the Component Palette, then select CSS.
8. From the CSS list, drag JDeveloper item onto our web page, then click the Save
button, to accept the default File name: jdeveloper.css.
9. Drag a UseBean tag onto the web page. Enter worksbean as the ID and
browse to select sps.DataHandling as the Class. Set the Scope to session, then
click the OK button.
10. Let us position the cursor after the UseBean tag and add another jsp:usebean tag.
This time let us enter myworkers as the ID, browse to select sps.MyWorkers
as the Class, and leave the Scope as page. Finally, click the OK button.
11. Let us add a Scriptlet to the web page. Enter the following code in the Insert
Scriptlet dialog box:

Integer EmpNo = new Integer(request.getParameter("empno"));


myworkers=worksbean.findMyWorkersById(EmpNo.intValue());

This scriptlet code passes the worker ID to the findMyWorkersById method and retrieves
the data inside the MyWorkers bean.

12. Finally, click the OK button.


13. At the Component Palette, select HTML, then drag and drop a Form into the web
page. In the Insert Form dialog box, enter changing.jsp for the Action field.
Finally, click the OK button.

Note:
We cannot select this web page from the drop down list, because we have not yet created it.

14. This time, let us add a Table to the web page. Let us position it inside the Form.
Specify a 4-row and 2-column layout, and accept other default values for our
layout. Lastly, click the OK button.
15. In the first column of our table, let us enter the following headings, each on a
separate row, Last Name:, First Name:, Position Code:, Salary:.
16. Drag a Hidden Field component from the HTML Forms web page of the
Component Palette, then drop it into the second column, adjacent to the Last
Name heading. In the Insert Hidden Field dialog box, enter empno as the Name
property and enter <%=myworkers.getMyWorkersId()%> as the Value
property. Finally, click the OK button.
17. Drag a Text Field component to this column, adjacent to the Last Name heading.
In the Insert Text Field dialog box, enter LastName in the Name field, and
478

<%=myworkers.getLastName()%> in the Value field. Finally, click the


OK button.
18. Drag a Text Field component to this column, adjacent to the First Name heading.
In the Insert Text Field dialog box, enter FirstName in the Name field, and
<%=myworkers.getFirstName()%> in the Value field. Finally, click the
OK button.
19. Drag a Text Field component to this column, adjacent to the Position Code
heading. In the Insert Text Field dialog box, enter PosCode in the Name field,
and <%=myworkers.getPosCode()%> in the Value field. Finally, click the
OK button.
20. Drag a Text Field component to this column, adjacent to the Salary heading. In
the Insert Text Field dialog box, enter Salary in the Name field, and
<%=myworkers.getSalary()%> in the Value field. Finally, click the OK
button.
21. This time, we will add a Submit button in the Form, below the Table. Enter
Change Now! as its Value.
22. Let us save our Java EE application now.

Our change.jsp web page design should look like the following:

Creating a JSP Web Page to Handle a Change Action

Solution:

1. In the Application Navigator window, right-click the view project, then from the
short-cut menu, select New.
479

2. In the New Gallery dialog box, select JSP under the Web Tier category (which
in turn under the selection of Categories:). Now, at the selection of Items:, select
JSP ). Finally, click the OK button.

This will display the Create JSP dialog box.

3. Enter changing.jsp as the file name at the File Name text-field . Finally,
click the OK button.

You will notice here that you are brought into the new blank web page within the
JSP/HTML Visual Editor for you to design and develop your web page.

4. From the JSP page of the Component Palette, let us drag a Page Directive
component to the web page. In the Insert Page Directive dialog box, for the
Import field, browse to import java.sql.ResultSet. Just accept all other default
values. Finally, click the OK button.

Note:
To accomplish the above task, just simply select the Search tab, then click the java item of the Class and
Package Browser, then next select the sql item. Select the ResultSet item (under the sql item). Finally,
click the OK button. Got it?

5. Drag a UseBean tag onto the web page. Enter worksbean as the ID and
browse to select sps.DataHandling as the Class. Set the Scope to session, then
click the OK button.

6. This time, let us add a Scriptlet to the web page. We have to enter the following
code into the Insert Scriptlet dialog box:

Integer EmpNo = new Integer(request.getParameter("empno"));


String LastName = request.getParameter("LastName");
String FirstName = request.getParameter("FirstName");
String PosCode = request.getParameter("PosCode");
String Salary = request.getParameter("Salary");
worksbean.updateMyWorkers(EmpNo.intValue(),LastName,
FirstName,PosCode,Salary);

7. We have to drag a Forward (jsp:forward) tag onto the web page. In the Insert
Forward dialog box, enter myworkers.jsp for the Page property. Finally, click
the OK button.
8. Let us save now our work.
9. Now, let us run the project to test whether we can change or edit a worker record.
Click the Change link for any worker on the myworkers.jsp web page.

Let us try to modify any of the worker details and check whether the change reflects in
the myworkers.jsp web page. Try it now! For example, the figure below contains the
original record of Juan Cruise.
480

We will edit the last name Cruise, and change it to Cruz.


481

When we click the Change Now! button, here is now the result below:

See? We are successful in editing Juan’s record!

Note:
This web page processes the Form on the change.jsp web page that allows users to edit or update a worker
record. We have to remember that there are no visual elements on this web page, because it is only used to
process the change.jsp Form and returns control to the myworkers.jsp file.

Updating Data from Java Class

Adding a new worker record to the MyWorkers table is similar to the process of updating
(editing) a worker record. It requires us to accomplish the following task:

1. First, we create a method to add a new worker row into the MyWorkers table.
2. Then, we add a link to the main Java EE application web page, allowing a user to
click to insert a new worker. The link takes the user to adding.jsp web page with
an empty Form ready for the user to input details for the new row.
482

3. This time, we create a JSP web page to process the Form on the add.jsp web
page.
4. Finally, we create another JSP web page with Form controls for users to input the
values for the new worker.

Creating a Method to Add Data

Solution:

1. In the DataHandling class, let us declare a new method that adds a new worker
record:
public String addMyWorkers(String lastname, String firstname,
String poscode, int salary) throws SQLException {
getDBConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
sqlString = "INSERT INTO MyWorkers
VALUES(MyWorker_Sequence.NEXTVAL,'"
+lastname + "','" + firstname + "','" + poscode + "'," +
salary+")";
System.out.println("\nAdding: " + sqlString);
stmt.execute(sqlString);
return "success";
}

2. Let us re-compile our DataHandling.java file to check if there are no syntax


errors.

Adding a Link to Navigate to an Add Web Page


Figure 10.3 List of MyWorkers Page
483

Last Name First Name Position Code Salary Add


Worker

Change
Silang Gabriela MESSE 8,000 Erase

Cruise Juan SUPE 20,000 Change


Erase

Bonifacio Andres CLE 9,000 Change


Erase

Rizal Jose PRES 99,000 Change


Erase

Purisa Gavino GARDE 5,000 Change


Erase

Silang Diego CLE 9,000 Change


Erase

Solution:

1. Let us open the myworkers.jsp in the Visual Editor.


2. Then, we have to drag a HyperLink component from the HTML Common page
of the Component Palette into the empty column header cell at the end of the
header row. In the Insert HyperLink dialog box, let us enter Add Worker in the
Text field and add.jsp in the HyperLink field. Finally, click the OK button.
3. Finally, let us save the myworkers.jsp.

Note:
We cannot browse to find add.jsp, because we have not yet created it.

After revising our myworkers.jsp web page design, it should look like the following
figure below:
484

Explanation:

In our task above, we simply add a link to the header row of the myworkers.jsp web page
so that the user can click it to add a new worker data which in turn will be recorded into
the MyWorkers table.

Creating a JSP Web Page to Input New Data

Figure 10.4a* Adding Worker Record Page

MyCompany Inc. : Simple Personnel System

Add Worker Record

Last Name: Silang

Diego
First Name:

Job Title Janitor

Salary 4,000

Add Now!

Button Text Fields

Note:
485

*Revised figure based on Figure 10.4.

Solution:

1. In the Application Navigator window, right-click the view project, then from the
short-cut menu, select New.
2. In the New Gallery dialog box, select JSP under the Web Tier category (which
in turn under the selection of Categories:). Now, at the selection of Items:, select
JSP. Finally, click the OK button.

This will display the Create JSP dialog box.

3. Enter add.jsp as the file name at the File Name text-field . Finally, click the
OK button.

You will notice here that you are brought into the new blank web page within the
JSP/HTML Visual Editor for you to design and develop your web page.

1. Now at the top line of our web page, let us type the heading MyCompany
Inc.: Simple Personnel System. From the list of styles at the top of
the web page (in the Selection Box), select Heading 2, to format our header.
2. With the cursor still on the heading we added, from the Design menu (of
JDeveloper), select Align menu-item, then select the Center menu-item.
3. In a similar way, on a new line, type Add Worker Record and format it with
the Heading 3 style. Let us position this heading on the left-hand side of the web
page by clicking the Design menu (of JDeveloper), then select the Align menu-
item, and finally, select the Left menu-item.
4. This time, let us choose a Cascading Style-Sheets (CSS) for our web page. Click
the down- arrow at the top right of the Component Palette, then select CSS.
5. From the CSS list, drag JDeveloper item onto our webpage, then click the Save
button, to accept the default File name: jdeveloper.css.
6. At the Component Palette, select HTML, then drag and drop a Form into the web
page. In the Insert Form dialog box, enter adding.jsp for the Action field.
Finally, click the OK button.
7. This time, let us add a Table to the web page from the Component Palette (under
the HTML page and Control selection). Let us position it inside the Form.
Specify a 4-row and 2-column layout, and accept other default values for our
layout. Lastly, click the OK button.
8. In the first column of our table, let us enter the following headings, each on a
separate row, Last Name:, First Name:, Position Code:, Salary:.
9. Let us drag and drop a Text Field into the column to the right of the Last Name:
header. In the Insert Field dialog box, type LastName in the Name property.
Then, click the OK button.
486

Note:
The Text Field component is under the HTML page and Forms selection of the Component Palette.

10. Let us drag and drop a Text Field into the column to the right of the First Name:
header.. In the Insert Field dialog box, type FirstName in the Name property.
Then, click the OK button.

11. Let us drag and drop a Text Field into the column to the right of the Salary:
header. In the Insert Field dialog box, type Salary in the Name property. Then,
click the OK button.

In the Position Code, we have to drag and drop a different component.

12. Let us drag and drop a Combo Box component from the HTML Forms page of
the Component Palette to the column next to the Position Code:.
13. In the Insert Select dialog box, let us enter PosCode as the name, and 1 as the
size. Then, click the big GREEN plus symbol to add the Value and Caption data.
Click in the Value field and enter MESSE, and in the Caption field, enter
Messenger. Repeat the procedure for each of the following position codes.
After entering all the Value and Caption data, click the OK button.

Value Caption
================
SUPE Supervisor
CLE Clerk
PRES President
GARDE Gardener

14. This time, we will add a Submit button in the Form, but below the Table. Enter
Add Now! for the Value property. Finally, click the OK button.
15. Let us save our Java EE application now.

Our add.jsp web page design should look like the following figure:
487

Explanation:

The tasks above created the add.jsp web page, which allows users to enter details of a
new worker record.

Creating a JSP Web Page to Handle an Add Action

Solution:

1. In the Application Navigator window, right-click the view project, then from the
short-cut menu, select New.
2. In the New Gallery dialog box, select JSP under the Web Tier category (which
in turn under the selection of Categories:). Now, at the selection of Items:, select
JSP . Finally, click the OK button.

This will display the Create JSP dialog box.

3. Enter adding.jsp as the file name at the File Name text-field . Finally, click
the OK button.

You will notice here that you are brought into the new blank web page within the
JSP/HTML Visual Editor for you to design and develop your web page.

4. Drag a UseBean tag onto the web page. Enter worksbean as the ID and
browse to select sps.DataHandling as the Class. Set the Scope to session, then
click the OK button.
5. Let us position the cursor after the useBean tag and add a Scriptlet to the web
page. We have to enter the following code into the Insert Scriptlet dialog box:

String LastName=request.getParameter("LastName");
String FirstName=request.getParameter("FirstName");
String PosCode=request.getParameter("PosCode");
Integer Salary=new Integer(request.getParameter("Salary"));
worksbean.addMyWorkers(LastName,FirstName,PosCode,Salary.intValue())
;

6. After entering the code in our Scriptlet, click the OK button.


7. We have to drag a Forward (jsp:forward) tag onto the web page. In the Insert
Forward dialog box, enter myworkers.jsp for the Page property. Finally, click
the OK button.
8. Let us save now our work.
9. Now, let us run our view project to test whether we can really add a worker
record. We have to click the Add Worker link on the myworkers.jsp web page
to test it.
488

Explanation:

The tasks above created the adding.jsp web page. This is the web page that processes the
Form input from add.jsp, which is the web page on which users enter a new worker
record. Like any other action-oriented web page, there are no visual elements on this web
page, because it is only used to process the add.jsp Form and finally return control to the
mywokers.jsp.

After clicking the Add Worker link, we will be brought to the blank Add Worker Form
input, as you can see it in our figure below:
489

For example, we will input the following details for our new worker:

Once we click the Add Now! button, we will be brought to the myworkers.jsp web page
where we can see the new worker data added on the list of worker:
490

See? What a magnificent Java EE application! Isn’t it?

Erasing a Worker Record

Figure 10.3 List of MyWorkers Page

Last Name First Name Position Code Salary Add


Worker

Change
Silang Gabriela MESSE 8,000 Erase

Cruise Juan SUPE 20,000 Change


Erase

Bonifacio Andres CLE 9,000 Change


Erase

Rizal Jose PRES 99,000 Change


Erase

Purisa Gavino GARDE 5,000 Change


Erase

Silang Diego CLE 9,000 Change


Erase
491

Erasing a new worker record to the MyWorkers table is similar to the process of changing
and adding a worker record. It requires us to accomplish the following task:

1. First, we use the method created in Creating a Method to Identify a Worker


Record to identify a particular worker row. This is used to identify the row to be
erased.
2. Then, we create a method that erases a worker record from the database table.
3. Next, we add a link to the main application web page for each row, allowing a
user to click that Erase link to erase a worker in that particular row.
4. To erase a worker from the database table, we have to create a JSP web page to
call the erase method: erasing.jsp.

Creating a Method for Erasing Data

Solution:

1. In the DataHandling class, let us declare a new method that identifies a worker
record to be erased:
public String eraseMyWorkersById(int id) throws SQLException {
try {
getDBConnection();
stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
sqlString = "DELETE FROM MyWorkers WHERE empno = " + id;
System.out.println("\nExecuting Erase Method: " + sqlString);
stmt.execute(sqlString);
}
catch (SQLException ex) {
logException( ex );
return "failure";
}
return "success";
}

public void logException( SQLException ex )


{
while ( ex != null ) {
ex.printStackTrace();
ex = ex.getNextException();
}
}

2. Let us re-compile our DataHandling.java file to check if there are no syntax


errors.
492

Explanation:

We could observe that the tasks above created a method that is used to erase a worker
record by ID (when the ID is equivalent to empno). This further means, that our Java EE
application system used only the ID as its identifier to identify what particular worker
record to erase.

Creating a JSP Web Page to Handle an Erase Action

Solution:

1. In the Application Navigator window, right-click the view project, then from the
short-cut menu, select New.
2. In the New Gallery dialog box, select JSP under the Web Tier category (which
in turn under the selection of Categories:). Now, at the selection of Items:, select
JSP. Finally, click the OK button.

This will display the Create JSP dialog box.

3. Enter erasing.jsp as the file name at the File Name text-field . Finally, click
the OK button.

You will notice here that you are brought into the new blank web page within the
JSP/HTML Visual Editor for you to design and develop your web page.

4. Drag a UseBean tag onto the web page. Enter worksbean as the ID and
browse to select sps.DataHandling as the Class. Set the Scope to session, then
click the OK button.
5. Let us position the cursor after the useBean tag and add a Scriptlet to the web
page. We have to enter the following code into the Insert Scriptlet dialog box:

Integer EmpNo = new Integer(request.getParameter("empno"));


worksbean.eraseMyWorkersById(EmpNo.intValue());

6. After entering the code in our Scriptlet, click the OK button.


7. We have to drag a Forward (jsp:forward) tag onto the web page. In the Insert
Forward dialog box, enter myworkers.jsp for the Page property. Finally, click
the OK button.
8. Let us save now our work.
9. Now, let us run our view project to test whether we can really erase a worker
record. We have to click the Erase link on the myworkers.jsp web page to test it.
493

Explanation:

The tasks above created the erasing.jsp web page, which is a web page that only
processes the erase operation. Like any other action-oriented web page, there are no
visual elements on this web page, because it is only used to process the erase link form
and finally return control to the mywokers.jsp.

To test, whether we can really erase a particular worker record by clicking the Erase link,
we have to re-append the Mister Dummy record into our MyWorkers table. Now, let us
click first the Add Worker link.

Since we are brought into the blank Add Worker Form input, we have to input now the
data: Mister Dummy with a salary of 12345 and Messenger as his Position Code.
494

You can see in the figure below the data that we entered:

Once we click the Add Now! button, we will be brought to the myworkers.jsp web page
where we can see the new worker data added on the list of worker:
495

This time, let us click the Erase link within the row of Mister Dummy, to test if we can
really erase this particular worker record. Do it now!

Wow! The record of Mister Dummy was gone! So, our Erase method really works as we
expected it to be.
496

Exception Handling Explained

An SQLException object instance provides an error information during database access


or other application system related errors. Each SQLException instance provides many
types of error information, including a string describing the error, which is used as the
Java Exception message. This is available through the getMessage method.
Our Java EE application uses try and catch blocks, which are the Java mechanism for
handling exceptions. With Java, if a method throws an exception, there should be a
mechanism to handle it.
The role of the catch block is to catch the exception and specifies the course of action in
the event of an exception. One of the courses of action is to simply display the error
message.
We have to remember that each JDBC method throws an SQLException if a database
access error happens. This is the main reason why any method in a Java EE application
that executes such a method must handle the exception.
You could also notice that all the methods in our Java EE application include code for
handling exceptions. Like for example, in the authenticateUser method under the
DataHandling.java class, a try block contains the code for the work to be done to
authenticate a user, and a catch block handles the case where the authentication fails.

Creating a Method for Handling Any SQLException


We can refine our code in the DataHandling.java class, by including a logException( )
method that can be used in any method that might throw an SQLException, to handle the
exception. The following method could be called in the catch block of any of the methods
under the DataHandling.java class:

public void logException( SQLException ex )


{
while ( ex != null ) {
ex.printStackTrace();
ex = ex.getNextException();
}
}

In the catch block, we can return a text message that explains why the method has failed.
The catch block of a method could be written like the following code:

catch (SQLException ex) {


logException( ex );
return "failure";
}

To include this try and catch blocks to our Java EE application, we have to accomplish
the following tasks:

1. In our DataHandling.java class, we have to add this logException( ) method.


497

2. Let us edit each of the methods in our DataHandling.java class, then we have to
include the try and catch blocks statements within them.
3. In the catch block of each method in the DataHandling.java class, run the
logException( ) method.
4. For any methods that have a return value of String, let us include a return
statement to return a message indicating that the method has failed such as simple
as the following statement:

return "failure";

This time, SQLException handling is probably clearer to you. I hope so, buddy.

Navigation in Java EE Application

If we click the WEB-INF folder in our Application Navigator of the JDeveloper IDE,
we can see the web.xml file. This is the deployment descriptor file for a web application.
One section of the web.xml file can be used for defining a start web page for our Java EE
application. An example script can be similar to the following:
….
….
<web-app>
……
……
<welcome-page>
MyWelcomePage.jsp
</welcome-page>
</web-app>
………
………

If we do not define a welcome web page in our web.xml file, generally a file with the
name index.htm (html or jsp extension name) if there is one, is used as the starting web
page. With JDeveloper, we can define which web page is to be the default run target for
our Java EE application. Meaning, the web page of the Java EE application that is
displayed first, by defining it in the properties of the project.
Once the Java EE application has started, and the start web page has been displayed,
navigation through the application is achieved using the following scheme:

• Links, in the form of HTML anchor tags, define a target for the link, usually
identifying another JSP web page to which to navigate.
• The HMTL Submit buttons are used to submit Forms on the web pages, like for
example a Form used for entering an edited data or a new data.
• Forward tags (jsp:forward tags), which are executed on JSP web pages that
handle queries and forms, to forward to either the same JSP web page again, or
another JSP web page.
498

Creating a Starting Web Page for Java EE Application

Solution:

1. In the Application Navigator window, right-click the view project, then from the
short-cut menu, select New.
2. In the New Gallery dialog box, select JSP under the Web Tier category (which
in turn under the selection of Categories:). Now, at the selection of Items:, select
JSP . Finally, click the OK button.

This will display the Create JSP dialog box.

3. Enter index.jsp as the file name at the File Name text-field . Finally, click
the OK button.
4. For our Java EE application, we will not add any text to this index.jsp web page.
We have to drag a Forward (jsp:forward) tag onto the web page. In the Insert
Forward dialog box, enter login.jsp for the Page property. Finally, click the OK
button.

We can now specify this new web page as the default target for our Java EE application
with the following tasks:

1. In the Application Navigator window, right-click the view project, then choose
Project Properties.
2. In the displayed tree menu, select Run/Debug/Profile. In the Run/Debug/Profile
area, let us ensure that Use Project Settings is selected, and in the Run
Configurations area, let us ensure that Default is presented. Click the Edit button.
3. Finally, in the Launch Settings dialog box, select Launch Settings. At the same
time, in the Launch Settings area on the right, click Browse next to the Default
Run Target field and navigate to find the new index.jsp web page we just created.
Next, click the Open button. This time, click the OK button to close the dialog
box. Click again this another OK button to close the Run/Debug/Profile dialog
box.

We can now run our Java EE application by right-clicking our view project and select
Run from the shortcut menu. This time, our Java EE application runs and runs index.jsp,
which has been set as the default launch target.

You can see in our URL web site below that the index.jsp is the web page where we can
navigate our Java EE application.
499

Explanation:

In the above tasks, we created the index.jsp web page, which is the default starting web
page for our Java EE application. The web page does not include any display elements,
and simply forwards the user to the application login web page, login.jsp. To accomplish
this task, we use the jsp:forward tag. A jsp:forward tag runs on JSP web pages that
handle queries and Forms, to forward to either the same JSP web page, or another JSP
web page.
500

Chapter 13
Advanced JDBC Features

We can see here in the figure below, how we can apply the advanced features of Java
Database Connectivity (JDBC) when we want to add a worker record in our database
table. This is by selecting if we can use JDBC only or using instead an Oracle Stored-
Procedure in adding a new record.

Figure 10.4 Adding Worker Record Page

MyCompany Inc. : Simple Personnel System

Add Worker Record

Use JDBC only to add a new record

Use Stored-Procedure via JDBC to add new record

Silang
Last Name:

First Name: Diego

Job Title Janitor

4,000
Salary

Add Now!

Button Text Fields

Applying Dynamic SQL

The dynamic SQL means generating SQL statements on the fly. In an actual
programming practice, this is usually needed. Most often, especially during updates of a
database table, the final query is not known until run time.
We can apply OraclePreparedStatement object (which extends the Statement object),
for scenarios where many similar queries with differing update values must be run on the
database. This can be accomplished by substituting the literal update values with bind
501

variables. The other way also is to apply stored PL/SQL functions on the database by
calling stored procedures through the OracleCallableStatement object.

Note:
JDBC stands for Java Database Connectivity

OraclePrepared Statement Explained

We apply the Statement object in order to run static SQL queries by hard-coding them.
But when it comes to performing multiple updates or running multiple similar queries
that affect many columns in the database table, it is not feasible to hard-code each query
in our Java EE application.
We can use OraclePreparedStatement when we run the same SQL statement multiple
times. For example, let us consider a query like the following:

select * from MyWorkers where ID=abc

Where:
ID could be the EmpNo (Employee Number)
abc could be any EmpNo such as 1020 or 1021 or etc.

Every time the value of abc in this query changes, the SQL statement needs to be
compiled again.

If we apply the capability of OraclePreparedStatement, the SQL statement we want to


run is precompiled and stored in a PreparedStatement object, and we can run it as many
times as required without compiling it every time it is run. Now, what if the data in the
statement changes? Well, we can use bind variables as placeholders for the data and then
provide literal values at run time.
Let us now have our actual example of OraclePreparedStament application:

OraclePreparedStatement ops = conn.preparedStatement(“UPDATE MyWorkers


set Salary = ? WHERE ID = ? “);
ops.setInt(1,1000);
ops.setBigDecimal(2,123456.24);

Here are the advantages of applying OraclePreparedStatement:

• We can improve performance because the SQL statement that is run many times
is compiled only the first time it is run.
• We can batch updates by applying the same PreparedStatement object
• We can use bind variables to make the code reusable and simpler.
502

Now, how about the OracleCallableStatement? This is our next topic.

OracleCallableStatement Explained

By applying the OracleCallableStatement, we can access stored procedures on databases.


The OracleCallableStatement interface extends the OraclePreparedStatement interface.
This interface consists of standard JDBC escape syntax to call stored procedures. We
may use this with or without a result parameter. We have to remember that if we use a
result parameter, it must be registered as an OUT parameter. We can also use the IN
parameter or both IN and OUT parameter at the same time.
The IN and OUT parameters are set by using accessor methods inherited from the
OraclePreparedStatement interface. The IN parameters are set by using the setXXX
methods, while the OUT parameters are retrieved by using the getXXX methods. The
XXX refers to the Java data type of the parameter. A CallableStatement can also return
multiple ResultSet object.

In our example below, we can create an OracleCallableStatement to call the stored


procedure called Fool:

OracleCallableStatement ocs = (OracleCallStatement)


conn.prepareCall(“{call Fool( ? )”);

We can pass the string me to this procedure in one of the following ways:

ocs.setString(“myparameter”,”me”); // Oracle extension


// or…
ocs.setString(1,”me”); // JDBC standard

Bind Variables Explained

Using bind variables has remarkable performance advantages in an actual Java EE


application system in the company. But what are bind variables? Bind variables are
simply variable substitutes for literals in an SQL statement. The bind variables are
applied in conjunction with OraclePreparedStatement and OracleCallableStatement to
specify parameter values that are used to build the SQL statement.
When it comes to PL/SQL blocks or stored procedure calls, we can use the following
qualifiers to differentiate between input and output variables: IN, OUT, and IN OUT. The
input variable values are set by using setXXX methods and OUT variable values can be
retrieved by using getXXX methods, where XXX is the Java data type of the values. This
will depend on the SQL data types of the columns that we are accessing in the database
table.
503

Calling Stored Procedures Explained

The JDBC drivers support the processing of anonymous blocks as well as PL/SQL stored
procedures. They support most of SQL92 escape syntax and all of Oracle PL/SQL block
syntax.
We have here below our example on how to call stored procedures:

// The syntax for Oracle PL/SQL block

CallableStatement ocs1 = conn.prepareCall


( “begin proc (?,?); end;”); // stored proc

CallableStatement ocs2 = conn.prepareCall


(“begin ? := func(?,?); end;”); // stored func

// The syntax for SQL92

CallableStatement ocs3 = conn.prepareCall


(“{call proc(?,?)}”); // stored proc

CallableStatement ocs4 = conn.prepareCall


(“ { ? = call func(?,? ) } ” ); // stored func

Now, we have an example that uses the Oracle syntax. Here is a PL/SQL code snippet
that creates a stored function. In this example, the PL/SQL function gets a character
sequence and concatenates a foolme to it:

create or replace function Fool(val2 char)


return char as
begin
return val2 | | ‘foolme’;
end;

We can call this stored function in a Java EE application as follows:

OracleDataSource ods = new OracleDataSource( );


ods.setURL(“jdbc:oracle:thin:@<hoststring>”);
ods.setUser(“hr”);
ods.setPassword(“hr”);
Connection conn = ods.getConnection( );
CallableStatement ocs = conn.prepareCall (“begin ? := Fool(?); end;”);
ocs.registerOutParameter(1,Types.CHAR);
ocs.setString(2,”bb”);
ocs.executeUpdate( );
String result = ocs.getString(1);
504

This time, we will create a PL/SQL Stored Procedure in JDeveloper.

Creating a PL/SQL Stored Procedure in JDeveloper

Solution:

1. Let us click the View menu of the JDeveloper, then select the Database
Navigator menu item.
2. Next, let us expand the DBConnection2 database connection node.
3. Right-click Procedures, and select New Procedure in the shortcut menu.
4. In the Create PL/SQL Procedure dialog box, enter AddWorker in the Name
field. Finally, click the OK button.
You could notice that the skeleton code for the Procedure is displayed in the
Source Editor.
5. Now, edit the skeleton code and enter the following code:

create or replace
PROCEDURE "ADDWORKER" (p_LastName MyWorkers.LastName%Type,
p_FirstName MyWorkers.FirstName%Type,
p_PosCode MyWorkers.PosCode%Type,
p_Salary MyWorkers.Salary%Type
)
AS
BEGIN
INSERT INTO MyWorkers VALUES (MyWorker_Sequence.NEXTVAL,
p_LastName, p_FirstName, p_PosCode, p_Salary) ;
END "ADDWORKER";

6. Let us save the AddWorker Procedure file, and check whether there are any
compilation errors.

Explanation:

The JDeveloper IDE allows us to create stored procedures in the database through the
Connection Navigator. In the tasks above, we created a stored procedure that can be
used as an alternative way of adding (inserting) a worker record in our Java EE
application.
After the procedure name, we enter the following lines of code:
....

PROCEDURE "ADDWORKER" (p_LastName MyWorkers.LastName%Type,
p_FirstName MyWorkers.FirstName%Type,
p_PosCode MyWorkers.PosCode%Type,
p_Salary MyWorkers.Salary%Type
505

)
….
….
After the BEGIN statement, we replace the line that reads NULL with the following
script:

….
….
BEGIN
INSERT INTO MyWorkers VALUES (MyWorker_Sequence.NEXTVAL,
p_LastName, p_FirstName, p_PosCode, p_Salary) ;
….
….
Lastly, we add the procedure name in the END statement:
….
….
END "ADDWORKER";

This is the end of our discussion about creating a stored procedure in Oracle Database.
Next, we will learn how to create a method within our Java EE application that calls the
stored procedure from Oracle Database.

Creating a Method to Use the Stored Procedure

Solution:

1. Let us select the Applications tab to display the Application Navigator.


2. This time, we have to open the DataHandling.java class.
3. Import the CallableStatement interface as follows:

import java.sql.CallableStatement;

4. In the DataHandling class, let us declare a new method that uses the Stored
Procedure created from Oracle Database:

public String addMyWorkersSP(String LastName, String FirstName,


String PosCode,int Salary) throws SQLException {
try {
getDBConnection();
sqlString = "begin HR.ADDWORKER(?,?,?,?); end;";
CallableStatement ocs = conn.prepareCall(sqlString);
ocs.setString(1,LastName);
ocs.setString(2,FirstName);
ocs.setString(3,PosCode);
ocs.setInt(4,Salary);
System.out.println("\nAdding using Stored Procedure:
"+sqlString);
ocs.execute();
506

return "success";
}
catch (SQLException ex) {
System.out.println("Possible error: Make sure you
have created the stored procedure first!");
logException( ex );
return "failure";
}

5. Let us save the DataHandling.java class file, and check for possible compilation
errors.

Explanation:

In the tasks above, we add a method to the DataHandling.java class that can be used as
an alternative to the addMyWorkers method. The new method we added here makes use
of the AddWorker stored procedure which we had created from Oracle Database. We
named the new method as addMyWorkersSP( ).
We import the CallableStatement interface as follows:
….
import java.sql.CallableStatement;
….
….
because this is a requirement for calling a stored procedure.
You could notice that inside the try block, we connected to the database then we created
an SQL string:
….
….
getDBConnection( );
sqlString = "begin HR.ADDWORKER(?,?,?,?); end;";
….
….
The question marks (?) in the statement are bind variables, acting as placeholders for the
values of LastName, FirstName, PosCode, and Salary columns. The four question marks
correspond also with the four columns in our MyWorkers table. These columns are what
our stored procedure expected.
We created the CallableStatement and set the IN parameters:
.…
….
CallableStatement ocs = conn.prepareCall(sqlString);
ocs.setString(1,LastName);
ocs.setString(2,FirstName);
ocs.setString(3,PosCode);
ocs.setInt(4,Salary);
….
507

….
We added a trace message (for debugging purposes), and run the callable statement:
….
….
System.out.println("\nAdding using Stored Procedure: "+sqlString);
ocs.execute( );
return "success";
….
….
With a return message for a successful execution of all statements.
Lastly, we add a catch block to trap any errors by calling the LogException method:
….
….
catch (SQLException ex) {
System.out.println("Possible error: Make sure you have created
the stored procedure first!");
logException( ex );
return "failure";
}
….
….
This is the end of our discussion about the addMyWorkersSP( ) method.

Allowing Users to Choose the Stored Procedures

Solution:

1. Let us open the add.jsp web page in the Visual Editor.


2. Let us create a new line after the Add Worker Record heading. With the cursor on
this new line, drag UseBean from the JSP page of the Component Palette to add a
jsp:useBean tag to the web page. Enter worksbean as the ID and browse to
select sps.DataHandling as the Class. Set the Scope to session. then click the
OK button. With the UseBean still selected on the web page, set the style of this
line to None instead of Heading 3.
3. This time, let us drag a Radio Button component from the HTML Forms page of
the Component Palette onto the web page inside the Form above the table. In the
Insert Radio Button dialog box, enter useSP as the Name, false as the Value,
and put a check mark on the Checked box. Finally, click the OK button.
4. In the Visual Editor, position the cursor to the right of the button, and enter text to
describe the purpose of the button: “Use JDBC only to add a new record”.
5. Press the Enter key at the end of the current line to create a new line.
6. Let us drag another Radio Button component below the first one. In the Insert
Radio Button dialog box, enter useSP as the Name, and true as the Value. This
time, make it sure that the Checked box is not selected or simply empty of a
check mark. Finally, click the OK button.
508

7. In the Visual Editor, position the cursor to the right of the button, and enter text to
describe the purpose of the button: “Use Stored Procedure via JDBC to add a
new record”.
8. Lastly, let us save the add.jsp web page.

Explanation:

The tasks above add an option (radio) button group to the add.jsp web page, which
allows a user to choose between adding a worker record using the stored procedure, or by
using SQL query in Java code.

Calling the Stored Procedure from the Java EE Application

Solution:

1. Let us open the adding.jsp web page.


2. Then, we have to click the Source tab of the Source Editor and add a new variable
after the Salary variable with the following script:
String useSPFlag = request.getParameter("useSP");

3. Below the new variable declaration, replace the existing worksbean.AddWorkers


line with the following lines of code to select addMyWorkersSP method or the
pure JDBC addMyWorkers method in adding a new record:

if ( useSPFlag.equalsIgnoreCase("true"))
worksbean.addMyWorkersSP(LastName, FirstName,
PosCode, Salary.intValue());
// otherwise let us use pure JDBC Insert command
else
worksbean.addMyWorkers(LastName,FirstName,PosCode,Salary.intValue());

4. Lastly, let us save the adding.jsp web page.

We can now run our Java EE application and use the Radio buttons on the add web page
to choose how we want to add a new worker record.
For example, originally our figure below shows the original content of our MyWorkers
table.
509

Now, we have to click the Add Worker link so that we can test adding a worker unto our
table.
We have to choose first the Use JDBC only to add a new record.

We will input the following data:

Last Name: Dummy


First Name: Mister
PosCode: Messenger
Salary: 12345
510

When we click the Add Now! button, Mister Dummy should appear in the list of workers
in our MyWorkers web page. Can you see Mister Dummy now in our figure below?:

See? We were able to add a worker in our MyWorkers table which in turn appears also in
our myworkers.jsp web page. However, we applied the option: Use JDBC only to add a
new record.
511

How about the other option? The option: Use Stored Procedure via JDBC to add a new
record.
Let us see if we can successfully add a new record by using this other option. Want to
bet?

This time, we will input the following data:

Last Name: Dummy


First Name: Miss
PosCode: Messenger
Salary: 12345
512

When we click the Add Now! button, Miss Dummy should appear in the list of workers
in our myworkers.jsp web page. Can you see Miss Dummy now in our figure below?:

Again, we were able to successfully add another worker record in our MyWorkers
database table. This means that our Java EE application works well to our expectation. Is
it not nice to know?
513

Explanation:

The tasks above modified the adding.jsp web page, which processes the Form on the
add.jsp web page, to use the Radio button selection and select the appropriate method for
adding a new worker record.

Using Cursor Variables

A cursor variable holds the memory location of a query work area, rather than the
contents of the area. Sounds familiar to you, isn’t it? Because declaring a cursor variable
creates a pointer. Now, you know that you are right!
The Oracle JDBC drivers support cursor variables with the REF CURSOR types. Cursor
variable implementation is not part of the JDBC standard. The REF CURSOR types are
supported as result sets in JDBC.
In SQL application, a pointer has the data type REF x. REF is short for REFERENCE
and x represents the entity being referenced. A REF CURSOR, then, identifies a
reference to a cursor variable. Since many cursor variables exist to point to many work
areas, REF CURSOR can be thought of as a category or data type specifier that identifies
many different types of cursor variables. A REF CURSOR essentially encapsulates the
results of the query.
The Oracle Database does not return ResultSets. To access data returned by a query, we
use REF CURSORS and CURSORS. The CURSORS contain query results and metadata.
A CURSOR variable or REF CURSOR data type contains a reference to a cursor. It can
be passed between Oracle PL/SQL and Java EE application in the database, or passed
between the RDBMS and the client. Moreover, it can also be returned from a stored
procedure or from a query.

Note:
The instances of REF CURSOR are not scrollable.

Type Category of Oracle REF CURSOR

In order to create a cursor variable, we have to begin by identifying a type that belongs to
the REF CURSOR category. Like for example,
….
cv_Dept DeptCursorTyp
….
Then, we can create the cursor variable by declaring it to be of the type DeptCursorTyp
as you can see it in our example script below:
….
DECLARE TYPE DeptCursorTyp IS REF CURSOR
514

….
In this example, REF CURSOR, then, is a category of data types, rather than a particular
data type. The Stored Procedures can return cursor variables of the REF CURSOR
category.

Accessing REF CURSOR Data


In Java EE application, a REF CURSOR is materialized as a ResultSet object and can be
accessed. Consider our example below:

Example:

import oracle.jdbc.*;
….
CallableStatement ocs;
ResultSet cursor;

// Use a PL/SQL block to open the cursor


ocs = conn.prepareCall
(“begin open ? for select LastName from MyWorkers; end;”);
ocs.registerOutParameter(1, OracleTypes.CURSOR);
ocs.execute( );
Cursor = ((OracleCallableStatement)ocs).getCursor(1);

// Use the cursor like a normal ResultSet


While (cursor.next( )) {
System.out.println(cursor.getString(1));
}

Now, to understand our example above, we have the explanation below:

Explanation:

A CallableStatement object is created by using the prepareCall method of the


connection class:
….
CallableStatement ocs;
….
Furthermore, the callable statement implements a PL/SQL procedure that returns a REF
CURSOR.
….
// Use a PL/SQL block to open the cursor
ocs = conn.prepareCall
(“begin open ? for select LastName, FirstName from MyWorkers; end;”);
515

….
As always, the output parameter of the callable statement must be registered to define its
type. We use the type code OracleTypes.CURSOR for a REF CURSOR:
….
ocs.registerOutParameter(1, OracleTypes.CURSOR);
….
The callable statement is run, returning the REF CURSOR:
….
ocs.execute( );
The CallableStatement object is cast to OracleCallableStatement to use the getCursor( )
method, which is an Oracle extension to the standard JDBC application programming
interface (API), and return the REF CURSOR into a ResultSet object.
….
Cursor = ((OracleCallableStatement)ocs).getCursor(1);
….

Creating a Package in the Database

Solution:

1. Let us select the Database Navigator tab to view it in the Navigator window.
2. This time, let us expand the DBConnection2 node (our Database node), to view
the list of database objects. Scroll down to Packages item. Right-click Packages
and select New Package from the short-cut menu.
3. In the Create PL/SQL Package dialog box, let us enter POSPKG as the name.
Then, click the OK button.
Now, the package definition is displayed in the Source Editor.
4. Now, within the package definition, type the following script:

CREATE OR REPLACE
PACKAGE POSPKG AS

/* TODO enter package declarations


(types, exceptions, methods etc) here */

TYPE ref_cursor IS REF CURSOR;

END POSPKG;

5. Let us now save the package.

Explanation:

The tasks above created a new package in the database to hold a REF CURSOR
declaration.
516

Creating a Database Function

Solution:

1. While in the Database Navigator, right-click Functions and select New Function
from the short-cut menu.
2. In the Create PL/SQL Function dialog box, enter GET_POSITIONS as the name.
Then, click the OK button.
Now, the definition for the GET_POSITIONS function is displayed in the Source
Editor.
3. In the first line of the function definition, replace VARCHAR2 with

Pospkg.ref_cursor

as the return value.

4. After the AS keyword, type the following script:

AS positions_cursor Pospkg.ref_cursor;
BEGIN
OPEN positions_cursor FOR
SELECT PosCode, Position from MyPositions;
RETURN positions_cursor;
END GET_POSITIONS;

5. Now, this time, replace NULL with

positions_cursor

as the return value.

6. Lastly, save the function now.

The function code should look like the following:

CREATE OR REPLACE
FUNCTION GET_POSITIONS RETURN Pospkg.ref_cursor
AS positions_cursor Pospkg.ref_cursor;
BEGIN
OPEN positions_cursor FOR
SELECT PosCode, Position from MyPositions;
RETURN positions_cursor;
END GET_POSITIONS;
517

So, this is how to create an Oracle Function that we can call from our Java EE
application.

Explanation:

We created a database function which we named GET_POS, that uses a REF CURSOR
to retrieve a result set of Positions from the MyPositions tables. We have here a new Java
method which we named getPositions that called the database function to retrieve the
result set.

Calling a REF CURSOR from Java Method

Solution:

1. Let us select the Applications tab to display the Application Navigator.


2. This time, we have to open the DataHandling.java class.
3. Import the OracleTypes interface as follows:

import oracle.jdbc.OracleTypes;

4. In the DataHandling.java class, let us declare a new method that calls the
GET_POSITIONS function to retrieve the result set:
public ResultSet getMyPositions() throws SQLException {
try {
getDBConnection();
String posquery = "begin ? := get_positions; end;";
CallableStatement ocs = conn.prepareCall(posquery);
ocs.registerOutParameter(1,OracleTypes.CURSOR);
ocs.execute();
rset = (ResultSet)ocs.getObject(1);
}
catch ( SQLException ex ) {
logException( ex );
}
return rset;
}

5.Let us save the DataHandling.java class file, and check for possible compilation
errors.
518

Explanation:

The tasks above created a Java method that we named as getMyPositions in the
DataHandling class which in turn calls the GET_POSITIONS function to retrieve the
result set.
We declared here a new variable
….
….
String posquery = "begin ? := get_positions; end;";
….
….
Which is to call the Oracle function: GET_POSITIONS within our Java EE application.
Then, we register the type of the OUT parameter, using an Oracle-specific type:
….
….
ocs.registerOutParameter(1,OracleTypes.CURSOR);
….
….
This is the time that we are asked to import the OracleTypes. In JDeveloper, we simply
press the Alt-Enter keys combination, then select the:
….
oracle.jdbc.OracleTypes;
….
Now, this is if we forgot to import it at the top of our Java EE application program.
This time, we have to execute the Oracle Call statement (ocs) and return the result set:
….
….
ocs.execute( );
rset = (ResultSet)ocs.getObject(1);
….
….
I think, we have already discussed the most important line of codes in this particular Java
method. Agree? I hope so.

Displaying a Dynamically Generated List

Solution:

1. Let us open the add.jsp web page in the Visual Editor.


2. Let us drag a Page Directive onto the web page to the right of the useBean tag. In
the Insert Page Directive dialog box, enter Java as the Language, and in the
Import field, browse to select java.sql.ResultSet. Finally, click the OK button.
3. Then, we have to click the Source tab of the Source Editor and insert the
following script after: <td width="50%"> PosCode </td> <td width="50%">
....
519


<%ResultSet rset = worksbean.getMyPositions();%>
<select name="PosCode"/>
<% while (rset.next()) {
out.println("<option value="+rset.getString("PosCode")+">"+
rset.getString("Position")+"</option>");
} %>
….
….
4. Let us delete or remove now the hard-coded values in the Structure window as
follows:

With the List Box component still selected in the Structure window, scroll to the
PosCode field. Examine the list of hard-coded options below the select HTML
command. Let us erase each of the options, but ensure that the Scriptlet is retained.

5. Lastly, let us save the add.jsp web page.

We can now run our Java EE application. Let us try to click the Add Worker link to add a
new worker and use the list to display a list of available positions.
The figure below shows the dynamic list of Positions in the Internet web browser:
520

Here in our Add Worker Record web page, we have the complete list of positions
available taken from our MyPositions table which are dynamically generated. The REF
CURSOR is so really very powerful, isn’t it?

Explanation:

Can you remember that we hard-coded the partial list (using Combo Box control) of
Position Codes (PosCode) and their respective Position titles in our previous Java EE
application? Like for example, when we enter a dummy data to test if we can add, change
or erase a particular worker record? We usually use Mister Dummy and Miss Dummy as
our dummy data on that particular example? We intentionally didn’t complete the list of
Position Codes and Position Titles because we will introduce this dynamically generated
list applying the power of Oracle’s REF CURSOR now!

We can now really say that we have a very cool Java EE application programming
experience. Nothing less.
521

MINI-CASE
STUDY

Design and develop a JDBC application system which has the following functions and features:

1. Allow users to login to the application with username and password validation.
2. Establish a connection to the Oracle Database server.
3. Query the database table for data and retrieve the data by applying the JavaBean
implementation.
4. Allow the users to add, change, or erase the data records from the table.
5. Display the data by applying the Java Server Pages (JSP) implementation.
6. Lastly, handle some error-trapping code by applying Exception implementation.

Follow the design specification below:

Figure 1: System Login Page

MySchool Foundation : Simple Grading System

System Login:

Username: hr

Password: hr

Host: localhost

Login Now!

Button Text fields


522

Figure 2: Filtered Search for MyStudents Page

MySchool Foundation : Simple Grading System


MyStudents Data

Enter (Last or First) Name: Santos Search

LastName FirstName Grade Course Code

Silverstone Alice 90 COMSCI

Therone Charliza 68 POLSCI

Figure 3: List of MyStudents Page

Last Name First Name Grade Course Code Add


Worker

Change
Silverstone Alice 90 COMPSCI Erase

Therone Charliza 68 POLSCI Change


Erase

Sobieski Leely 79 COMENG Change


Erase

Ballock Sandra 74 CIVENG Change


Erase

Cruz Tom 80 MECENG Change


Erase

Santos Nora 65 MARENG Change


Erase
523

Figure 4: Adding Student Record Page

MySchool Foundation : Simple Grading System

Add Student Record

Use JDBC only to add a new record

Use Stored-Procedure via JDBC to add new record

Aunor
Last Name:

First Name: Vilma

Grade: 94

INFTEC
Couse Code:

Add Now!

Button Text Fields

Figure 5: Edit Student Record Page

MySchool Foun dation : Simple Grading System

Change Student Record

Last Name: Aunor

First Name: Vilma

Grade: 94

COMSCI
Course Code:

Change Now!

Button Text Fields


524

Let us now start our solution for our mini-case study. We can easily follow the design
and development of our simple school grading system based on what we have learned
from the presented sample case study above.
Here are our strategies to accomplish the given problem:

a. First, we will create the database tables, which we will named: Student1 and
CourseCode. Now, we need to create also the Primary Key Sequence which we
will named: MyStudent_SEQ.
b. Second, we will input data into our tables. These data are the names of our
students.
c. Then, lastly, we will develop our Java EE application that is capable of searching,
adding, changing, or erasing a student’s record.

1. Apply the CREATE TABLE clause, create a table called Student1. The following
are its field names (column names) and their respective data types:

Field Names Data Types Character-Length

StudentNumber NUMBER
StudentName VARCHAR2 20
Grade INTEGER

2. Applying the INSERT INTO…VALUES clauses, input the following values into
Student1 table:

Student Number FirsName LastName Grade CourseCode

201 Alice Silverstone 90 COMSCI


202 Charliza Therone 68 POLSCI
203 Leely Sobieski 79 COMENG
204 Sandra Ballock 74 CIVENG
205 Tom Cruz 80 MECENG
206 Nora Santos 65 MARENG
207 Vilma Aunor 94 INFTEC

3. Apply the CREATE TABLE clause, create a table called CourseCode. The
following are its field names (column names) and their respective data types:

Field Names Data Types Character-Length

CourseCode VARCHAR2 10
Course VARCHAR2 30
525

4. Applying the INSERT INTO…VALUES clauses, input the following values into
CourseCode table:

Course Code Course

COMSCI Computer Science


COMENG Computer Engineering
INFTEC Information Technology
POLSCI Political Science
CIVENG Civil Engineering
MECENG Mechanical Engineering
MARENG Marine Engineering
ELEENG Electrical Engineering
MARTRA Marine Transportation
BUSMAN Business Management
BUSADM Business Administration
526

Appendix A
Complete Source Code

Java EE Application Program Source Code


We have here the complete source code of our Java EE application program which we
designed and developed in chapter 11 up to chapter 13.

.java (class) Files


// DataHandling.java
package sps;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.jdbc.pool.OracleDataSource;
import java.sql.Statement;

import javax.servlet.http.HttpSession;

import oracle.jdbc.OracleTypes;

public class DataHandling {


public DataHandling() {
}
// String jdbcUrl = null;
// String username = null;
// String password = null;
String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:XE";
String username = "hr";
String password = "hr";
Connection conn;
Statement stmt;
ResultSet rset;
String query;
String sqlString;
public void getDBConnection() throws SQLException{
OracleDataSource ds;
ds = new OracleDataSource();
ds.setURL(jdbcUrl);
conn=ds.getConnection(username,password);
}
public ResultSet getAllWorkers() throws SQLException{
getDBConnection();
try {
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
527

ResultSet.CONCUR_READ_ONLY);
query = "SELECT * FROM MyWorkers ORDER BY lastname";
System.out.println("\nQuery executed: " + query);
rset = stmt.executeQuery(query);
}
catch (SQLException e) {
e.printStackTrace();
}
return rset;
}
public ResultSet getWorkersByName(String name)
throws SQLException {
name = name.toUpperCase();
getDBConnection();
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
query =
"SELECT * FROM MyWorkers WHERE UPPER(LastName)
LIKE \'%" + name + "%\'" +
"OR UPPER(FirstName) LIKE \'%" + name +
"%\' ORDER BY LastName";
System.out.println("\nQuery executed:"+query);
rset = stmt.executeQuery(query);
return rset;
}
public boolean authenticateUser(String jdbcUrl, String username,
String password, HttpSession session) throws SQLException {
this.jdbcUrl= jdbcUrl;
this.username = username;
this.password = password;
try {
OracleDataSource ds;
ds = new OracleDataSource();
ds.setURL(jdbcUrl);
conn = ds.getConnection(username, password);
return true;
}
catch ( SQLException ex ) {
System.out.println("Unauthorized user credentials!");
session.setAttribute("errmsglogin", "Login Failed.
Pls. try again.");
this.jdbcUrl = null;
this.username = null;
this.password = null;
return false;
}
}
public MyWorkers findMyWorkersById(int empno) throws SQLException {
MyWorkers selectedWorker = new MyWorkers();
getDBConnection();
stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
query = "SELECT * FROM MyWorkers WHERE EmpNo="+empno;
System.out.println("\n Executing: " + query);
rset = stmt.executeQuery(query);
528

while (rset.next()) {
selectedWorker.setEmpNo(new Integer(rset.getInt("EmpNo")));
selectedWorker.setLastName(rset.getString("LastName"));
selectedWorker.setFirstName(rset.getString("FirstName"));
selectedWorker.setSalary(new Double(rset.getDouble("Salary")));
selectedWorker.setPosCode(rset.getString("PosCode"));
}
return selectedWorker;
}
public String updateMyWorkers(int empno, String lastname,
String firstname, String poscode,
String salary) throws SQLException {
MyWorkers oldWorker = findMyWorkersById(empno);
getDBConnection();
stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
StringBuffer columns = new StringBuffer(255);
if (lastname != null &&
!lastname.equals(oldWorker.getLastName())) {
if ( columns.length() > 0 ) {
columns.append( ", " );
}
columns.append( "LastName = '" + lastname + "'" );
}

if (firstname != null &&


!firstname.equals(oldWorker.getFirstName()))
{
columns.append( "FirstName = '" + firstname + "'" );
}

if ( poscode != null &&


!poscode.equals(oldWorker.getPosCode() ) ) {
if ( columns.length()>0) {
columns.append( ", " );
}
columns.append( "PosCode = '" + poscode + "'" );
}

if (salary != null &&


!salary.equals(oldWorker.getSalary().toString())) {
if (columns.length()>0) {
columns.append( ", " );
}
columns.append( "Salary = '"+salary+"'" );
}

if (columns.length()>0)
{
sqlString = "update MyWorkers SET "+columns.toString()
+ "WHERE empno=" + empno;
System.out.println("\nExecuting Change Method: " + sqlString);
stmt.execute(sqlString);
}
else
{
529

System.out.println("Nothing to do to update Worker Id:"+empno);


}
return "success";
}

public String addMyWorkers(String lastname, String firstname,


String poscode, int salary) throws SQLException {
getDBConnection();
stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
sqlString = "INSERT INTO MyWorkers VALUES
(MyWorker_Sequence.NEXTVAL,'"
+lastname + "','" + firstname + "','" + poscode + "'," +
salary+")";
System.out.println("\nExecuting Add Method: " + sqlString);
stmt.execute(sqlString);
return "success";
}

public String addMyWorkersSP(String LastName, String FirstName,


String PosCode,int Salary) throws SQLException {
try {
getDBConnection();
sqlString = "begin HR.ADDWORKER(?,?,?,?); end;";
CallableStatement ocs = conn.prepareCall(sqlString);
ocs.setString(1,LastName);
ocs.setString(2,FirstName);
ocs.setString(3,PosCode);
ocs.setInt(4,Salary);
System.out.println("\nAdding using Stored Procedure:
"+sqlString);
ocs.execute();
return "success";
}
catch (SQLException ex) {
System.out.println("Possible error: Make sure you
have created the stored procedure first!");
logException( ex );
return "failure";
}
}
public String eraseMyWorkersById(int id) throws SQLException {
try {
getDBConnection();
stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
sqlString = "DELETE FROM MyWorkers WHERE empno = " + id;
System.out.println("\nExecuting Erase Method: " + sqlString);
stmt.execute(sqlString);
}
catch (SQLException ex) {
logException( ex );
return "failure";
}
return "success";
530

}
public ResultSet getMyPositions() throws SQLException {
try {
getDBConnection();
String posquery = "begin ? := get_positions; end;";
CallableStatement ocs = conn.prepareCall(posquery);
ocs.registerOutParameter(1,OracleTypes.CURSOR);
ocs.execute();
rset = (ResultSet)ocs.getObject(1);
}
catch ( SQLException ex ) {
logException( ex );
}
return rset;
}
public void logException( SQLException ex ){
while ( ex != null ) {
ex.printStackTrace();
ex = ex.getNextException();
}
}
}

========================================

//TestClient.java
package sps;
import java.sql.ResultSet;

public class TestClient {


public TestClient() {
}

public static void main(String[]args) throws Exception {


DataHandling datahandling = new DataHandling();
ResultSet rset;
rset = datahandling.getAllWorkers();
System.out.println("\nEMPNO COMPLETE NAME");
System.out.println("----- -------------------");
while (rset.next()) {
System.out.println(rset.getInt(1) + " " +
rset.getString(2) + ", " +
rset.getString(3));
}
// filtered by Name with "Silang" as value
rset = datahandling.getWorkersByName("Silang");
System.out.println("\n Query results: ");
System.out.println("\nEMPNO LASTNAME FIRSTNAME SALARY");
System.out.println("------ ------- --------- --------");
while (rset.next()) {
System.out.println(rset.getInt(1) + " " +
rset.getString(2) + ", " +
rset.getString(3) + " " +
531

rset.getString(5));
}
}
}

=======================================
// MyWorkers.java
package sps;

public class MyWorkers {


public MyWorkers() {
}
private Integer empNo;
private String lastName;
private String firstName;
private Double salary;
private String posCode;

public void setEmpNo(Integer empNo) {


this.empNo = empNo;
}

public Integer getEmpNo() {


return empNo;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public String getLastName() {


return lastName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getFirstName() {


return firstName;
}

public void setSalary(Double salary) {


this.salary = salary;
}

public Double getSalary() {


return salary;
}

public void setPosCode(String posCode) {


this.posCode = posCode;
}

public String getPosCode() {


532

return posCode;
}
}

.jsp (Web Page) Files

==========================================
// index.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252"/>
<title>index</title>
</head>
<body>
<jsp:forward page="login.jsp"/>
</body>
</html>

============================================

// login.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252"/>
<title>login</title>
<link type="text/css" rel="stylesheet" href="jdeveloper.css"/>
</head>
<body>
<h2 align="center">
MyCompany Inc.: Simple Personnel System
</h2><h3>
System Login: Unauthorized User Keep Out!
</h3>
<%String errmsglogin=null;
errmsglogin =(String)session.getAttribute("errmsglogin");
if (errmsglogin !=null) {
%>
<h4>
<font color="Red">
<blink>
<%= errmsglogin%>
</blink>
533

</font>
</h4>
<%}%><form action="loging.jsp">
<table cellspacing="2" cellpadding="3" border="1" width="100%">
<tr>
<td width="50%">Username:</td>
<td width="50%">
<input type="text" name="username"/>
</td>
</tr><tr>
<td width="50%">Password:</td>
<td width="50%">
<input type="password" name="password"/>
</td>
</tr><tr>
<td width="50%">Host:</td>
<td width="50%">
<input type="text" name="host"/>
</td>
</tr>
</table>
<input type="submit" value="Login Now!"/>
</form>
</body>
</html>

=========================================

//loging.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="java.sql.ResultSet"
session="true"
autoFlush="true"
isThreadSafe="true"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252"/>
<title>loging</title>
</head>
<body>
<jsp:useBean id="worksbean" class="sps.DataHandling" scope="session"/>
<%boolean userIsValid=false;
String host = request.getParameter("host");
String username = request.getParameter("username");
String password = request.getParameter("password");
String jdbcUrl = "jdbc:oracle:thin:@"+host+":1521:XE";
userIsValid=
worksbean.authenticateUser(jdbcUrl,username,password,session);%>
<%if (userIsValid) {%>
534

<jsp:forward page="/myworkers.jsp"/>
<%} else {%>
<jsp:forward page="/login.jsp"/>
<%}%>
</body>
</html>

===========================================

// add.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252"/>
<title>add</title>
<link type="text/css" rel="stylesheet" href="jdeveloper.css"/>
</head>
<body>
<h2 align="center">
MyCompany Inc.: Simple Personnel System
</h2><h3>
Add Worker Record
</h3>
<form action="adding.jsp">
<p>
<input type="radio" name="useSP" value="false"
checked="checked"/>
Use JDBC only to add a new record
</p>
<p>
<input type="radio" name="useSP" value="true"/>
Use Stored Procedure via JDBC to add a new record
</p>
<table cellspacing="2" cellpadding="3" border="1" width="100%">
<jsp:useBean id="worksbean" class="sps.DataHandling"
scope="session"/>
<%@ page import="java.sql.ResultSet" session="true"
autoFlush="true" isThreadSafe="true"%>
<tr>
<td width="50%">Last Name:</td>
<td width="50%">
<input type="text" name="LastName"/>
</td>
</tr>
<tr>
<td width="50%">First Name:</td>
<td width="50%">
<input type="text" name="FirstName"/>
</td>
535

</tr>
<tr>
<td width="50%">PosCode:</td>
<td width="50%">
<%ResultSet rset = worksbean.getMyPositions();%>
<select name="PosCode"/>
<% while (rset.next()) {
out.println("<option value="+rset.getString("PosCode")+">"+
rset.getString("Position")+"</option>");
} %>
</td>
</tr>
<tr>
<td width="50%">Salary:</td>
<td width="50%">
<input type="text" name="Salary"/>
</td>
</tr>
</table>
<input type="submit" value="Add Now!"/>
</form>
</body>
</html>

=========================================

// adding.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252"/>
<title>adding</title>
</head>
<body>
<jsp:useBean id="worksbean" class="sps.DataHandling" scope="session"/>
<%String LastName=request.getParameter("LastName");
String FirstName=request.getParameter("FirstName");
String PosCode=request.getParameter("PosCode");
Integer Salary=new Integer(request.getParameter("Salary"));

String useSPFlag = request.getParameter("useSP");

if ( useSPFlag.equalsIgnoreCase("true"))
worksbean.addMyWorkersSP(LastName, FirstName,
PosCode, Salary.intValue());
// otherwise let us use pure JDBC Insert command
else
worksbean.addMyWorkers(LastName,FirstName,PosCode,Salary.intValue());
%>
536

<jsp:forward page="myworkers.jsp"/>
</body>
</html>

=====================================

// change.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252"/>
<title>change</title>
<link type="text/css" rel="stylesheet" href="jdeveloper.css"/>
</head>
<body>
<h2 align="center">
MyCompany Inc.: Simple Personnel System
</h2><h3 align="left">
Change Worker Record
</h3>
<form action="changing.jsp">
<table cellspacing="2" cellpadding="3" border="1" width="100%">
<jsp:useBean id="worksbean" class="sps.DataHandling"
scope="session"/>
<jsp:useBean id="myworkers" class="sps.MyWorkers"/>
<%Integer EmpNo = new Integer(request.getParameter("empno"));
myworkers=worksbean.findMyWorkersById(EmpNo.intValue());
%>
<tr>
<td width="50%">Last Name:</td>
<td width="50%">
<input type="text" name="LastName"
value="<%=myworkers.getLastName()%>"/>
<input type="hidden" name="empno"
value="<%=myworkers.getEmpNo()%>"/>
</td>
</tr>
<tr>
<td width="50%">First Name:</td>
<td width="50%">
<input type="text" name="FirstName"
value="<%=myworkers.getFirstName()%>"/>
</td>
</tr>
<tr>
<td width="50%">Position Code:</td>
<td width="50%">
<input type="text" name="PosCode"
value="<%=myworkers.getPosCode()%>"/>
</td>
537

</tr>
<tr>
<td width="50%">Salary:</td>
<td width="50%">
<input type="text" name="Salary"
value="<%=myworkers.getSalary()%>"/>
</td>
</tr>
</table>
<input type="submit" value="Change Now!"/>
</form>
</body>
</html>

==========================================

// changing.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252"/>
<title>changing</title>
</head>
<body>
<p>
&nbsp;
</p><p>
<%@ page import="java.sql.ResultSet" session="true"
autoFlush="true" isThreadSafe="true"%>
</p><p>
<jsp:useBean id="worksbean" class="sps.DataHandling"
scope="session"/>
<% Integer EmpNo = new Integer(request.getParameter("empno"));
String LastName = request.getParameter("LastName");
String FirstName = request.getParameter("FirstName");
String PosCode = request.getParameter("PosCode");
String Salary = request.getParameter("Salary");
worksbean.updateMyWorkers(EmpNo.intValue(),LastName,FirstName,
PosCode,Salary);
%>
</p><p>
&nbsp;
</p> <jsp:forward page="myworkers.jsp"/>
</body>
</html>

===============================================
538

// erasing.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252"/>
<title>erasing</title>
</head>
<body>
<jsp:useBean id="worksbean" class="sps.DataHandling"
scope="session"/>
<%Integer EmpNo = new Integer(request.getParameter("empno"));
worksbean.eraseMyWorkersById(EmpNo.intValue());%>
<jsp:forward page="myworkers.jsp"/>
</body>
</html>

========================================

// myworkers.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"
import="java.sql.ResultSet"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252"/>
<title>myworkers</title>
<link type="text/css" rel="stylesheet" href="jdeveloper.css"/>
</head>
<body>
<h2 align="center">
MyCompany &nbsp;Inc.: Simple Personnel System
</h2><h3>
MyWorkers Data:
</h3><jsp:useBean id="worksbean" class="sps.DataHandling"
scope="session"/>
<form action="myworkers.jsp">
Enter (Last or First) Name:
<input type="text" name="query"/>
<input type="submit" value="Search"/>
</form>
<%ResultSet rset;
String query = request.getParameter("query");
if (query !=null && query !=null)
rset=worksbean.getWorkersByName(query);
else
539

rset = worksbean.getAllWorkers();%>
<table cellspacing="2" cellpadding="3" border="1" width="98%">
<tr>
<td width="130">
<h4>
LAST NAME
</h4></td>
<td width="131">
<h4>
FIRST NAME
</h4></td>
<td width="131">
<h4>
POSITION CODE
</h4></td>
<td width="83">
<h4>
SALARY
</h4></td>
<td width="57">
<h4>
<a href="add.jsp">Add Worker</a>
</h4></td>
</tr>
<% while (rset.next()) {
out.println("<tr>");
out.println("<td>"+
rset.getString("LastName")+"</td><td>"+
rset.getString("FirstName")+"</td><td>"+
rset.getString("PosCode")+"</td><td>"+
rset.getString("Salary")+
"</td><td> <a href=\"change.jsp?empno=" + rset.getInt(1) +
"\">Change</a> <a href=\"erasing.jsp?empno=" + rset.getInt(1)
+ "\">Erase</a></td>");
out.println("</tr>");
};%>
</table>
</body>
</html>

==================================

Proc, Func, and Pkg Files


(Procedure, Function, and Package)
REM Oracle Database PROCEDURE
CREATE OR REPLACE
PROCEDURE "ADDWORKER" (p_LastName MyWorkers.LastName%Type,
p_FirstName MyWorkers.FirstName%Type,
p_PosCode MyWorkers.PosCode%Type,
p_Salary MyWorkers.Salary%Type
540

)
AS
BEGIN
INSERT INTO MyWorkers VALUES (MyWorker_Sequence.NEXTVAL,
p_LastName, p_FirstName, p_PosCode, p_Salary) ;
END "ADDWORKER";

=================================

REM Oracle Database FUNCTION

CREATE OR REPLACE
FUNCTION GET_POSITIONS RETURN Pospkg.ref_cursor
AS positions_cursor Pospkg.ref_cursor;
BEGIN
OPEN positions_cursor FOR
SELECT PosCode, Position from MyPositions;
RETURN positions_cursor;
END GET_POSITIONS;

==========================================

REM Oracle Database PACKAGE


CREATE OR REPLACE
PACKAGE POSPKG AS

/* TODO enter package declarations


(types, exceptions, methods etc) here */

TYPE ref_cursor IS REF CURSOR;

END POSPKG;
541

DISCLAIMER and WARNING


The author is trying his very best to ensure that all the codes presented in the Java EE
(Enterprise Edition) Application programs should be free of any errors or bugs. Inspite of
his best effort to based his presentation with the official manual – *Oracle Database 2
Day + Java Developer’s Guide 11g, downloaded from oracle.com website, the bugs or
errors in the program are actually lurking in the presented code (with the author’s great
confusion why?). This further means that the code presented here must not be used in a
production environment or in an actual company used, because the program could harm
the data integrity within the company’s Oracle Database Server. This should serve as a
warning to you – developers. Nevertheless, you are advised to fine-tune the code
presented here to suit your company’s IT needs. You just need more readings and
research about Java EE Application programming from different reliable resources. With
this advice, I wish you luck and happiness in your programming endeavor. May God
bless you always, my friend.

* The Oracle Database 2 Day + Java Developer’s Guide 11g Release 1 is the official manual of Java EE
Application in a tutorial format. This official manual was revised 3 times in 5 years. The first one is
published in July 2007, then the second one is on September 2009, and the third one is on February 2012.
The author expiremented and tested all the sample Java EE application programs presented in the official
manual in more than a dozen times. Unfortunately, the author failed to come up with an error-free Java EE
Application program. It was in his great confusion that he concluded that there could be some missing
software libraries that are needed to successfully run the entire Java EE Application programs that are
presented in the official manual. Maybe, just maybe, a developer in the company should purchase the
commercial version of Oracle JDeveloper as well as the Oracle Database 11g software from Oracle
company so that the Java EE Application programs presented in the official manual would run and work
without any problem or bug whatsover. Well, as the author said, “it is just- maybe?”.

Das könnte Ihnen auch gefallen