Java Lecture Chapter 6

Marvic

Member
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 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.

Example 1:
Design and develop a Java program that generates the given sequence numbers using looping statements. Follow the given design specification below:

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 program 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
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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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:
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;
while (i<=5) {
strNo = String.valueOf(i);
varRow=varRow+20;
objG.drawString(strNo,60,varRow);
i++;
}
}
}

2. Then save the Java program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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++;
}
}
}

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 program 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
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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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);
}
}

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 program that generates the given sequence numbers using looping statements. This time, it is in horizontal format. Follow the given design specification below:

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);
}
}
}
2. Then save the Java program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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
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);
}
}
}
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 program 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>
</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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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
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.
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 program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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)
7. When no error is encountered during the compilation process, you can now type the following
at your Web browser:
C:\javaprog\dol4.htm
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 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 program that generates the given inverse sequence numbers using for loop statement. Follow the given design specification below:

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 program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (then press the Enter key)
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

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;
.
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 program that generates the given inverse sequence numbers using while loop statement. This time, it is in horizontal format. Follow the given design specification below:

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 program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (then press the Enter key)
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

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) {
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 program that generates the given sequence numbers which is incremented by 5 using do/while loop statement. Follow the given design specification below:

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 program 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:
Type the word command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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 as 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 6:
Design and develop a Java program that generates the given sequence numbers which is decremented by 5 using while loop statement. Follow the given design specification below:

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 program 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>
<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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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.

Example 7:
Design and develop a Java program 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:

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();
}
}

2. Then save the Java program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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
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);
}

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++)
So this is how we finished our discussion.


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 program 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>
</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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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++;
}
}
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 how 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);
}
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 program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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:
C:\javaprog\dol3.htm

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 specify 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;
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.
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 this problem could be impossible to accomplish. Let us start solving them now.

Example 8:
Design and develop a Java program that computes the factorial value of N! (as input) and displays the result. Follow the given design specification below:

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));
}
}
}

2. Then save the Java program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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


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);
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;
}
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 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 program that computes the power value of the input base and exponent numbers. Then display the result. Follow the given design specification below:

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 program 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:
<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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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);
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 observed 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);

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.

Example 10:
Design and develop a Java program that demonstrates how to preload a collection of items to a Scrolling list. Follow the given design specification below:

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);
}
}

2. Then save the Java program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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 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 9:
Design and develop a Java program 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:

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:");
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 program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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)
7. When no error is encountered during the compilation process, you can now type the following
at your Web browser:
C:\javaprog\listbox6.htm

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);
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 10:
Design and develop a Java program 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:

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 program 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:
<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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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 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 11:
Design and develop a Java program 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:

Solution:
1. At the Microsoft NotePad, write the following code:
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;

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 program 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>
<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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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 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 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 12:
Design and develop a Java program 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:

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");
lstBox1.add("Gray");
add(lstBox1);

}

public void actionPerformed(ActionEvent objE) {
strColor = txtText1.getText();
lstBox1.add(strColor);
repaint();
}
}

2. Then save the Java program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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 served 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=" ";

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 13:
Design and develop a Java program 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:

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);
}

public void actionPerformed(ActionEvent objE) {
if (objE.getSource() == lstBox1) {
strFood = lstBox1.getSelectedItem();
lstBox2.add(strFood);
repaint();
}

}
}

2. Then save the Java program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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 served 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=" ";

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 14:
Design and develop a Java program 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:

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());
repaint();
}
else if (objE.getItemSelectable()==lstBox2) {
lstBox1.add(lstBox2.getSelectedItem());
lstBox2.remove(lstBox2.getSelectedIndex());
repaint();
}
}
}

2. Then save the Java program 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=250
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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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");
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
Example 15:

Design and develop a Java program that should apply the add( ), remove( ), and clear( ) methods of the scrolling list object. Follow the given design specification below:

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();
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 program 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>
</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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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

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( );
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 observed 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 organized the controls in each respective panels. You have to take note that we were able to accomplish this task by apply 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 16:

Design and develop a Java program 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:

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);
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);
}
repaint();
}
}

2. Then save the Java program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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:t9

C:\javaprog\dlistbox1.htm

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;

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);
}
repaint( );
}
}

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 tha 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 17:

Design and develop a Java program 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:

6.17 An applet that displays the selected item from the Choice control to 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 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 program 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>
</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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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:t9

C:\javaprog\combobox2.htm

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);
}

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 18:

Design and develop a Java program 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:

6.18 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.*;
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 program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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
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.
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( ));
}
}
}

Example 19:

Design and develop a Java program 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:

6.19 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"));
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 program 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 command at the Run menu of Windows operating system, then at the C:\> prompt, type:
C:\>cd javaprog (then press the Enter key)
C:\JAVAPROG>javap (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)
7. When no error is encountered during the compilation process, you can now type the following
at your Web browser:
C:\javaprog\combobox1.htm
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;

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.
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!

QagqXaT.png


Java Lecture Pages
 

Similar threads


Top Bottom