- •Contents
- •Preface
- •Introduction to Computers, the Internet and the Web
- •1.3 Computer Organization
- •Languages
- •1.9 Java Class Libraries
- •1.12 The Internet and the World Wide Web
- •1.14 General Notes about Java and This Book
- •Sections
- •Introduction to Java Applications
- •2.4 Displaying Text in a Dialog Box
- •2.5 Another Java Application: Adding Integers
- •2.8 Decision Making: Equality and Relational Operators
- •Introduction to Java Applets
- •3.2 Sample Applets from the Java 2 Software Development Kit
- •3.3 A Simple Java Applet: Drawing a String
- •3.4 Two More Simple Applets: Drawing Strings and Lines
- •3.6 Viewing Applets in a Web Browser
- •3.7 Java Applet Internet and World Wide Web Resources
- •Repetition)
- •Class Attributes
- •5.8 Labeled break and continue Statements
- •5.9 Logical Operators
- •Methods
- •6.2 Program Modules in Java
- •6.7 Java API Packages
- •6.13 Example Using Recursion: The Fibonacci Series
- •6.16 Methods of Class JApplet
- •Class Operations
- •Arrays
- •7.6 Passing Arrays to Methods
- •7.8 Searching Arrays: Linear Search and Binary Search
- •Collaboration Among Objects
- •8.2 Implementing a Time Abstract Data Type with a Class
- •8.3 Class Scope
- •8.4 Controlling Access to Members
- •8.5 Creating Packages
- •8.7 Using Overloaded Constructors
- •8.9 Software Reusability
- •8.10 Final Instance Variables
- •Classes
- •8.16 Data Abstraction and Encapsulation
- •9.2 Superclasses and Subclasses
- •9.5 Constructors and Finalizers in Subclasses
- •Conversion
- •9.11 Type Fields and switch Statements
- •9.14 Abstract Superclasses and Concrete Classes
- •9.17 New Classes and Dynamic Binding
- •9.18 Case Study: Inheriting Interface and Implementation
- •9.19 Case Study: Creating and Using Interfaces
- •9.21 Notes on Inner Class Definitions
- •Strings and Characters
- •10.2 Fundamentals of Characters and Strings
- •10.21 Card Shuffling and Dealing Simulation
- •Handling
- •Graphics and Java2D
- •11.2 Graphics Contexts and Graphics Objects
- •11.5 Drawing Lines, Rectangles and Ovals
- •11.9 Java2D Shapes
- •12.12 Adapter Classes
- •Cases
- •13.3 Creating a Customized Subclass of JPanel
- •Applications
- •Controller
- •Exception Handling
- •14.6 Throwing an Exception
- •14.7 Catching an Exception
- •Multithreading
- •15.3 Thread States: Life Cycle of a Thread
- •15.4 Thread Priorities and Thread Scheduling
- •15.5 Thread Synchronization
- •15.9 Daemon Threads
- •Multithreading
- •Design Patterns
- •Files and Streams
- •16.2 Data Hierarchy
- •16.3 Files and Streams
- •Networking
- •17.2 Manipulating URIs
- •17.3 Reading a File on a Web Server
- •17.4 Establishing a Simple Server Using Stream Sockets
- •17.5 Establishing a Simple Client Using Stream Sockets
- •17.9 Security and the Network
- •18.2 Loading, Displaying and Scaling Images
- •18.3 Animating a Series of Images
- •18.5 Image Maps
- •18.6 Loading and Playing Audio Clips
- •18.7 Internet and World Wide Web Resources
- •Data Structures
- •19.4 Linked Lists
- •20.8 Bit Manipulation and the Bitwise Operators
- •Collections
- •21.8 Maps
- •21.9 Synchronization Wrappers
- •21.10 Unmodifiable Wrappers
- •22.2 Playing Media
- •22.3 Formatting and Saving Captured Media
- •22.5 Java Sound
- •22.8 Internet and World Wide Web Resources
- •Hexadecimal Numbers
1360 |
Number Systems (on CD) |
|
Appendix E |
|
|
|
|||
Positional values in the hexadecimal number system |
|
|||
|
|
|
|
|
Decimal digit |
3 |
D |
A |
|
Position name |
Two-hundred-and- |
Sixteens |
Ones |
|
|
|
fifty-sixes |
|
|
Positional value |
256 |
16 |
1 |
|
Positional value as a |
162 |
161 |
160 |
|
power of the base (16) |
|
|
|
Fig. E.6 Positional values in the hexadecimal number system.
For longer hexadecimal numbers, the next positions to the left would be the four-thou- sand-and-ninety-sixes position (16 to the 3rd power), the sixty-five-thousand-five-hun- dred-and-thirty-six position (16 to the 4th power), and so on.
E.2 Abbreviating Binary Numbers as Octal Numbers and
Hexadecimal Numbers
The main use for octal and hexadecimal numbers in computing is for abbreviating lengthy binary representations. Figure E.7 highlights the fact that lengthy binary numbers can be expressed concisely in number systems with higher bases than the binary number system.
Decimal |
Binary{ |
Octal |
Hexadecimal |
number |
representation |
representation |
representation |
|
|
|
|
0 |
0 |
0 |
0 |
1 |
1 |
1 |
1 |
2 |
10 |
2 |
2 |
3 |
11 |
3 |
3 |
4 |
100 |
4 |
4 |
5 |
101 |
5 |
5 |
6 |
110 |
6 |
6 |
7 |
111 |
7 |
7 |
8 |
1000 |
10 |
8 |
9 |
1001 |
11 |
9 |
10 |
1010 |
12 |
A |
11 |
1011 |
13 |
B |
12 |
1100 |
14 |
C |
13 |
1101 |
15 |
D |
14 |
1110 |
16 |
E |
15 |
1111 |
17 |
F |
16 |
10000 |
20 |
10 |
Fig. E.7 Decimal, binary, octal, and hexadecimal equivalents.
Appendix E |
Number Systems (on CD) |
1361 |
A particularly important relationship that both the octal number system and the hexadecimal number system have to the binary system is that the bases of octal and hexadecimal (8 and 16 respectively) are powers of the base of the binary number system (base 2). Consider the following 12-digit binary number and its octal and hexadecimal equivalents. See if you can determine how this relationship makes it convenient to abbreviate binary numbers in octal or hexadecimal. The answer follows the numbers.
Binary Number |
Octal equivalent |
Hexadecimal equivalent |
100011010001 |
4321 |
8D1 |
To see how the binary number converts easily to octal, simply break the 12-digit binary number into groups of three consecutive bits each, and write those groups over the corresponding digits of the octal number as follows
100 |
011 |
010 |
001 |
4 |
3 |
2 |
1 |
Notice that the octal digit you have written under each group of thee bits corresponds precisely to the octal equivalent of that 3-digit binary number as shown in Fig. E.7.
The same kind of relationship may be observed in converting numbers from binary to hexadecimal. In particular, break the 12-digit binary number into groups of four consecutive bits each and write those groups over the corresponding digits of the hexadecimal number as follows
1000 |
1101 |
0001 |
8 |
D |
1 |
Notice that the hexadecimal digit you wrote under each group of four bits corresponds precisely to the hexadecimal equivalent of that 4-digit binary number as shown in Fig. E.7.
E.3 Converting Octal Numbers and Hexadecimal Numbers to Binary Numbers
In the previous section, we saw how to convert binary numbers to their octal and hexadecimal equivalents by forming groups of binary digits and simply rewriting these groups as their equivalent octal digit values or hexadecimal digit values. This process may be used in reverse to produce the binary equivalent of a given octal or hexadecimal number.
For example, the octal number 653 is converted to binary simply by writing the 6 as its 3-digit binary equivalent 110, the 5 as its 3-digit binary equivalent 101, and the 3 as its 3- digit binary equivalent 011 to form the 9-digit binary number 110101011.
The hexadecimal number FAD5 is converted to binary simply by writing the F as its 4-digit binary equivalent 1111, the A as its 4-digit binary equivalent 1010, the D as its 4- digit binary equivalent 1101, and the 5 as its 4-digit binary equivalent 0101 to form the 16digit 1111101011010101.
E.4 Converting from Binary, Octal, or Hexadecimal to Decimal
Because we are accustomed to working in decimal, it is often convenient to convert a binary, octal, or hexadecimal number to decimal to get a sense of what the number is “really” worth. Our diagrams in Section E.1 express the positional values in decimal. To convert a number to decimal from another base, multiply the decimal equivalent of each digit by its
1362 |
Number Systems (on CD) |
Appendix E |
positional value, and sum these products. For example, the binary number 110101 is converted to decimal 53 as shown in Fig. E.8.
To convert octal 7614 to decimal 3980, we use the same technique, this time using appropriate octal positional values as shown in Fig. E.9.
To convert hexadecimal AD3B to decimal 44347, we use the same technique, this time using appropriate hexadecimal positional values as shown in Fig. E.10.
E.5 Converting from Decimal to Binary, Octal, or Hexadecimal
The conversions of the previous section follow naturally from the positional notation conventions. Converting from decimal to binary, octal, or hexadecimal also follows these conventions.
Suppose we wish to convert decimal 57 to binary. We begin by writing the positional values of the columns right to left until we reach a column whose positional value is greater than the decimal number. We do not need that column, so we discard it. Thus, we first write:
Converting a binary number to decimal
Positional values: |
32 |
16 |
|
8 |
4 |
2 |
1 |
|
Symbol values: |
1 |
1 |
|
0 |
1 |
0 |
1 |
|
Products: |
|
1*32=32 |
1*16=16 |
0*8=0 |
1*4=4 |
0*2=0 |
1*1=1 |
|
Sum: |
|
= 32 + 16 + 0 + 4 + 0 + 1 = 53 |
|
|
||||
|
|
|
|
|
||||
Fig. E.8 |
Converting a binary number to decimal. |
|
|
|
||||
|
|
|
|
|
||||
Converting an octal number to decimal |
|
|
|
|
||||
|
|
|
|
|
|
|
|
|
Positional values: |
512 |
|
64 |
|
8 |
1 |
|
|
Symbol values: |
7 |
|
6 |
|
1 |
4 |
|
|
Products |
|
7*512=3584 |
6*64=384 |
1*8=8 |
4*1=4 |
|||
Sum: |
|
= 3584 + 384 + 8 + 4 = 3980 |
|
|
||||
|
|
|
|
|||||
Fig. E.9 |
Converting an octal number to decimal. |
|
|
|||||
|
|
|
|
|||||
Converting a hexadecimal number to decimal |
|
|
|
|||||
|
|
|
|
|
|
|
|
|
Positional values: |
4096 |
|
256 |
|
16 |
1 |
|
|
Symbol values: |
A |
|
D |
|
3 |
B |
|
|
Products |
|
A*4096=40960 D*256=3328 |
3*16=48 |
B*1=11 |
||||
Sum: |
|
= 40960 + 3328 + 48 + 11 = 44347 |
|
|
Fig. E.10 Converting a hexadecimal number to decimal.
Appendix E |
Number Systems (on CD) |
1363 |
||
Positional values: 64 32 16 8 |
4 |
2 |
1 |
|
Then we discard the column with positional value 64 leaving:
Positional values: |
32 16 8 |
4 |
2 |
1 |
Next we work from the leftmost column to the right. We divide 32 into 57 and observe that there is one 32 in 57 with a remainder of 25, so we write 1 in the 32 column. We divide 16 into 25 and observe that there is one 16 in 25 with a remainder of 9 and write 1 in the 16 column. We divide 8 into 9 and observe that there is one 8 in 9 with a remainder of 1. The next two columns each produce quotients of zero when their positional values are divided into 1 so we write 0s in the 4 and 2 columns. Finally, 1 into 1 is 1 so we write 1 in the 1 column. This yields:
Positional values: |
32 |
16 |
8 |
4 |
2 |
1 |
Symbol values: |
1 |
1 |
1 |
0 |
0 |
1 |
and thus decimal 57 is equivalent to binary 111001.
To convert decimal 103 to octal, we begin by writing the positional values of the columns until we reach a column whose positional value is greater than the decimal number. We do not need that column, so we discard it. Thus, we first write:
Positional values: 512 64 8 |
1 |
Then we discard the column with positional value 512, yielding:
Positional values: |
64 8 |
1 |
Next we work from the leftmost column to the right. We divide 64 into 103 and observe that there is one 64 in 103 with a remainder of 39, so we write 1 in the 64 column. We divide 8 into 39 and observe that there are four 8s in 39 with a remainder of 7 and write 4 in the 8 column. Finally, we divide 1 into 7 and observe that there are seven 1s in 7 with no remainder so we write 7 in the 1 column. This yields:
Positional values: |
64 |
8 |
1 |
Symbol values: |
1 |
4 |
7 |
and thus decimal 103 is equivalent to octal 147.
To convert decimal 375 to hexadecimal, we begin by writing the positional values of the columns until we reach a column whose positional value is greater than the decimal number. We do not need that column, so we discard it. Thus, we first write
Positional values: 4096 256 16 1
Then we discard the column with positional value 4096, yielding:
Positional values: |
256 16 1 |
Next we work from the leftmost column to the right. We divide 256 into 375 and observe that there is one 256 in 375 with a remainder of 119, so we write 1 in the 256 column. We divide 16 into 119 and observe that there are seven 16s in 119 with a remainder of 7 and write 7 in the 16 column. Finally, we divide 1 into 7 and observe that there are seven 1s in 7 with no remainder so we write 7 in the 1 column. This yields:
1364 |
Number Systems (on CD) |
|
Appendix E |
|
|
Positional values: |
256 |
16 |
1 |
|
Symbol values: |
1 |
7 |
7 |
and thus decimal 375 is equivalent to hexadecimal 177.
E.6 Negative Binary Numbers: Two’s Complement Notation
The discussion in this appendix has been focussed on positive numbers. In this section, we explain how computers represent negative numbers using two’s complement notation. First we explain how the two’s complement of a binary number is formed, and then we show why it represents the negative value of the given binary number.
Consider a machine with 32-bit integers. Suppose
int value = 13;
The 32-bit representation of value is
00000000 00000000 00000000 00001101
To form the negative of value we first form its one’s complement by applying Java’s bitwise complement operator (~):
onesComplementOfValue = ~value;
Internally, ~value is now value with each of its bits reversed—ones become zeros and zeros become ones as follows:
value:
00000000 00000000 00000000 00001101
~value (i.e., value’s ones complement): 11111111 11111111 11111111 11110010
To form the two’s complement of value we simply add one to value’s one’s complement. Thus
Two’s complement of value:
11111111 11111111 11111111 11110011
Now if this is in fact equal to -13, we should be able to add it to binary 13 and obtain a result of 0. Let us try this:
00000000 |
00000000 00000000 00001101 |
+11111111 |
11111111 11111111 11110011 |
------------------------------------
00000000 00000000 00000000 00000000
The carry bit coming out of the leftmost column is discarded and we indeed get zero as a result. If we add the one’s complement of a number to the number, the result would be all 1s. The key to getting a result of all zeros is that the twos complement is 1 more than the one’s complement. The addition of 1 causes each column to add to 0 with a carry of 1. The carry keeps moving leftward until it is discarded from the leftmost bit, and hence the resulting number is all zeros.
Computers actually perform a subtraction such as
x = a - value;
Appendix E |
Number Systems (on CD) |
1365 |
by adding the two’s complement of value to a as follows:
x = a + (~value + 1);
Suppose a is 27 and value is 13 as before. If the two’s complement of value is actually the negative of value, then adding the two’s complement of value to a should produce the result 14. Let us try this:
a (i.e., 27) |
00000000 |
00000000 00000000 00011011 |
+(~value + 1) |
+11111111 |
11111111 11111111 11110011 |
|
------------------------------------ |
|
|
00000000 |
00000000 00000000 00001110 |
which is indeed equal to 14.
SUMMARY
•When we write an integer such as 19 or 227 or -63 in a Java program, the number is automatically assumed to be in the decimal (base 10) number system. The digits in the decimal number system are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. The lowest digit is 0 and the highest digit is 9—one less than the base of 10.
•Internally, computers use the binary (base 2) number system. The binary number system has only two digits, namely 0 and 1. Its lowest digit is 0 and its highest digit is 1—one less than the base of 2.
•The octal number system (base 8) and the hexadecimal number system (base 16) are popular primarily because they make it convenient to abbreviate binary numbers.
•The digits of the octal number system range from 0 to 7.
•The hexadecimal number system poses a problem because it requires sixteen digits—a lowest digit of 0 and a highest digit with a value equivalent to decimal 15 (one less than the base of 16). By convention, we use the letters A through F to represent the hexadecimal digits corresponding to decimal values 10 through 15.
•Each number system uses positional notation—each position in which a digit is written has a different positional value.
•A particularly important relationship that both the octal number system and the hexadecimal number system have to the binary system is that the bases of octal and hexadecimal (8 and 16 respectively) are powers of the base of the binary number system (base 2).
•To convert an octal number to a binary number, simply replace each octal digit with its three-digit binary equivalent.
•To convert a hexadecimal number to a binary number, simply replace each hexadecimal digit with its four-digit binary equivalent.
•Because we are accustomed to working in decimal, it is convenient to convert a binary, octal or hexadecimal number to decimal to get a sense of the number’s “real” worth.
•To convert a number to decimal from another base, multiply the decimal equivalent of each digit by its positional value, and sum these products.
•Computers represent negative numbers using two’s complement notation.
•To form the negative of a value in binary, first form its one’s complement by applying Java’s bitwise complement operator (~). This reverses the bits of the value. To form the two’s complement of a value, simply add one to the value’s one’s complement.
1366 Number Systems (on CD) Appendix E
TERMINOLOGY
base |
digit |
base 2 number system |
hexadecimal number system |
base 8 number system |
negative value |
base 10 number system |
octal number system |
base 16 number system |
one’s complement notation |
binary number system |
positional notation |
bitwise complement operator (~) |
positional value |
conversions |
symbol value |
decimal number system |
two’s complement notation |
SELF-REVIEW EXERCISES
E.1 |
The bases of the decimal, binary, octal, and hexadecimal number systems are |
, |
||||||
|
|
, |
|
and |
|
respectively. |
|
|
E.2 In general, the decimal, octal, and hexadecimal representations of a given binary number contain (more/fewer) digits than the binary number contains.
E.3 (True/False) A popular reason for using the decimal number system is that it forms a convenient notation for abbreviating binary numbers simply by substituting one decimal digit per group of four binary bits.
E.4 The (octal / hexadecimal / decimal) representation of a large binary value is the most concise (of the given alternatives).
E.5 (True/False) The highest digit in any base is one more than the base.
E.6 (True/False) The lowest digit in any base is one less than the base.
E.7 |
The positional value of the rightmost digit of any number in either binary, octal, decimal, or |
||||
hexadecimal is always |
|
. |
|
|
|
E.8 |
The positional value of the digit to the left of the rightmost digit of any number in binary, |
||||
octal, decimal, or hexadecimal is always equal to |
|
. |
E.9 Fill in the missing values in this chart of positional values for the rightmost four positions in each of the indicated number systems:
decimal |
1000 |
100 |
10 |
1 |
hexadecimal |
... |
256 |
... |
... |
binary |
... ... |
... |
... |
|
octal |
512 ... |
8 |
... |
E.10 Convert binary 110101011000 to octal and to hexadecimal.
E.11 Convert hexadecimal FACE to binary.
E.12 Convert octal 7316 to binary.
E.13 Convert hexadecimal 4FEC to octal. (Hint: First convert 4FEC to binary then convert that binary number to octal.)
E.14 Convert binary 1101110 to decimal.
E.15 Convert octal 317 to decimal.
E.16 Convert hexadecimal EFD4 to decimal.
E.17 Convert decimal 177 to binary, to octal, and to hexadecimal.
E.18 Show the binary representation of decimal 417. Then show the one’s complement of 417, and the two’s complement of 417.
Appendix E |
Number Systems (on CD) |
1367 |
E.19 What is the result when the one’s complement of a number is added to itself?
SELF-REVIEW ANSWERS
E.1 10, 2, 8, 16.
E.2 Fewer.
E.3 False.
E.4 Hexadecimal.
E.5 False. The highest digit in any base is one less than the base.
E.6 False. The lowest digit in any base is zero.
E.7 1 (the base raised to the zero power).
E.8 The base of the number system.
E.9 Fill in the missing values in this chart of positional values for the rightmost four positions in each of the indicated number systems:
decimal |
1000 |
100 |
10 |
1 |
hexadecimal |
4096 |
256 |
16 |
1 |
binary |
8 |
4 |
2 |
1 |
octal |
512 |
64 |
8 |
1 |
E.10 Octal 6530; Hexadecimal D58.
E.11 Binary 1111 1010 1100 1110.
E.12 Binary 111 011 001 110.
E.13 Binary 0 100 111 111 101 100; Octal 47754.
E.14 Decimal 2+4+8+32+64=110.
E.15 Decimal 7+1*8+3*64=7+8+192=207.
E.16 Decimal 4+13*16+15*256+14*4096=61396.
E.17 Decimal 177
to binary:
256 128 64 32 16 8 4 2 1
128 64 32 16 8 4 2 1 (1*128)+(0*64)+(1*32)+(1*16)+(0*8)+(0*4)+(0*2)+(1*1) 10110001
to octal:
512 64 8 1
64 8 1 (2*64)+(6*8)+(1*1) 261
to hexadecimal:
256 16 1
16 1 (11*16)+(1*1) (B*16)+(1*1) B1
1368 |
Number Systems (on CD) |
Appendix E |
E.18 Binary:
512 256 128 64 32 16 8 4 2 1
256 128 64 32 16 8 4 2 1 (1*256)+(1*128)+(0*64)+(1*32)+(0*16)+(0*8)+(0*4)+(0*2)+ (1*1)
110100001
One’s complement: 001011110 Two’s complement: 001011111
Check: Original binary number + its two’s complement
110100001
001011111
---------
000000000
E.19 Zero.
EXERCISES
E.20 Some people argue that many of our calculations would be easier in the base 12 number system because 12 is divisible by so many more numbers than 10 (for base 10). What is the lowest digit in base 12? What might the highest symbol for the digit in base 12 be? What are the positional values of the rightmost four positions of any number in the base 12 number system?
E.21 How is the highest symbol value in the number systems we discussed related to the positional value of the first digit to the left of the rightmost digit of any number in these number systems?
E.22 Complete the following chart of positional values for the rightmost four positions in each of the indicated number systems:
decimal1000100 |
10 |
1 |
||
base 6 |
...... |
6... |
|
|
base |
13 ... 169... |
... |
||
base |
3 |
27......... |
|
|
E.23 Convert binary 100101111010 to octal and to hexadecimal.
E.24 Convert hexadecimal 3A7D to binary.
E.25 Convert hexadecimal 765F to octal. (Hint: First convert 765F to binary, then convert that binary number to octal.)
E.26 Convert binary 1011110 to decimal.
E.27 Convert octal 426 to decimal.
E.28 Convert hexadecimal FFFF to decimal.
E.29 Convert decimal 299 to binary, to octal, and to hexadecimal.
E.30 Show the binary representation of decimal 779. Then show the one’s complement of 779, and the two’s complement of 779.
E.31 What is the result when the two’s complement of a number is added to itself?
E.32 Show the two’s complement of integer value -1 on a machine with 32-bit integers.
F
Creating HTML Documentation with javadoc (on CD)
Objectives
•To introduce the javadoc J2SDK tool.
•To introduce documentation comments.
•To understand javadoc tags.
• To be able to generate HTML API documentation with javadoc.
• To understand javadoc generated documentation files.
Oh I get by with a little help from my friends.
John Lennon and Paul McCartney
I feel
The link of nature draw me.
John Milton
I think I shall never see
A poem lovely as a tree.
Joyce Kilmer
There is only one religion, though there are a hundred versions of it.
George Bernard Shaw
What I like in a good author is not what he says, but what he whispers.
Logan Pearsall Smith
I shall return.
Douglas MacArthur
1370 |
Creating HTML Documentation with javadoc (on CD) |
Appendix F |
Outline
F.1 Introduction
F.2 Documentation Comments
F.3 Documenting Java Source Code
F.4 javadoc
F.5 Files Produced by javadoc
Summary • Terminology
F.1 Introduction
In this appendix, we provide an introduction to the Java 2 Software Developent Kit’s javadoc utility for creating HTML files that document Java code. This is the tool used by Sun Microsystems to create the Java API documentation (Fig. F.1). We discuss the special Java comments and tags required by javadoc to create documentation based on your source code and how to execute the javadoc tool.
For detailed information on javadoc, visit the javadoc home page at
java.sun.com/j2se/1.3/docs/tooldocs/javadoc/index.html
F.2 Documentation Comments
Before HTML files can be generated with the javadoc tool, programmers must insert special comments—called documentation comments—into their source files. Documentation comments are the only comments recognized by javadoc. Documentation comments begin with /** and end with */. An example of a simple documentation comment is
/** Sorts integer array using MySort algorithm */
Like other comments, documentation comments are not translated into bytecodes. Because javadoc is used to create HTML files, documentation comments can contain HTML tags. For example, the documentation comment
/** Sorts integer array using <em>MySort</em> algorithm */
which contains the HTML emphasis tags <em> and </em> is valid. In the generated HTML files, MySort will appear as emphasized text (normally italic). As we will see, javadoc tags can be inserted into the documentation comments to help javadoc document your source code. These tags—which begin with an @ symbol—are not HTML tags.
F.3 Documenting Java Source Code
Figure F.2 presents a modified version of the Time3 class from Fig. 8.8 that contains documentation comments. In the text that follows the example, we thoroughly discuss each of the javadoc tags used in the documentation comments. We discuss how to use the javadoc tool to generate HTML documentation from this file in Section F.4.
Appendix F |
Creating HTML Documentation with javadoc (on CD) |
1371 |
|
links to packages are |
the selected Web page is |
|
|
displayed in this frame |
displayed in this frame |
|
links to classes and interfaces are displayed in this frame. Interfaces are italicized
Fig. F.1 Java API documentation.
1// Fig. F.2: Time3.java
2 // Time3 class definition with set and get methods 3 package com.deitel.jhtp4.appenF;
4
5// Java core packages
6 import java.text.DecimalFormat;
7
8/**
9 * This class maintains the time in 24-hour format.
10* @see java.lang.Object
11* @author Deitel & Associates, Inc.
12*/
13public class Time3 extends Object {
15 |
private int hour; |
// 0 - 23 |
Fig. F.2 A Java source code file containing documentation comments (part 1 of 5).
1372 |
Creating HTML Documentation with javadoc (on CD) |
Appendix F |
16 |
private |
int |
minute; |
// |
0 |
- |
59 |
17 |
private |
int |
second; |
// |
0 |
- |
59 |
18 |
|
|
|
|
|
|
|
19 |
|
|
|
|
|
|
|
20/**
21* Time3 constructor initializes each instance variable
22* to zero. Ensures that Time object starts in a
23* consistent state.
24* @throws <code>Exception</code> in the case of an invalid time
25*/
26public Time3() throws Exception
27{
28setTime( 0, 0, 0 );
29}
30
31
32/**
33* Time3 constructor: hour supplied, minute and second
34* defaulted to 0
35* @param h the hour
36* @throws <code>Exception</code> in the case of an invalid time
37*/
38public Time3( int h ) throws Exception
39{
40setTime( h, 0, 0 );
41}
42
43/**
44* Time3 constructor: hour and minute supplied, second
45* defaulted to 0
46* @param h the hour
47* @param m the minute
48* @throws <code>Exception</code> in the case of an invalid time
49*/
50public Time3( int h, int m ) throws Exception
51{
52setTime( h, m, 0 );
53}
54
55/**
56* Time3 constructor: hour, minute and second supplied
57* @param h the hour
58* @param m the minute
59* @param s the second
60* @throws <code>Exception</code> in the case of an invalid time
61*/
62public Time3( int h, int m, int s ) throws Exception
63{
64setTime( h, m, s );
65}
66
Fig. F.2 A Java source code file containing documentation comments (part 2 of 5).
Appendix F |
Creating HTML Documentation with javadoc (on CD) |
1373 |
67/**
68* Time3 constructor: another Time3 object supplied
69* @param time Time3 object
70* @throws <code>Exception</code> in the case of an invalid time
71*/
72public Time3( Time3 time ) throws Exception
73{
74setTime( time.getHour(), time.getMinute(),
75time.getSecond() );
76}
77
78// Set Methods
79/**
80* Set a new time value using universal time. Perform
81* validity checks on data. Set invalid values to zero.
82* @param h the hour
83* @param m the minute
84* @param s the second
85* @see com.deitel.jhtp4.appenF.Time3#setHour
86* @see Time3#setMinute
87* @see #setSecond
88* @throws <code>Exception</code> in the case of an invalid time
89*/
90public void setTime( int h, int m, int s ) throws Exception
91{
92 |
setHour( h ); |
// set the hour |
93setMinute( m ); // set the minute
94setSecond( s ); // set the second
95}
96
97/**
98* Sets the hour
99* @param h the hour
100* @throws Exception in the case of an invalid time
101*/
102public void setHour( int h ) throws Exception
103{
104if ( h >= 0 && h < 24 )
105hour = h;
106else
107throw new Exception();
108}
109
110/**
111* Sets the minute
112* @param m the minute
113* @throws Exception in the case of an invalid time
114*/
115public void setMinute( int m ) throws Exception
116{
117if ( m >= 0 && h < 60 )
118 |
minute = m; |
|
|
Fig. F.2 A Java source code file containing documentation comments (part 3 of 5).
1374 |
Creating HTML Documentation with javadoc (on CD) |
Appendix F |
119 else
120throw new Exception();
121}
122
123/**
124* Sets the second
125* @param m the minute
126* @throws Exception in the case of an invalid time
127*/
128public void setSecond( int s ) throws Exception
129{
130if ( s >= 0 && s < 60 )
131second = s;
132else
133throw new Exception();
134}
135
136// Get Methods
137/**
138* Gets the hour
139* @return an <code>int</code> specifying the hour.
140*/
141public int getHour()
142{
143return hour;
144}
145
146/**
147* Gets the minute
148* @return an <code>int</code> specifying the minute.
149*/
150public int getMinute()
151{
152return minute;
153}
154
155/**
156* Gets the second
157* @return an <code>int</code> specifying the second.
158*/
159public int getSecond()
160{
161return second;
162}
163
164/**
165* Convert to <code>String</code> in universal-time format
166* @return a <code>String</code> representation
167* of the time in universal-time format
168*/
169public String toUniversalString()
170{
171DecimalFormat twoDigits = new DecimalFormat( "00" );
Fig. F.2 A Java source code file containing documentation comments (part 4 of 5).
Appendix F |
Creating HTML Documentation with javadoc (on CD) |
1375 |
172
173 return twoDigits.format( getHour() ) + ":" +
174 twoDigits.format( getMinute() ) + ":" +
175twoDigits.format( getSecond() );
176}
177
178/**
179* Convert to <code>String</code> in standard-time format
180* @return a <code>String</code> representation
181* of the time in standard-time format
182*/
183public String toString()
184{
185DecimalFormat twoDigits = new DecimalFormat( "00" );
187 return ( ( getHour() == 12 || getHour() == 0 ) ? 188 12 : getHour() % 12 ) + ":" +
189 twoDigits.format( getMinute() ) + ":" +
190 twoDigits.format( getSecond() ) +
191( getHour() < 12 ? " AM" : " PM" );
192}
193}
Fig. F.2 A Java source code file containing documentation comments (part 5 of 5).
Documentation comments are placed on the line before a class definition, an interface definition, a constructor, a method and a field (i.e., an instance variable or a reference). The first documentation comment (lines 8–12) introduces class Time3. The line
* This class maintains the time in 24-hour format.
is a description of class Time3 provided by the programmer. The description can contain as many lines as necessary to provide a description of the class to any programmer who may use it. Tags @see and @author are used to specify a See Also: note and an Author: note, respectively in the HTML documentation (Fig. F.3). The See Also: note specifies other related classes that may be of interest to a programmer using this class. The @author tag specifies the author of the class. More than one @author tag can be used to document multiple authors. Note that the asterisks (*) on each line between /** and */ are not required. This is a convention used by programmers to align descriptions and javadoc tags. When parsing a documentation comment, javadoc discards all whitespace characters up to the first non-whitespace character in each line. If the first non-whitespace character encountered is an asterisk, it is also discarded.
Notice that the documentation comment in lines 8–12 immediately precedes the class definition—any code placed between the documentation comment and the class definition causes javadoc to ignore the documentation comment. This is also true of other code structures (e.g., constructors, methods, instance variables, etc.).
Common Programming Error F.1
Placing an import statement between the class comment and the class declaration is a log-
ic error. This causes the class comment to be ignored by javadoc.
1376 |
Creating HTML Documentation with javadoc (on CD) |
Appendix F |
Fig. F.3 HTML documentation for class Time3.
Software Engineering Observation F.1
Defining several fields in one comma-separated statement with a single comment above that statement, will result in javadoc using that comment for all of the fields.
The documentation comment on lines 32–37 describes one of the Time3 constructors. The tag @param describes a parameter to the method. Parameters appear in the HTML document in a Parameters: note (Fig. F.4) that is followed by a list of all parameters specified with the @param tag. For this constructor, the parameter’s name is h and its description is “the hour.” Tag @param can be used only with methods and constructors.
The tag @throws specifies the exceptions thrown by this method. Like @param tags, @throws tags are only used with methods and constructors. One @throws should be supplied for each type of exception thrown by the method.
Software Engineering Observation F.2
To produce proper javadoc documentation, you must declare every instance variable on a separate line.
Documentation comments can contain multiple @param and @see tags. The documentation comment at lines 79–89 describes method setTime. The HTML generated for this method is shown in Fig. F.5. Three @param tags describe the method’s parameters. This results in one Parameters: note which lists the three parameters. Methods setHour, setMinute and setSecond are tagged with @see to create hyperlinks to their descriptions in the HTML document. A # character is used instead of a dot when tagging a method or a field. This creates a link to the name that follows the # character. We demon-
Appendix F |
Creating HTML Documentation with javadoc (on CD) |
1377 |
strate three different ways (i.e., the fully qualified name, class name qualification and no qualification) to tag methods using @see on lines 85–87. If the fully qualified name is not given (as in lines 86–87), javadoc looks for the specified method or field in the following order: current class, superclasses, package and imported files.
Fig. F.4 The Parameters: note generated by javadoc.
Fig. F.5 HTML documentation for method setTime.
1378 |
Creating HTML Documentation with javadoc (on CD) |
Appendix F |
The only other tag used in this file is @return which specifies a Returns: note in the HTML documentation (Fig. F.6). The comment at lines 137–140 documents method getHour. Tag @return describes a method’s return type to help the programmer understand how to use the return value of the method. By javadoc convention, programmers typeset source code (i.e., keywords, identifiers, expressions, etc.) with the HTML tags
<code> and </code>.
Good Programming Practice F.1
Changing source code fonts in javadoc tags helps code names stand out from the rest of the description.
In addition to the tags presented in this example, javadoc recognizes four other tags. Figure F.7 summarizes the most commonly used tags.
Fig. F.6 HTML documentation for method getHour.
javadoc tag |
Description |
|
|
@author |
Adds a Author: note if the -author option is used when executing |
|
javadoc. |
@param |
Used to describe the parameters of methods and constructors. |
@return |
Adds a Returns: note describing a methods return type. |
@see |
Adds a See Also: note containing hyperlinks to related classes or methods. |
@throws |
Adds a Throws: note that specifies the exceptions thrown by the method. |
|
@exception is a synonym for @throws. |
@deprecated |
Adds a Deprecated note. These are notes to programmers indicating that |
|
they should not use the specified features of the class. Deprecated notes |
|
normally appear when a class has been enhanced with new and improved |
|
features, but older features are maintained for backwards compatibility. |
Fig. F.7 Common javadoc tags (part 1 of 2).
Appendix F |
Creating HTML Documentation with javadoc (on CD) |
1379 |
|
|
|
|
|
javadoc tag |
Description |
|
|
|
|
|
|
@link |
|
This allows the programmer to insert an explicit hyperlink to another HTML |
|
|
|
document. |
|
@since |
|
Adds a Since note. These notes are used for new versions of a class to indi- |
|
|
|
cate when a feature was first introduced. For example, the Java API docu- |
|
|
|
mentation uses this to indicate features that were introduced in Java 1.0, Java |
|
|
|
1.1 and Java 2. |
|
@version |
Adds a Version note. These notes help maintain version number of the soft- |
||
|
|
ware containing the class or method. |
|
|
|
|
|
Fig. F.7 |
Common javadoc tags (part 2 of 2). |
|
F.4 javadoc
In this section, we discuss how to execute the javadoc tool on a Java source file to create HTML documentation for the class in the file. Like other tools, javadoc is executed from the command line. The general form of the javadoc command is
javadoc options packages sources @files
where options is a list of command line options, packages is a list of packages the user would like to document, sources is a list of java source files to document and @files is a text file containing the names of packages and/or source files to send to the javadoc utility, so that it can create documentation for those packages and classes. The wildcard character * can be used to specify multiple sources. (e.g., c:\*.java) [Note: All items are separated by spaces and @files is one word.] Figure F.8 shows a DOS window containing the javadoc command we typed to generate the HTML documentation.
In Fig. F.8, the -d argument specifies the directory (e.g., c:\docs) where the HTML files will be stored on disk. We use the -link option so that our documentation links to Sun’s documentation. This creates a hyperlink between our documentation and Sun’s documentation (see Fig. F.5 where Java class Exception from package java.lang is hyperlinked). Without the -link argument, Exception appears as text in the HTML doc- ument—not a hyperlink. The -author argument instructs javadoc to process the @author tag (it ignores this tag by default).
F.5 Files Produced by javadoc
In the last section, we executed the javadoc tool on the Time3.java file. When javadoc executes, it displays the name of each HTML file it creates (see Fig. F.8). From the source file, javadoc created an HTML document named Time3.html for the class. If the source file contained multiple classes or interfaces, a separate HTML document is created for each class. Because class Time3 belongs to a package, the page is created in the directory C:\docs\com\deitel\jhtp4\appenF (on Win32 platforms). The c:\docs directory was specified with the -d command line option of javadoc, and the remaining directories were created based on the package statement.
1380 |
Creating HTML Documentation with javadoc (on CD) |
Appendix F |
Fig. F.8 Using the javadoc tool.
Another file that javadoc creates is index.html the starting HTML page in the documentation. To view the documentation you generate with javadoc, load index.html into your web browser. In Fig. F.9, the right frame contains the page index.html and the left frame contains the page allclasses-frame.html which contains links to the source code’s classes. [Note: Because our example does not contain multiple packages, there is no frame listing the packages. Normally this frame would appear above the left frame (containing “All Classes”) as in Fig. F.1.]
The navigation bar (at the top of the right frame in Fig. F.9) indicates which HTML page is currently loaded by highlighting the page’s link (e.g., the Class link in Fig. F.9).
Clicking the Tree link (Fig. F.10) displays a class hierarchy for all the classes displayed in the left frame. In our example, we documented only class Time3—which extends Object. Clicking the Deprecated link loads deprecated-list.html into the right frame. This page contains a list of all deprecated names. Because we did not use the @deprecated tag in this example, this page does not contain any information. Clicking the Index link loads the index-all.html page which contains an alphabetical list of all classes, interfaces, methods and fields.
Figure F.11 shows class Time3’s index-all.html page loaded into a Web browser. Clicking the Help link loads helpdoc.html (Fig. F.12). This is a help file for navigating the documentation. A default help file is provided, however the programmer can specify other help files.
Among the other files generated by javadoc are serialized-form.html which documents Serializable and Externalizable classes and package-list.txt which is used by the -link command-line argument and is not actually part of the documentation.
Appendix F |
Creating HTML Documentation with javadoc (on CD) |
1381 |
|
frames |
highlighted link |
navigation bar |
|
Fig. F.9 Class Time3’s index.html.
Fig. F.10 Tree page.
1382 |
Creating HTML Documentation with javadoc (on CD) |
Appendix F |
Fig. F.11 Time3’s index-all.html page.
Fig. F.12 Time3’s helpdoc.html page.
Appendix F Creating HTML Documentation with javadoc (on CD) 1383
TERMINOLOGY
allclasses-frame.html |
@link tag |
–author argument |
name-frame.html |
@author javadoc tag |
Overrides: note |
Class item in the navigator bar |
Parameters: note |
–d argument |
@param tag |
deprecated-list.html |
Returns: note |
@deprecated tag |
@return tag |
documentation comment |
See Also: note |
Exception note |
@see tag |
@exception tag |
serialized-form.html |
Help |
@serial tag |
helpdoc.html |
@serialData tag |
index.html |
@since tag |
index-all.html |
@throws tag |
javadoc |
Tree link |
-link argument |
@version tag |
G
Elevator Events
and Listener Interfaces
(on CD)
G.1 Introduction
In “Thinking About Objects” Section 10.22, we discussed how event handling works in our elevator simulation. We mentioned that for an object to receive an event, that object must register as a listener for that event. Therefore, the class of that object must implement an appropriate listener interface that contains methods that receive an event object as a parameter. In this section, we present the events and listener interfaces used in our simulation.
G.2 Events
The next eight figures (Fig. G.1–Fig. G.7) contain the events of the system. Each event inherits from class ElevatorModelEvent in Fig. G.1. This class contains a Location reference (line 11) that represent where the event was generated—in our simulation, this reference is the Elevator object or either Floor object. Class ElevatorModelEvent also contains an Object reference (line 14) representing the source object that generated the event. Methods getLocation (lines 30–33) and getSource (lines 42–45) return the Location and Object references, respectively. Note that each subclass of ElevatorModelEvent (Fig. G.2–Fig. G.7) provides only a constructor calling the constructor of class ElevatorModelEvent. As we mentioned in Section 10.22, dividing class ElevatorModelEvent into several subclass events makes event handling easier to understand in our simulation.
1// ElevatorModelEvent.java
2 // Basic event packet in Elevator simulation
3 package com.deitel.jhtp4.elevator.event;
4
Fig. G.1 ElevatorModelEvent superclass for events in the elevator simulation model (part 1 of 2).
Appendix G |
Elevator Events and Listener Interfaces (on CD) |
1385 |
5// Deitel packages
6 import com.deitel.jhtp4.elevator.model.*;
7
8 public class ElevatorModelEvent {
9
10// Location where ElevatorModelEvent was generated
11private Location location;
12
13// source Object that generated ElevatorModelEvent
14private Object source;
15
16// ElevatorModelEvent constructor sets Location
17public ElevatorModelEvent( Object source, Location location )
18{
19setSource( source );
20setLocation( location );
21}
22
23// set ElevatorModelEvent Location
24public void setLocation( Location eventLocation )
25{
26location = eventLocation;
27}
28
29// get ElevatorModelEvent Location
30public Location getLocation()
31{
32return location;
33}
34
35// set ElevatorModelEvent source
36private void setSource( Object eventSource )
37{
38source = eventSource;
39}
40
41// get ElevatorModelEvent source
42public Object getSource()
43{
44return source;
45}
46}
Fig. G.1 ElevatorModelEvent superclass for events in the elevator simulation model (part 2 of 2).
1// BellEvent.java
2// Indicates that Bell has rung
3 package com.deitel.jhtp4.elevator.event;
4
Fig. G.2 BellEvent ElevatorModelEvent subclass indicating that the
Bell has rung (part 1 of 2).
1386 |
Elevator Events and Listener Interfaces (on CD) |
Appendix G |
5// Deitel packages
6 import com.deitel.jhtp4.elevator.model*;
7
8 public class BellEvent extends ElevatorModelEvent {
9
10// BellEvent constructor
11public BellEvent( Object source, Location location )
12{
13super( source, location );
14}
15}
Fig. G.2 BellEvent ElevatorModelEvent subclass indicating that the
Bell has rung (part 2 of 2).
1// ButtonEvent.java
2 // Indicates that a Button has changed state
3 package com.deitel.jhtp4.elevator.event;
4
5// Deitel packages
6 import com.deitel.jhtp4.elevator.model.*;
7
8 public class ButtonEvent extends ElevatorModelEvent {
9
10// ButtonEvent constructor
11public ButtonEvent( Object source, Location location )
12{
13super( source, location );
14}
15}
Fig. G.3 ButtonEvent ElevatorModelEvent subclass indicating that a
Button has changed state.
1// DoorEvent.java
2 // Indicates that a Door has changed state
3 package com.deitel.jhtp4.elevator.event;
4
5// Deitel packages
6 import com.deitel.jhtp4.elevator.model.*;
7
8 public class DoorEvent extends ElevatorModelEvent {
9
10// DoorEvent constructor
11public DoorEvent( Object source, Location location )
12{
13super( source, location );
14}
15}
Fig. G.4 DoorEvent ElevatorModelEvent subclass indicating that a Door has changed state.
Appendix G |
Elevator Events and Listener Interfaces (on CD) |
1387 |
1// ElevatorMoveEvent.java
2 // Indicates on which Floor the Elevator arrived or departed 3 package com.deitel.jhtp4.elevator.event;
4
5// Deitel packages
6 import com.deitel.jhtp4.elevator.model.*;
7
8 public class ElevatorMoveEvent extends ElevatorModelEvent {
9
10// ElevatorMoveEvent constructor
11public ElevatorMoveEvent( Object source, Location location )
12{
13super( source, location );
14}
15}
Fig. G.5 ElevatorMoveEvent ElevatorModelEvent subclass indicating on which Floor the Elevator has either arrived or departed.
1// LightEvent.java
2 // Indicates on which Floor the Light has changed state 3 package com.deitel.jhtp4.elevator.event;
4
5// Deitel packages
6 import com.deitel.jhtp4.elevator.model.*;
7
8 public class LightEvent extends ElevatorModelEvent {
9
10// LightEvent constructor
11public LightEvent( Object source, Location location )
12{
13super( source, location );
14}
15}
Fig. G.6 LightEvent ElevatorModelEvent subclass indicating on which
Floor the Light has changed state.
Class PersonMoveEvent (Fig. G.7) has a slightly different structure than that of the other event classes. Line 11 declares int attribute ID. We will discover in Appendix I that the ElevatorView obtains this attribute through method getID (lines 22–25) to determine which Person sent the event.
1// PersonMoveEvent.java
2// Indicates that a Person has moved
3 package com.deitel.jhtp4.elevator.event;
4
5// Deitel packages
6import com.deitel.jhtp4.elevator.model.*;
Fig. G.7 PersonMoveEvent ElevatorModelEvent subclass indicating that a Person has moved (part 1 of 2).
1388 |
Elevator Events and Listener Interfaces (on CD) |
Appendix G |
7
8 public class PersonMoveEvent extends ElevatorModelEvent {
9
10// identifier of Person sending Event
11private int ID;
12
13// PersonMoveEvent constructor
14public PersonMoveEvent( Object source, Location location,
15int identifier )
16{
17super( source, location );
18ID = identifier;
19}
20
21// return identifier
22public int getID()
23{
24return( ID );
25}
26}
Fig. G.7 PersonMoveEvent ElevatorModelEvent subclass indicating that a Person has moved (part 2 of 2).
G.3 Listeners
The next eight figures (Fig. G.8–Fig. G.14) contain the listener interfaces for the elevator simulation. BellListener (Fig. G.8) provides method bellRang (lines 8), which is invoked when the Bell has rung. ButtonListener (Fig. G.9) provides methods buttonPressed (line 8) and buttonReset (line 11), which listen when a Button is pressed or reset. DoorListener (Fig. G.10) provides methods doorOpened (line 8) and doorClosed (line 11), which listen for a Door opening or closing. ElevatorMoveListener (Fig. G.11) provides methods elevatorDeparted (line 8) and elevatorArrived (line 11), which listen for Elevator departures and arrivals. LightListener (Fig. G.12) provides methods lightTurnedOn (line 8) and lightTurnedOff (line 11) that listen for Light state changes. PersonMoveListener (Fig. G.13) provides methods personCreated (line 8), personArrived
(line 11), personDeparted (line 14), personPressedButton (line 17–18), personEntered (line 21) and personExited (line 24). These methods listen for when a Person has been created, has arrived at or departed from the Elevator, pressed a Button, entered the Elevator, or exited the simulation, respectively. Lastly, ElevatorModelListener (Fig. G.14) inherits behaviors from all listener interfaces. The
ElevatorView uses interface ElevatorModelListener in Section 13.17 and Appendix I to receive events from the ElevatorModel.
1// BellListener.java
2// Method invoked when Bell has rung
3 package com.deitel.jhtp4.elevator.event;
4
Fig. G.8 Interface BellListener method when Bell has rung (part 1 of 2).
Appendix G |
Elevator Events and Listener Interfaces (on CD) |
1389 |
5 public interface BellListener {
6
7// invoked when Bell has rungs
8 public void bellRang( BellEvent bellEvent );
9}
Fig. G.8 Interface BellListener method when Bell has rung (part 2 of 2).
1// ButtonListener.java
2 // Methods invoked when Button has been either pressed or reset 3 package com.deitel.jhtp4.elevator.event;
4
5 public interface ButtonListener {
6
7// invoked when Button has been pressed
8 public void buttonPressed( ButtonEvent buttonEvent );
9
10// invoked when Button has been reset
11public void buttonReset( ButtonEvent buttonEvent );
12}
Fig. G.9 Interface ButtonListener methods when Button has been either pressed or reset.
1// DoorListener.java
2 // Methods invoked when Door has either opened or closed 3 package com.deitel.jhtp4.elevator.event;
4
5 public interface DoorListener {
6
7// invoked when Door has opened
8 public void doorOpened( DoorEvent doorEvent );
9
10// invoked when Door has closed
11public void doorClosed( DoorEvent doorEvent );
12}
Fig. G.10 Interface DoorListener methods when Door has either opened or closed.
1// ElevatorMoveListener.java
2 // Methods invoked when Elevator has either departed or arrived 3 package com.deitel.jhtp4.elevator.event;
4
5 public interface ElevatorMoveListener {
6
7// invoked when Elevator has departed
8 public void elevatorDeparted( ElevatorMoveEvent moveEvent );
9
Fig. G.11 Interface ElevatorMoveListener methods when Elevator has either departed from or arrived on a Floor (part 1 of 2).
1390 |
Elevator Events and Listener Interfaces (on CD) |
Appendix G |
10// invoked when Elevator has arrived
11public void elevatorArrived( ElevatorMoveEvent moveEvent );
12}
Fig. G.11 Interface ElevatorMoveListener methods when Elevator has either departed from or arrived on a Floor (part 2 of 2).
1// LightListener.java
2 // Methods invoked when Light has either turned on or off 3 package com.deitel.jhtp4.elevator.event;
4
5 public interface LightListener {
6
7// invoked when Light has turned on
8 public void lightTurnedOn( LightEvent lightEvent );
9
10// invoked when Light has turned off
11public void lightTurnedOff( LightEvent lightEvent );
12}
Fig. G.12 Interface LightListener method for when Light has either turned on or off.
1// PersonMoveListener.java
2// Methods invoked when Person moved
3 package com.deitel.jhtp4.elevator.event;
4
5 public interface PersonMoveListener {
6
7// invoked when Person has been instantiated in model
8 public void personCreated( PersonMoveEvent moveEvent );
9
10// invoked when Person arrived at elevator
11public void personArrived( PersonMoveEvent moveEvent );
13// invoked when Person departed from elevator
14public void personDeparted( PersonMoveEvent moveEvent );
16// invoked when Person pressed Button
17public void personPressedButton(
18PersonMoveEvent moveEvent );
19
20// invoked when Person entered Elevator
21public void personEntered( PersonMoveEvent moveEvent );
23// invoked when Person exited simulation
24public void personExited( PersonMoveEvent moveEvent );
25}
Fig. G.13 Interface PersonMoveListener methods when Person has moved.
Appendix G |
Elevator Events and Listener Interfaces (on CD) |
1391 |
1// ElevatorModelListener.java
2 // Listener for ElevatorView from ElevatorModel
3 package com.deitel.jhtp4.elevator.event;
4
5// ElevatorModelListener inherits all Listener interfaces
6 public interface ElevatorModelListener extends BellListener,
7 ButtonListener, DoorListener, ElevatorMoveListener,
8 LightListener, PersonMoveListener {
9}
Fig. G.14 Interface ElevatorModelListener allows the model to send all events to the view.
G.4 Component Diagrams Revisited
In Section 13.17, we introduced the component diagram for the elevator simulation. In our simulation, the ElevatorView and every object in the model import package event. Figure G.15 presents the component diagram for package event. Each component in package event maps to a class from Fig. G.1–Fig. G.14. According to the component diagram, ElevatorView.java of package view aggregates package event. In Java, this aggregation translates to class ElevatorView importing package event. Also according to Fig. G.15, package model aggregates package event—i.e., each component in package model contains an aggregation with all components in pacckage event. (We show all components of package model in a separate component diagram in Appendix H.) In Java, this aggregation translates to each class in package model that imports ‘package event.
This concludes the appendix on the events and listener interfaces of the elevator simulation. We hope you have found it a useful reference for the material on event handling discussed in “Thinking About Objects” Section 10.22. In the next two appendices, we implement the design for the model and the view, and we provide the component diagrams for packages model and view.
1392 |
Elevator Events and Listener Interfaces (on CD) |
Appendix G |
event
|
|
|
|
|
|
|
|
|
|
|
|
«file» |
|
|
|
«file» |
|
|
|
|
|
|
||||
|
|
|
BellEvent.java |
|
|
|
BellListener.java |
|
|
|
|
|
|
|
|
||
|
|
|
|
|
||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
«file» |
|
|
|
«file» |
|
|
|
|
|
|
|
|||
|
|
|
ButtonEvent.java |
|
|
|
ButtonListener.java |
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
«file» |
|
|
|
«file» |
|
|
|
|
|
|
|
|||
|
|
|
DoorEvent.java |
|
|
|
DoorListener.java |
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
«file» |
|
|
|
«file» |
|
|
|
|
|
|
|
|||
|
|
|
ElevatorMoveEvent.java |
|
|
|
ElevatorMoveListener.java |
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
«file» |
|
|
|
«file» |
|
|
|
|
|
|
|
|||
|
|
|
ElevatorModelEvent.java |
|
|
|
ElevatorModelListener.java |
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
«file» |
|
|
|
«file» |
|
|
|
|
|
|
|
|||
|
|
|
LightEvent.java |
|
|
|
LightListener.java |
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
«file» |
|
|
|
«file» |
|
|
|
|
|
|
|
|||
|
|
|
PersonMoveEvent.java |
|
|
|
PersonMoveListener.java |
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11
view |
|
model |
«file» |
1 |
1 |
|
||
ElevatorView.java |
|
|
Fig. G.15 Component diagram for package event.
H
Elevator Model (on CD)
H.1 Introduction
After reading the “Thinking About Objects” sections, you should have a comfortable grasp of the design process and of the UML diagrams that pertain to our simulation. This appendix presents the code for all 10 classes that collectively represent the model, and concludes the discussion of its workings. We discuss each class separately and in detail.
H.2 Class ElevatorModel
As discussed in Section 13.17, class ElevatorModel (Fig. H.1) ties together the objects that comprise the elevator simulation model. The ElevatorModel serves to send events from the model to the view. The ElevatorModel also instantiates new Persons and allows each Floor to obtain a reference to the ElevatorShaft.
1// ElevatorModel.java
2 // Elevator simulation model with ElevatorShaft and two Floors 3 package com.deitel.jhtp4.elevator.model;
4
5 // Java core packages
6 import java.util.*;
7
8// Deitel packages
9import com.deitel.jhtp4.elevator.event.*;
10 import com.deitel.jhtp4.elevator.ElevatorConstants;
11
12public class ElevatorModel implements ElevatorModelListener,
13ElevatorConstants {
14
Fig. H.1 Class ElevatorModel represents the model in our elevator simulation (part 1 of 7).
1394 |
Elevator Model (on CD) |
Appendix H |
15// declare two-Floor architecture in simulation
16private Floor firstFloor;
17private Floor secondFloor;
18
19// ElevatorShaft in simulation
20private ElevatorShaft elevatorShaft;
22// objects listening for events from ElevatorModel
23private Set personMoveListeners;
24private DoorListener doorListener;
25private ButtonListener buttonListener;
26private LightListener lightListener;
27private BellListener bellListener;
28private ElevatorMoveListener elevatorMoveListener;
30// cumulative number of people in simulation
31private int numberOfPeople = 0;
32
33// constructor instantiates ElevatorShaft and Floors
34public ElevatorModel()
35{
36// instantiate firstFloor and secondFloor objects
37firstFloor = new Floor( FIRST_FLOOR_NAME );
38secondFloor = new Floor( SECOND_FLOOR_NAME );
39
40// instantiate ElevatorShaft object
41elevatorShaft =
42 |
new ElevatorShaft( firstFloor, secondFloor ); |
43 |
|
44// give elevatorShaft reference to first and second Floor
45firstFloor.setElevatorShaft( elevatorShaft );
46secondFloor.setElevatorShaft( elevatorShaft );
47
48// register for events from ElevatorShaft
49elevatorShaft.setDoorListener( this );
50elevatorShaft.setButtonListener( this );
51elevatorShaft.addElevatorMoveListener( this );
52elevatorShaft.setLightListener( this );
53elevatorShaft.setBellListener( this );
54
55// instantiate Set for ElevatorMoveListener objects
56personMoveListeners = new HashSet( 1 );
57
58 } // end ElevatorModel constructor
59
60// return Floor with given name
61private Floor getFloor( String name )
62{
63if ( name.equals( FIRST_FLOOR_NAME ) )
64return firstFloor;
65else
66
Fig. H.1 Class ElevatorModel represents the model in our elevator simulation (part 2 of 7).
Appendix H |
Elevator Model (on CD) |
1395 |
|
|
|
|
|
67 |
|
if ( name.equals( SECOND_FLOOR_NAME ) ) |
|
68 |
|
return secondFloor; |
|
69 |
|
else |
|
70 |
|
return null; |
|
71 |
|
|
|
72 |
} // end method getFloor |
|
|
73 |
|
|
|
74// add Person to Elevator Simulator
75public void addPerson( String floorName )
76{
77// instantiate new Person and place on Floor
78Person person =
79new Person( numberOfPeople, getFloor( floorName ) );
80person.setName( Integer.toString( numberOfPeople ) );
82// register listener for Person events
83person.setPersonMoveListener( this );
85// start Person thread
86person.start();
87
88// increment number of Person objects in simulation
89numberOfPeople++;
90
91 } // end method addPerson
92
93// invoked when Elevator has departed from Floor
94public void elevatorDeparted(
95ElevatorMoveEvent moveEvent )
96{
97elevatorMoveListener.elevatorDeparted( moveEvent );
98}
99
100// invoked when Elevator has arrived at destination Floor
101public void elevatorArrived(
102ElevatorMoveEvent moveEvent )
103{
104elevatorMoveListener.elevatorArrived( moveEvent );
105}
106
107// send PersonMoveEvent to listener, depending on event type
108private void sendPersonMoveEvent(
109int eventType, PersonMoveEvent event )
110{
111Iterator iterator = personMoveListeners.iterator();
112 |
|
113 |
while ( iterator.hasNext() ) { |
114 |
|
115 |
PersonMoveListener listener = |
116 |
( PersonMoveListener ) iterator.next(); |
117 |
|
Fig. H.1 Class ElevatorModel represents the model in our elevator simulation (part 3 of 7).
1396 |
Elevator Model (on CD) |
Appendix H |
|
|
|
118 |
// send Event to this listener, depending on eventType |
|
119 |
switch ( eventType ) { |
|
120 |
|
|
121 |
// Person has been created |
|
122 |
case Person.PERSON_CREATED: |
|
123 |
listener.personCreated( event ); |
|
124 |
break; |
|
125 |
|
|
126 |
// Person arrived at Elevator |
|
127 |
case Person.PERSON_ARRIVED: |
|
128 |
listener.personArrived( event ); |
|
129 |
break; |
|
130 |
|
|
131 |
// Person entered Elevator |
|
132 |
case Person.PERSON_ENTERING_ELEVATOR: |
|
133 |
listener.personEntered( event ); |
|
134 |
break; |
|
135 |
|
|
136 |
// Person pressed Button object |
|
137 |
case Person.PERSON_PRESSING_BUTTON: |
|
138 |
listener.personPressedButton( event ); |
|
139 |
break; |
|
140 |
|
|
141 |
// Person exited Elevator |
|
142 |
case Person.PERSON_EXITING_ELEVATOR: |
|
143 |
listener.personDeparted( event ); |
|
144 |
break; |
|
145 |
|
|
146 |
// Person exited simulation |
|
147 |
case Person.PERSON_EXITED: |
|
148 |
listener.personExited( event ); |
|
149 |
break; |
|
150 |
|
|
151 |
default: |
|
152 |
break; |
|
153}
154}
155} // end method sendPersonMoveEvent
157// invoked when Person has been created in model
158public void personCreated( PersonMoveEvent moveEvent )
159{
160sendPersonMoveEvent( Person.PERSON_CREATED, moveEvent );
161}
162
163// invoked when Person has arrived at Floor's Button
164public void personArrived( PersonMoveEvent moveEvent )
165{
166sendPersonMoveEvent( Person.PERSON_ARRIVED, moveEvent );
167}
168
Fig. H.1 Class ElevatorModel represents the model in our elevator simulation (part 4 of 7).
Appendix H |
Elevator Model (on CD) |
1397 |
169// invoked when Person has pressed Button
170public void personPressedButton( PersonMoveEvent moveEvent )
171{
172sendPersonMoveEvent( Person.PERSON_PRESSING_BUTTON,
173moveEvent );
174}
175
176// invoked when Person has entered Elevator
177public void personEntered( PersonMoveEvent moveEvent )
178{
179sendPersonMoveEvent( Person.PERSON_ENTERING_ELEVATOR,
180moveEvent );
181}
182
183// invoked when Person has departed from Elevator
184public void personDeparted( PersonMoveEvent moveEvent )
185{
186sendPersonMoveEvent( Person.PERSON_EXITING_ELEVATOR,
187moveEvent );
188}
189
190// invoked when Person has exited Simulation
191public void personExited( PersonMoveEvent moveEvent )
192{
193sendPersonMoveEvent( Person.PERSON_EXITED, moveEvent );
194}
195
196// invoked when Door has opened
197public void doorOpened( DoorEvent doorEvent )
198{
199doorListener.doorOpened( doorEvent );
200}
201
202// invoked when Door has closed
203public void doorClosed( DoorEvent doorEvent )
204{
205doorListener.doorClosed( doorEvent );
206}
207
208// invoked when Button has been pressed
209public void buttonPressed( ButtonEvent buttonEvent )
210{
211buttonListener.buttonPressed( buttonEvent );
212}
213
214// invoked when Button has been reset
215public void buttonReset( ButtonEvent buttonEvent )
216{
217buttonListener.buttonReset( buttonEvent );
218}
219
Fig. H.1 Class ElevatorModel represents the model in our elevator simulation (part 5 of 7).
1398 |
Elevator Model (on CD) |
Appendix H |
220// invoked when Bell has rung
221public void bellRang( BellEvent bellEvent )
222{
223bellListener.bellRang( bellEvent );
224}
225
226// invoked when Light has turned on
227public void lightTurnedOn( LightEvent lightEvent )
228{
229lightListener.lightTurnedOn( lightEvent );
230}
231
232// invoked when Light has turned off
233public void lightTurnedOff( LightEvent lightEvent )
234{
235lightListener.lightTurnedOff( lightEvent );
236}
237
238// set listener for ElevatorModelListener
239public void setElevatorModelListener(
240ElevatorModelListener listener )
241{
242// ElevatorModelListener extends all interfaces below
243addPersonMoveListener( listener );
244setElevatorMoveListener( listener );
245setDoorListener( listener );
246setButtonListener( listener );
247setLightListener( listener );
248setBellListener( listener );
249}
250
251// set listener for PersonMoveEvents
252public void addPersonMoveListener(
253PersonMoveListener listener )
254{
255personMoveListeners.add( listener );
256}
257
258// set listener for DoorEvents
259public void setDoorListener( DoorListener listener )
260{
261doorListener = listener;
262}
263
264// set listener for ButtonEvents
265public void setButtonListener( ButtonListener listener )
266{
267buttonListener = listener;
268}
269
Fig. H.1 Class ElevatorModel represents the model in our elevator simulation (part 6 of 7).
Appendix H |
Elevator Model (on CD) |
1399 |
270// add listener for ElevatorMoveEvents
271public void setElevatorMoveListener(
272ElevatorMoveListener listener )
273{
274elevatorMoveListener = listener;
275}
276
277// set listener for LightEvents
278public void setLightListener( LightListener listener )
279{
280lightListener = listener;
281}
282
283// set listener for BellEvents
284public void setBellListener( BellListener listener )
285{
286bellListener = listener;
287}
288}
Fig. H.1 Class ElevatorModel represents the model in our elevator simulation (part 7 of 7).
The class diagram in Fig. 15.21 shows that class ElevatorModel contains one instance of class ElevatorShaft and two instances of class Floor, so ElevatorModel declares object elevatorShaft (line 20) and objects firstFloor and secondFloor (lines 16–17). Lines 37–46 instantiate these objects and give each Floor object a reference to the ElevatorShaft object. Fig. 15.21 also shows that class ElevatorModel creates Person objects. According to Fig. 15.21, class ElevatorModel contains method addPerson (lines 75–91), which creates and places a Person on the specified Floor. Line 86 of method addPerson starts the Person’s thread and line 89 increments the cumulative number of Person objects in the simulation.
As previously mentioned, class ElevatorModel sends events from the model to the view. The class declaration (lines 12–13) and lines 49–53 reveal that the ElevatorModel listens for several types of events from the ElevatorShaft—this is how the ElevatorModel receives events from the objects that comprise the model. Specifically, class ElevatorModel implements interface ElevatorModelListener, which implements all interfaces in package event. Lines 23–28 declare the listener objects to which the ElevatorModel sends the events it receives from the ElevatorShaft. As mentioned in Section 13.17, the ElevatorFrame (the application) registers the ElevatorView as a listener for events from the ElevatorModel—this is how the ElevatorModel sends events from the model to the view.
Lines 94–236 of class ElevatorModel implement all methods of interface ElevatorModelListener, and lines 239–288 provide addListener methods to register a listener (in this case, the listener is the ElevatorView) for all events. In fact, twothirds of the class devotes itself to “bubbling up” messages from the model to the view.
We presented a class diagram that showed the realizations of the elevator model in Fig. 11.27. We alter this diagram to accommodate the fact that class ElevatorModel implements all interfaces through interface ElevatorModelListener. In addition, class ElevatorShaft must implement more interfaces to receive events from class
1400 |
Elevator Model (on CD) |
Appendix H |
Elevator so that ElevatorShaft can send these events to the ElevatorModel. We present the class diagram showing all realizations for the model in Fig. H.2 and Fig. H.3—Fig. H.2 shows the relationship between the classes in the model and the listener interfaces, and Fig. H.3 shows the relationship between the listener interfaces and interface ElevatorModelListener (we could have created one class diagram showing both types of relationships, but the diagram would have been too cluttered).
Figure H.4 describes the contents of the class diagram that shows elevator model realizations. The substantial changes are that class ElevatorShaft now implements interface ElevatorMoveListener, and ElevatorModel implements interface
ElevatorModelListener, which implements all interfaces.
ElevatorModelListener |
ButtonListener |
DoorListener |
BellListener |
ElevatorModel |
|
Elevator |
|
|
|
LightListener |
ButtonListener |
DoorListener |
BellListener |
ElevatorMove- |
Listener |
DoorListener
ElevatorShaft
|
|
|
ElevatorMoveListener |
Person |
|
|
|
|
|
|
|
Door |
|
Light |
|
Bell |
|
Button |
|
|
|
|
|
|
|
Fig. H.2 Class diagram showing realizations in the elevator model (Part 1).
Appendix H |
|
|
Elevator Model (on CD) |
1401 |
||
PersonMove- |
Light- |
Button- |
Door- |
Bell- |
ElevatorMove- |
|
Listener |
Listener |
Listener |
Listener |
Listener |
Listener |
ElevatorModelListener
ElevatorModel
Fig. H.3 Class diagram showing realizations in the elevator model (Part 2).
Class |
implements Listener |
|
|
ElevatorModel |
ElevatorModelListener |
ElevatorModelListener |
PersonMoveListener |
|
ElevatorMoveListener |
|
ButtonListener |
|
DoorListener |
|
BellListener |
|
LightListener |
Door, Light, Bell, Button |
ElevatorMoveListener |
Elevator |
ButtonListener |
|
DoorListener |
|
BellListener |
ElevatorShaft |
LightListener |
|
ButtonListener |
|
DoorListener |
|
BellListener |
|
ElevatorMoveListener |
Person |
DoorListener |
Fig. H.4 Classes and implemented listener interfaces from Fig. H.2.
H.3 Classes Location and Floor
We need to represent the location of the Person in the simulation. The Person could have an int attribute describing on which Floor the Person is walking; however, the Person does not occupy either Floor when riding the Elevator. As described in “Thinking About Objects” Section 9.23, our solution is for the Person to maintain a Location reference, which references either a Floor or the Elevator, depending on the whereabouts of the Person. To implement this feature, classes Floor and Elevator extend abstract superclass Location (Fig. H.5).
1402 |
Elevator Model (on CD) |
Appendix H |
1// Location.java
2 // Abstract superclass representing location in simulation
3 package com.deitel.jhtp4.elevator.model;
4
5// Deitel packages
6 import com.deitel.jhtp4.elevator.event.*;
7
8 public abstract class Location {
9
10// name of Location
11private String locationName;
13// set name of Location
14protected void setLocationName( String name )
15{
16locationName = name;
17}
18
19// return name of Location
20public String getLocationName()
21{
22return locationName;
23}
24
25// return Button at Location
26public abstract Button getButton();
28// return Door object at Location
29public abstract Door getDoor();
30}
Fig. H.5 Location abstract superclass that represents a location in the simulation.
Location contains String locationName (line 11), which may contain either value firstFloor, secondFloor or elevator to describe the three locations the Person may occupy. Lines 26 and 29 declare abstract methods getButton and getDoor, respectively. Using these methods, a Floor returns references to objects associated with that Floor, and the Elevator returns references to the objects associated with the Elevator. The Location reference allows a Person to press a Button and to know when a Door has opened. For example, if we wish a Person to press a Button, we write
person.getLocation().getButton().pressButton();
Therefore, our use of an abstract superclass provides an alternate means for objects in our model to interact. Figure H.6 presents class Floor, a subclass of class Location. The Floor constructor (lines 15–18) takes as a String argument the value firstFloor or secondFloor to identify the Floor. Line 17 invokes method setLocationName to assign the value of this String to attribute locationName, inherited from superclass Location.
Appendix H |
Elevator Model (on CD) |
1403 |
1// Floor.java
2 // Represents a Floor located next to an ElevatorShaft 3 package com.deitel.jhtp4.elevator.model;
4
5// Deitel packages
6 import com.deitel.jhtp4.elevator.ElevatorConstants;
7
8 public class Floor extends Location
9 implements ElevatorConstants {
10
11// reference to ElevatorShaft object
12private ElevatorShaft elevatorShaft;
14// Floor constructor sets name of Floor
15public Floor( String name )
16{
17setLocationName( name );
18}
19
20// get first or second Floor Button, using Location name
21public Button getButton()
22{
23if ( getLocationName().equals( FIRST_FLOOR_NAME ) )
24return getElevatorShaft().getFirstFloorButton();
25else
26 |
|
27 |
if ( getLocationName().equals( SECOND_FLOOR_NAME ) ) |
28 |
return getElevatorShaft().getSecondFloorButton(); |
29 |
else |
30 |
|
31 |
return null; |
32 |
|
33 |
} // end method getButton |
34 |
|
35// get first or second Floor Door, using Location name
36public Door getDoor()
37{
38if ( getLocationName().equals( FIRST_FLOOR_NAME ) )
39return getElevatorShaft().getFirstFloorDoor();
40else
41 |
|
42 |
if ( getLocationName().equals( SECOND_FLOOR_NAME ) ) |
43 |
return getElevatorShaft().getSecondFloorDoor(); |
44 |
else |
45 |
|
46 |
return null; |
47 |
|
48 |
} // end method getDoor |
49 |
|
50// get ElevatorShaft reference
51public ElevatorShaft getElevatorShaft()
52{
Fig. H.6 Class Floor—a subclass of Location—represents a Floor across which a Person walks to the Elevator (part 1 of 2).
1404 |
Elevator Model (on CD) |
Appendix H |
53return elevatorShaft;
54}
55
56// set ElevatorShaft reference
57public void setElevatorShaft( ElevatorShaft shaft )
58{
59elevatorShaft = shaft;
60}
61}
Fig. H.6 Class Floor—a subclass of Location—represents a Floor across which a Person walks to the Elevator (part 2 of 2).
Class Floor provides concrete methods getButton (lines 21–33) and getDoor (lines 36–48). Methods getButton and getDoor return a Button and Door reference on either the first or second Floor, depending on which Floor returns the reference. Lastly, method getElevatorShaft (lines 51–54) returns a reference to the ElevatorShaft. We will see later how a Person uses this method, in conjunction with that Person’s Location reference, to enter the Elevator.
H.4 Class Door
The Doors are an essential part of the model, because they inform a Person when to enter and exit the Elevator—without the Doors, no Person would ride the Elevator. The collaboration diagrams of Fig. 7.20, Fig. 10.25 and Fig. 15.18 presented the collaborations among the Doors, the Elevator and the Person. Now, we provide a walkthrough of class Door (Fig. H.7).
1// Door.java
2 // Sends DoorEvents to DoorListeners when opened or closed 3 package com.deitel.jhtp4.elevator.model;
4
5 // Java core packages
6 import java.util.*;
7
8// Deitel packages
9 import com.deitel.jhtp4.elevator.event.*;
10
11 public class Door implements ElevatorMoveListener {
12
13// represent whether Door is open or closed
14private boolean open = false;
15
16// time before Door closes automatically
17public static final int AUTOMATIC_CLOSE_DELAY = 3000;
19// Set of DoorListeners
20private Set doorListeners;
Fig. H.7 Class Door, which represents a Door in the model, informs listeners when a Door has opened or closed (part 1 of 4).
Appendix H |
Elevator Model (on CD) |
1405 |
22// location where Door opened or closed
23private Location doorLocation;
24
25// Door constructor instantiates Set for DoorListeners
26public Door()
27{
28doorListeners = new HashSet( 1 );
29}
30
31// add Door listener
32public void addDoorListener( DoorListener listener )
33{
34// prevent other objects from modifying doorListeners
35synchronized( doorListeners )
36{
37doorListeners.add( listener );
38}
39}
40
41// remove Door listener
42public void removeDoorListener( DoorListener listener )
43{
44// prevent other objects from modifying doorListeners
45synchronized( doorListeners )
46{
47doorListeners.remove( listener );
48}
49}
50
51// open Door and send all listeners DoorEvent objects
52public void openDoor( Location location )
53{
54if ( !open ) {
55 |
|
56 |
open = true; |
57 |
|
58 |
// obtain iterator from Set |
59 |
Iterator iterator; |
60 |
synchronized( doorListeners ) |
61 |
{ |
62 |
iterator = new HashSet( doorListeners ).iterator(); |
63 |
} |
64 |
|
65 |
// get next DoorListener |
66 |
while ( iterator.hasNext() ) { |
67 |
DoorListener doorListener = |
68 |
( DoorListener ) iterator.next(); |
69 |
|
70 |
// send doorOpened event to this DoorListener |
71 |
doorListener.doorOpened( |
72 |
new DoorEvent( this, location ) ); |
73 |
} |
Fig. H.7 Class Door, which represents a Door in the model, informs listeners when a Door has opened or closed (part 2 of 4).
1406 |
Elevator Model (on CD) |
Appendix H |
|
|
|
74 |
|
|
75 |
doorLocation = location; |
|
76 |
|
|
77 |
// declare Thread that ensures automatic Door closing |
|
78 |
Thread closeThread = new Thread( |
|
79 |
new Runnable() { |
|
80 |
|
|
81 |
public void run() |
|
82 |
{ |
|
83 |
// close Door if open for more than 3 seconds |
|
84 |
try { |
|
85 |
Thread.sleep( AUTOMATIC_CLOSE_DELAY ); |
|
86 |
closeDoor( doorLocation ); |
|
87 |
} |
|
88 |
|
|
89 |
// handle exception if interrupted |
|
90 |
catch ( InterruptedException exception ) { |
|
91 |
exception.printStackTrace(); |
|
92 |
} |
|
93 |
} |
|
94 |
} // end anonymous inner class |
|
95 |
); |
|
96 |
|
|
97closeThread.start();
98}
99} // end method openDoor
100
101// close Door and send all listeners DoorEvent objects
102public void closeDoor( Location location )
103{
104if ( open ) {
105 |
|
106 |
open = false; |
107 |
|
108 |
// obtain iterator from Set |
109 |
Iterator iterator; |
110 |
synchronized( doorListeners ) |
111 |
{ |
112 |
iterator = new HashSet( doorListeners ).iterator(); |
113 |
} |
114 |
|
115 |
// get next DoorListener |
116 |
while ( iterator.hasNext() ) { |
117 |
DoorListener doorListener = |
118 |
( DoorListener ) iterator.next(); |
119 |
|
120 |
// send doorClosed event to this DoorListener |
121 |
doorListener.doorClosed( |
122 |
new DoorEvent( this, location ) ); |
123}
124}
125} // end method closeDoor
Fig. H.7 Class Door, which represents a Door in the model, informs listeners when a Door has opened or closed (part 3 of 4).
Appendix H |
Elevator Model (on CD) |
1407 |
126
127// return whether Door is open or closed
128public boolean isDoorOpen()
129{
130return open;
131}
132
133// invoked after Elevator has departed
134public void elevatorDeparted( ElevatorMoveEvent moveEvent ) {}
136// invoked when Elevator has arrived
137public void elevatorArrived( ElevatorMoveEvent moveEvent )
138{
139openDoor( moveEvent.getLocation() );
140}
141}
Fig. H.7 Class Door, which represents a Door in the model, informs listeners when a Door has opened or closed (part 4 of 4).
Figure 15.12 indicates that class Door contains boolean attribute open (line 14) to represent the state of the Door (open or closed). Figure 15.12 also indicates that class Door contains methods openDoor (lines 52–99) and closeDoor (lines 102–125). Method openDoor sends a doorOpened event to all registered DoorListeners (the Door passes a DoorEvent object to the doorOpened method of each registered DoorListener), and method closeDoor sends a doorClosed event to all registered DoorListeners. Set doorListeners (line 20) stores all registered DoorListeners. A
DoorListener wishing to receive DoorEvents from a Door must invoke method addDoorListener (lines 32–39); those listeners that no longer wish to be a DoorListener for that Door must invoke removeDoorListener (lines 42–49).
Line 56 of method openDoor opens the Door by setting open to true. Lines 66– 73 iterate Set doorListeners and send each object a doorOpened event. Lines 60– 63 use a synchronized block obtaining the Iterator from Set doorListeners, because a Person, at any time, can add or remove itself from this Set. If method openDoor iterates doorListeners as a Person adds or removes itself from doorListeners, the JVM throws a ConcurrentModificationException—the Person is modifying the Set as method openDoor is iterating the same Set. Method openDoor avoids this situation with the synchronized block.
Method openDoor receives as an argument a Location reference on what Floor that Door should open. Lines 71–72 send a DoorEvent using the Location reference to all registered DoorListeners. Method closeDoor sets open to false (thus closing the Door) and invokes the doorClosed method on all registered DoorListeners.
We decided in Section 15.12 to make class Door an active class, so that the Door closes itself after three seconds of being open. Lines 78–95 of method openDoor instantiate a thread that handles this responsibility. Method run (lines 81–93) puts this thread to sleep for three seconds then closes the Door. Line 97 of method openDoor starts the thread.
Lastly, according to Fig. H.2, Door implements ElevatorMoveListener. In our simulation, the Elevator invokes method elevatorDeparted (line 134) when the
1408 |
Elevator Model (on CD) |
Appendix H |
Elevator has departed and invokes method elevatorArrived (lines 137–140) when the Elevator has arrived. Method elevatorArrived calls method open- Door—the Door opens when the Elevator has arrived. Method elevatorDeparted does not perform any action. At a first glance, you may wonder why this method does not call method closeDoor. The reason is that a Door should close before the Elevator has departed so the passenger will not be injured—in our model, the Elevator calls method closeDoor before calling elevatorDeparted.
H.5 Class Button
Buttons (Fig. H.8) are important to the model as well, because they signal the Elevator to move between Floors. Figure 15.12 indicates that class Button contains boolean attribute pressed (line 14) to represent the state of the Button (pressed or reset). Figure 15.12 indicates also that class Button contains methods pressButton (lines 23–29) and resetButton (lines 32–38).
1// Button.java
2 // Sends ButtonEvents to ButtonListeners when accessed
3 package com.deitel.jhtp4.elevator.model;
4
5// Deitel packages
6 import com.deitel.jhtp4.elevator.event.*;
7
8 public class Button implements ElevatorMoveListener {
9
10// ButtonListener
11private ButtonListener buttonListener = null;
13// represent whether Button is pressed
14private boolean pressed = false;
15
16// set listener
17public void setButtonListener( ButtonListener listener )
18{
19buttonListener = listener;
20}
21
22// press Button and send ButtonEvent
23public void pressButton( Location location )
24{
25pressed = true;
26
27 buttonListener.buttonPressed(
28new ButtonEvent( this, location ) );
29}
30
31// reset Button and send ButtonEvent
32public void resetButton( Location location )
33{
34pressed = false;
Fig. H.8 Class Button, which represents a Button in the model, informs listeners when a Button has been pressed or reset (part 1 of 2).
Appendix H |
Elevator Model (on CD) |
1409 |
35
36 buttonListener.buttonReset(
37new ButtonEvent( this, location ) );
38}
39
40// return whether button is pressed
41public boolean isButtonPressed()
42{
43return pressed;
44}
45
46// invoked when Elevator has departed
47public void elevatorDeparted( ElevatorMoveEvent moveEvent ) {}
49// invoked when Elevator has arrived
50public void elevatorArrived( ElevatorMoveEvent moveEvent )
51{
52resetButton( moveEvent.getLocation() );
53}
54}
Fig. H.8 Class Button, which represents a Button in the model, informs listeners when a Button has been pressed or reset (part 2 of 2).
Method pressButton sends a buttonPressed event to the registered ButtonListener (line 11), and method resetButton sends a buttonReset event to the ButtonListener. Method setButtonListener (lines 17–20) allows an object to receive ButtonEvents by registering itself as the ButtonListener.
Line 25 of method pressButton sets attribute pressed to true, and lines 27–28 pass a ButtonEvent to method buttonPressed of the buttonListener. Line 34 of method resetButton sets attribute pressed to false and line 36–37 pass a ButtonEvent to method buttonReset of the buttonListener.
Lastly, according to Fig. H.2, classes Button implements interface ElevatorMoveListener. Method elevatorArrived (lines 50–53) calls method resetButton to reset the Button.
H.6 Class ElevatorShaft
Class ElevatorShaft (Fig. H.9) represents the ElevatorShaft in which the Elevator travels in the model. Most methods in class ElevatorShaft access private variables, listen for messages from the Elevator and send “bubble up” events to the ElevatorModel, which sends them to the ElevatorView. According to the class diagram of Fig. 15.21, class ElevatorShaft contains one Elevator object, two Button objects, two Door objects and two Light objects. The Button, Door and Light objects refer to the buttons, doors and lights on each Floor. Line 15 declares the Elevator object—elevator. Lines 18–19 declare the Buttons firstFloorButton and secondFloorButton. Lines 22–23 declare the Doors firstFloorDoor and secondFloorDoor. Lines 26–27 declare the Lights firstFloorLight and secondFloorLight. Lines 169–208 provide methods to access references to these objects.
1410 |
Elevator Model (on CD) |
Appendix H |
1// ElevatorShaft.java
2 // Represents elevator shaft, which contains elevator
3 package com.deitel.jhtp4.elevator.model;
4
5 // Java core packages
6 import java.util.*;
7
8// Deitel packages
9 import com.deitel.jhtp4.elevator.event.*;
10
11public class ElevatorShaft implements ElevatorMoveListener,
12LightListener, BellListener {
13
14// Elevator
15private Elevator elevator;
17// Buttons on Floors
18private Button firstFloorButton;
19private Button secondFloorButton;
21// Doors on Floors
22private Door firstFloorDoor;
23private Door secondFloorDoor;
25// Lights on Floors
26private Light firstFloorLight;
27private Light secondFloorLight;
29// listeners
30private DoorListener doorListener;
31private ButtonListener buttonListener;
32private LightListener lightListener;
33private BellListener bellListener;
34private Set elevatorMoveListeners;
35
36// constructor initializes aggregated components
37public ElevatorShaft( Floor firstFloor, Floor secondFloor )
38{
39// instantiate Set for ElevatorMoveListeners
40elevatorMoveListeners = new HashSet( 1 );
41
42// anonymous inner class listens for ButtonEvents
43ButtonListener floorButtonListener =
44 |
new ButtonListener() { |
|
45 |
|
|
46 |
// called when Floor Button has been pressed |
|
47 |
public void buttonPressed( ButtonEvent buttonEvent ) |
|
48 |
{ |
|
49 |
// request elevator |
move to location |
50 |
Location location = |
buttonEvent.getLocation(); |
51 |
buttonListener.buttonPressed( buttonEvent ); |
Fig. H.9 Class ElevatorShaft, which represents the ElevatorShaft, which sends events from the Elevator to the ElevatorModel (part 1 of 6).
Appendix H |
Elevator Model (on CD) |
1411 |
|
|
|
52 |
elevator.requestElevator( location ); |
|
53 |
} |
|
54 |
|
|
55 |
// called when Floor Button has been reset |
|
56 |
public void buttonReset( ButtonEvent buttonEvent ) |
|
57 |
{ |
|
58 |
buttonListener.buttonReset( buttonEvent ); |
|
59}
60}; // end anonymous inner class
62// instantiate Floor Buttons
63firstFloorButton = new Button();
64secondFloorButton = new Button();
66// register anonymous ButtonListener with Floor Buttons
67firstFloorButton.setButtonListener(
68floorButtonListener );
69secondFloorButton.setButtonListener(
70 |
floorButtonListener ); |
71 |
|
72// Floor Buttons listen for ElevatorMoveEvents
73addElevatorMoveListener( firstFloorButton );
74addElevatorMoveListener( secondFloorButton );
76// anonymous inner class listens for DoorEvents
77DoorListener floorDoorListener = new DoorListener() {
79 |
// called when Floor Door has opened |
80 |
public void doorOpened( DoorEvent doorEvent ) |
81 |
{ |
82 |
// forward event to doorListener |
83 |
doorListener.doorOpened( doorEvent ); |
84 |
} |
85 |
|
86 |
// called when Floor Door has closed |
87 |
public void doorClosed( DoorEvent doorEvent ) |
88 |
{ |
89 |
// forward event to doorListener |
90 |
doorListener.doorClosed( doorEvent ); |
91}
92}; // end anonymous inner class
94// instantiate Floor Doors
95firstFloorDoor = new Door();
96secondFloorDoor = new Door();
98// register anonymous DoorListener with Floor Doors
99firstFloorDoor.addDoorListener( floorDoorListener ); 100 secondFloorDoor.addDoorListener( floorDoorListener );
101
102// instantiate Lights, then listen for LightEvents
103firstFloorLight = new Light();
Fig. H.9 Class ElevatorShaft, which represents the ElevatorShaft, which sends events from the Elevator to the ElevatorModel (part 2 of 6).
1412 |
Elevator Model (on CD) |
Appendix H |
104addElevatorMoveListener( firstFloorLight );
105firstFloorLight.setLightListener( this );
107secondFloorLight = new Light();
108addElevatorMoveListener( secondFloorLight );
109secondFloorLight.setLightListener( this );
111// instantiate Elevator object
112elevator = new Elevator( firstFloor, secondFloor );
114// register for ElevatorMoveEvents from elevator
115elevator.addElevatorMoveListener( this );
116
117// listen for BellEvents from elevator
118elevator.setBellListener( this );
119
120// anonymous inner class listens for ButtonEvents from
121// elevator
122elevator.setButtonListener(
123 |
new ButtonListener() { |
124 |
|
125 |
// invoked when button has been pressed |
126 |
public void buttonPressed( ButtonEvent buttonEvent ) |
127 |
{ |
128 |
// send event to listener |
129 |
buttonListener.buttonPressed( buttonEvent ); |
130 |
} |
131 |
|
132 |
// invoked when button has been reset |
133 |
public void buttonReset( ButtonEvent buttonEvent ) |
134 |
{ |
135 |
// send event to listener |
136 |
buttonListener.buttonReset( |
137 |
new ButtonEvent( this, elevator ) ); |
138 |
} |
139} // end anonymous inner class
140);
141
142// anonymous inner class listens for DoorEvents from
143// elevator
144elevator.setDoorListener(
145 |
new DoorListener() { |
146 |
|
147 |
// invoked when door has opened |
148 |
public void doorOpened( DoorEvent doorEvent ) |
149 |
{ |
150 |
// send event to listener |
151 |
doorListener.doorOpened( doorEvent ); |
152 |
} |
153 |
|
Fig. H.9 Class ElevatorShaft, which represents the ElevatorShaft, which sends events from the Elevator to the ElevatorModel (part 3 of 6).
Appendix H |
Elevator Model (on CD) |
1413 |
154 |
// invoked when door has closed |
155 |
public void doorClosed( DoorEvent doorEvent ) |
156 |
{ |
157 |
// send event to listener |
158 |
doorListener.doorClosed( doorEvent ); |
159 |
} |
160} // end anonymous inner class
161);
162
163// start Elevator Thread
164elevator.start();
165
166 } // end ElevatorShaft constructor
167
168// get Elevator
169public Elevator getElevator()
170{
171return elevator;
172}
173
174// get Door on first Floor
175public Door getFirstFloorDoor()
176{
177return firstFloorDoor;
178}
179
180// get Door on second Floor
181public Door getSecondFloorDoor()
182{
183return secondFloorDoor;
184}
185
186// get Button on first Floor
187public Button getFirstFloorButton()
188{
189return firstFloorButton;
190}
191
192// get Button on second Floor
193public Button getSecondFloorButton()
194{
195return secondFloorButton;
196}
197
198// get Light on first Floor
199public Light getFirstFloorLight()
200{
201return firstFloorLight;
202}
203
Fig. H.9 Class ElevatorShaft, which represents the ElevatorShaft, which sends events from the Elevator to the ElevatorModel (part 4 of 6).
1414 |
Elevator Model (on CD) |
Appendix H |
204// get Light on second Floor
205public Light getSecondFloorLight()
206{
207return secondFloorLight;
208}
209
210// invoked when Bell rings
211public void bellRang( BellEvent bellEvent )
212{
213bellListener.bellRang( bellEvent );
214}
215
216// invoked when Light turns on
217public void lightTurnedOn( LightEvent lightEvent )
218{
219lightListener.lightTurnedOn( lightEvent );
220}
221
222// invoked when Light turns off
223public void lightTurnedOff( LightEvent lightEvent )
224{
225lightListener.lightTurnedOff( lightEvent );
226}
227
228// invoked when Elevator departs
229public void elevatorDeparted( ElevatorMoveEvent moveEvent )
230{
231Iterator iterator = elevatorMoveListeners.iterator();
233// iterate Set of ElevatorMoveEvent listeners
234while ( iterator.hasNext() ) {
235 |
|
236 |
// get respective ElevatorMoveListener from Set |
237 |
ElevatorMoveListener listener = |
238 |
( ElevatorMoveListener ) iterator.next(); |
239 |
|
240 |
// send ElevatorMoveEvent to this listener |
241listener.elevatorDeparted( moveEvent );
242}
243} // end method elevatorDeparted
244
245// invoked when Elevator arrives
246public void elevatorArrived( ElevatorMoveEvent moveEvent )
247{
248// obtain iterator from Set
249Iterator iterator = elevatorMoveListeners.iterator();
251// get next DoorListener
252while ( iterator.hasNext() ) {
Fig. H.9 Class ElevatorShaft, which represents the ElevatorShaft, which sends events from the Elevator to the ElevatorModel (part 5 of 6).
Appendix H |
|
Elevator Model (on CD) |
1415 |
|
|
|
|
254 |
// get next ElevatorMoveListener from Set |
|
|
255 |
ElevatorMoveListener listener = |
|
|
256 |
( ElevatorMoveListener |
) iterator.next(); |
|
257 |
|
|
|
258 |
// send ElevatorMoveEvent |
to this listener |
|
259 |
listener.elevatorArrived( |
moveEvent ); |
|
260 |
|
|
|
261} // end while loop
262} // end method elevatorArrived
264// set listener to DoorEvents
265public void setDoorListener( DoorListener listener )
266{
267doorListener = listener;
268}
269
270// set listener to ButtonEvents
271public void setButtonListener( ButtonListener listener )
272{
273buttonListener = listener;
274}
275
276// add listener to ElevatorMoveEvents
277public void addElevatorMoveListener(
278ElevatorMoveListener listener )
279{
280elevatorMoveListeners.add( listener );
281}
282
283// set listener to LightEvents
284public void setLightListener( LightListener listener )
285{
286lightListener = listener;
287}
288
289// set listener to BellEvents
290public void setBellListener( BellListener listener )
291{
292bellListener = listener;
293}
294}
Fig. H.9 Class ElevatorShaft, which represents the ElevatorShaft, which sends events from the Elevator to the ElevatorModel (part 6 of 6).
The main responsibility of the ElevatorShaft is to receive events from other objects then to send these events to the ElevatorModel (the ElevatorModel then sends the events to the ElevatorView, which displays the workings of the model). The ElevatorShaft contains references to several different listener objects, such as a
DoorListener, a ButtonListener, a LightListener, a BellListener and several ElevatorMoveListeners. Lines 30–34 declare these listeners—line 34 declares a Set to hold multiple ElevatorMoveListeners, because the Buttons,
Doors, Lights and the ElevatorModel are all ElevatorMoveListeners. Lines
1416 |
Elevator Model (on CD) |
Appendix H |
265–293 provide methods allowing objects to register themselves as listeners for various events.
The constructor (lines 37–166) instantiates listener objects from several inner classes— these listener objects receive events from other objects, then re-send the events to the listener objects defined in line 30–34. For example, lines 43–60 declare a ButtonListener object called floorButtonListener, which contains the logic for when a Button on a Floor has been pressed or reset. Lines 63–70 instantiate firstFloorButton and secondFloorButton, then register floorButtonListener as a ButtonListener for both Button objects. When either Button has been pressed, that Button invokes method buttonPressed (lines 47–53) of the floorButtonListener. When either Button has been reset, that Button invokes the floorButtonListener’s method buttonReset (lines 56–59). Method buttonPressed requests the Elevator by invoking the Elevator’s method requestElevator—method buttonPressed passes a Location reference of the Floor that generated the ButtonEvent. Both methods buttonPressed and buttonReset send the ButtonEvent to the ButtonListener defined in line 31 (which, in this case, is ElevatorModel).
Lines 77–92 declare a DoorListener object called floorDoorListener, which contains the logic for when a Door on a Floor has opened or closed. Lines 95–100 instantiate firstFloorDoor and secondFloorDoor, then register floorDoorListener as a DoorListener for both Door objects. When either Door has opened, that Door calls method doorOpened (lines 80–84) of the floorDoorListener. When either Door has closed, that Door calls method doorClosed (lines 87–91) of the floorDoorListener. Both methods send the DoorEvent to the DoorListener declared in line 30 (which, in this case, is ElevatorModel).
Lines 112–115 instantiate the Elevator and register the ElevatorShaft as an
ElevatorMoveListener with the Elevator. When the Elevator has departed, the Elevator invokes method elevatorDeparted (lines 229–243), which informs all objects in elevatorMoveListeners of the departure. When the Elevator has arrived, the Elevator invokes method elevatorArrived (lines 246–262), which informs all objects in elevatorMoveListeners of the arrival.
H.7 Classes Light and Bell
Class Light (Fig. H.10) represents the Lights on the Floors in the model. Objects of classes Light help decorate the view by sending events to the ElevatorView via the “bubble up” technique described previously. In our simulation, the ElevatorView turns on and off the Light in the view upon receiving a lightTurnedOn or lightTurnedOff event, respectively.
1// Light.java
2// Light turns a light on or off
3 package com.deitel.jhtp4.elevator.model;
4
5// Deitel packages
6 import com.deitel.jhtp4.elevator.event.*;
7
Fig. H.10 Class Light represents a Light on the Floor in the model (part 1 of 3).
Appendix H |
Elevator Model (on CD) |
1417 |
8 public class Light implements ElevatorMoveListener {
9
10// Light state (on/off)
11private boolean lightOn;
13// time before Light turns off automatically (3 seconds)
14public static final int AUTOMATIC_TURNOFF_DELAY = 3000;
16// LightListener listens for when Light should turn on/off
17private LightListener lightListener;
18
19// location where Light turned on or off
20private Location lightLocation;
21
22// set LightListener
23public void setLightListener( LightListener listener )
24{
25lightListener = listener;
26}
27
28// turn on Light
29public void turnOnLight( Location location )
30{
31if ( !lightOn ) {
32 |
|
33 |
lightOn = true; |
34 |
|
35 |
// send LightEvent to LightListener |
36 |
lightListener.lightTurnedOn( |
37 |
new LightEvent( this, location ) ); |
38 |
|
39 |
lightLocation = location; |
40 |
|
41 |
// declare Thread that ensures automatic Light turn off |
42 |
Thread thread = new Thread( |
43 |
new Runnable() { |
44 |
|
45 |
public void run() |
46 |
{ |
47 |
// turn off Light if on for more than 3 seconds |
48 |
try { |
49 |
Thread.sleep( AUTOMATIC_TURNOFF_DELAY ); |
50 |
turnOffLight( lightLocation ); |
51 |
} |
52 |
|
53 |
// handle exception if interrupted |
54 |
catch ( InterruptedException exception ) { |
55 |
exception.printStackTrace(); |
56 |
} |
57 |
} |
58 |
} // end anonymous inner class |
59 |
); |
60 |
|
|
|
Fig. H.10 Class Light represents a Light on the Floor in the model (part 2 of 3).
1418 |
Elevator Model (on CD) |
Appendix H |
61thread.start();
62}
63} // end method turnOnLight
65// turn off Light
66public void turnOffLight( Location location )
67{
68if ( lightOn ) {
69 |
|
70 |
lightOn = false; |
71 |
|
72 |
// send LightEvent to LightListener |
73 |
lightListener.lightTurnedOff( |
74 |
new LightEvent( this, location ) ); |
75}
76} // end method turnOffLight
78// return whether Light is on or off
79public boolean isLightOn()
80{
81return lightOn;
82}
83
84// invoked when Elevator has departed
85public void elevatorDeparted(
86ElevatorMoveEvent moveEvent )
87{
88turnOffLight( moveEvent.getLocation() );
89}
90
91// invoked when Elevator has arrived
92public void elevatorArrived(
93ElevatorMoveEvent moveEvent )
94{
95turnOnLight( moveEvent.getLocation() );
96}
97}
Fig. H.10 Class Light represents a Light on the Floor in the model (part 3 of 3).
According to Fig. 15.21, class Light contains attribute lightOn (line 11), which represents the state of the Light (on or off). In addition, Fig. 15.21 specifies that class Light contains methods turnOnLight (lines 29–63) and turnOffLight (lines 66– 76). Line 33 of method turnOnLight sets attribute lightOn to true, and lines 36–37 call method lightTurnedOn of the lightListener (line 17). In our model, the
ElevatorShaft is the lightListener—the ElevatorShaft receives events from the Light and sends them to the ElevatorModel, which sends them to the ElevatorView. The ElevatorShaft uses method setLightListener (lines 23–26) to register for LightEvents. Method turnOffLight sets attribute lightOn to false, then calls method lightTurnedOff of the lightListener.
We decided in Section 15.12 to make class Light an active class, so that the Light turns itself off after three seconds of being illuminated. Lines 42–59 of method turnOn-
Appendix H |
Elevator Model (on CD) |
1419 |
Light instantiate a thread that handles this responsibility. Method run (lines 45–57) puts this thread to sleep for three seconds, then turns off the Light. Line 61 of method turnOnLight starts the thread.
According to Fig. H.2, class Light implements interface ElevatorMoveListener. Lines 85–89 and lines 92–96 list methods elevatorDeparted and elevatorArrived, respectively. In our model, the Light turns off when the Elevator has departed, and the Light turns on when the Elevator has arrived.
Class Bell (Fig. H.11) represents the Bell in the model and sends a bellRang event to a BellListener when the Bell has rung. This event eventually “bubbles up” to the ElevatorView. The ElevatorView plays an audio clip of a bell ringing upon receiving a bellRang event.
1// Bell.java
2// Represents Bell in simulation
3 package com.deitel.jhtp4.elevator.model;
4
5// Deitel packages
6 import com.deitel.jhtp4.elevator.event.*;
7
8 public class Bell implements ElevatorMoveListener {
9
10// BellListener listens for BellEvent object
11private BellListener bellListener;
12
13// ring bell and send BellEvent object to listener
14private void ringBell( Location location )
15{
16if ( bellListener != null )
17 |
bellListener.bellRang( |
18 |
new BellEvent( this, location ) ); |
19 |
} |
20 |
|
21// set BellListener
22public void setBellListener( BellListener listener )
23{
24bellListener = listener;
25}
26
27// invoked when Elevator has departed
28public void elevatorDeparted( ElevatorMoveEvent moveEvent ) {}
30// invoked when Elevator has arrived
31public void elevatorArrived( ElevatorMoveEvent moveEvent )
32{
33ringBell( moveEvent.getLocation() );
34}
35}
Fig. H.11 Class Bell represents the Bell in the model.
1420 |
Elevator Model (on CD) |
Appendix H |
According to Fig. 15.21, class Bell does not contain attributes, because the Bell does not change state. However, Fig. 15.21 specifies that class Bell contains method ringBell (lines 14–19), which rings the Bell by invoking method bellRang of the BellListener bellListener (line 11). In our simulation, the Elevator is the bellListener—the Elevator receives event from the Bell, then sends the event to the ElevatorShaft, which sends the event to the ElevatorModel, which sends the event to the ElevatorView. The ElevatorView then plays an audio clip of a bell ringing. The Elevator uses method setBellListener (lines 22–24) to register for
BellEvents from the Bell.
According to Fig. H.2, class Bell implements interface ElevatorMoveListener. Line 28 and lines 31–34 list methods elevatorDeparted and elevatorArrived, respectively. In our simulation, the Bell rings when the Elevator has arrived.
H.8 Class Elevator
Class Elevator (Fig. H.12) represents the elevator car that travels between the two Floors in the ElevatorShaft while carrying a Person. According to the class diagram of Fig. 15.21, class Elevator contains one object each of classes Button, Door and Bell—lines 37–39 declare objects elevatorButton, elevatorDoor and bell. As discussed in Section 9.23, class Elevator extends superclass Location, because the Elevator is a location that the Person can occupy. Class Elevator implements methods getButton (lines 232–235) and getDoor (lines 238–241) provided by class Location. Method getButton returns the elevatorButton and method getDoor returns the elevatorDoor. According to Fig. 15.21, we also must include two Location objects—one named currentFloor (line 22), which represents the current Floor being serviced, and the other named destinationFloor (line 25), which represents the Floor at which the Elevator will arrive. In addition, Fig. 15.21 specifies that class Elevator requires boolean variable moving (line 19), which describes whether the Elevator is moving or idle, and boolean variable summoned (line 28), which describes whether the Elevator has been summoned. Also, class Elevator uses int constant TRAVEL_TIME (line 44), which indicates the five second travel time between Floors.
1// Elevator.java
2 // Travels between Floors in the ElevatorShaft
3 package com.deitel.jhtp4.elevator.model;
4
5 // Java core packages
6 import java.util.*;
7
8// Deitel packages
9import com.deitel.jhtp4.elevator.event.*;
10 import com.deitel.jhtp4.elevator.ElevatorConstants;
11
12public class Elevator extends Location implements Runnable,
13BellListener, ElevatorConstants {
Fig. H.12 Class Elevator represents the Elevator traveling between two Floors, operating asynchronously with other objects (part 1 of 9).
Appendix H |
Elevator Model (on CD) |
1421 |
14
15// manages Elevator thread
16private boolean elevatorRunning = false;
18// describes Elevator state (idle or moving)
19private boolean moving = false;
20
21// current Floor
22private Location currentFloorLocation;
24// destination Floor
25private Location destinationFloorLocation;
27// Elevator needs to service other Floor
28private boolean summoned;
29
30// listener objects
31private Set elevatorMoveListeners;
32private ButtonListener elevatorButtonListener;
33private DoorListener elevatorDoorListener;
34private BellListener bellListener;
35
36// Door, Button and Bell on Elevator
37private Door elevatorDoor;
38private Button elevatorButton;
39private Bell bell;
40
41 public static final int ONE_SECOND = 1000;
42
43// time needed to travel between Floors (5 seconds)
44private static final int TRAVEL_TIME = 5 * ONE_SECOND;
46// max travel time for Elevator (20 minutes)
47private static final int MAX_TRAVEL_TIME =
4820 * 60 * ONE_SECOND;
49
50// Elevator's thread to handle asynchronous movement
51private Thread thread;
52
53// constructor creates variables; registers for ButtonEvents
54public Elevator( Floor firstFloor, Floor secondFloor )
55{
56setLocationName( ELEVATOR_NAME );
57
58// instantiate Elevator's Door, Button and Bell
59elevatorDoor = new Door();
60elevatorButton = new Button();
61bell = new Bell();
62
63// register Elevator for BellEvents
64bell.setBellListener( this );
65
Fig. H.12 Class Elevator represents the Elevator traveling between two Floors, operating asynchronously with other objects (part 2 of 9).
1422 |
Elevator Model (on CD) |
Appendix H |
66// instantiate listener Set
67elevatorMoveListeners = new HashSet( 1 );
69// start Elevator on first Floor
70currentFloorLocation = firstFloor;
71destinationFloorLocation = secondFloor;
73// register elevatorButton for ElevatorMoveEvents
74addElevatorMoveListener( elevatorButton );
75
76// register elevatorDoor for ElevatorMoveEvents
77addElevatorMoveListener( elevatorDoor );
78
79// register bell for ElevatorMoveEvents
80addElevatorMoveListener( bell );
81
82// anonymous inner class listens for ButtonEvents from
83// elevatorButton
84elevatorButton.setButtonListener(
85 |
new ButtonListener() { |
86 |
|
87 |
// invoked when elevatorButton has been pressed |
88 |
public void buttonPressed( ButtonEvent buttonEvent ) |
89 |
{ |
90 |
// send ButtonEvent to listener |
91 |
elevatorButtonListener.buttonPressed( |
92 |
buttonEvent ); |
93 |
|
94 |
// start moving Elevator to destination Floor |
95 |
setMoving( true ); |
96 |
} |
97 |
|
98 |
// invoked when elevatorButton has been reset |
99 |
public void buttonReset( ButtonEvent buttonEvent ) |
100 |
{ |
101 |
// send ButtonEvent to listener |
102 |
elevatorButtonListener.buttonReset( |
103 |
buttonEvent ); |
104 |
} |
105} // end anonymous inner class
106);
107
108// anonymous inner class listens for DoorEvents from
109// elevatorDoor
110elevatorDoor.addDoorListener(
111 |
new DoorListener() { |
112 |
|
113 |
// invoked when elevatorDoor has opened |
114 |
public void doorOpened( DoorEvent doorEvent ) |
115 |
{ |
116 |
// get Location associated with DoorEvent |
117 |
Location location = doorEvent.getLocation(); |
Fig. H.12 Class Elevator represents the Elevator traveling between two Floors, operating asynchronously with other objects (part 3 of 9).
Appendix H |
Elevator Model (on CD) |
1423 |
118 |
String locationName = location.getLocationName(); |
|
|
119 |
|
120 |
// open Door on Floor Location |
121 |
if ( !locationName.equals( ELEVATOR_NAME ) ) |
122 |
location.getDoor().openDoor( location ); |
123 |
|
124 |
// send DoorEvent to listener |
125 |
elevatorDoorListener.doorOpened( new DoorEvent( |
126 |
doorEvent.getSource(), Elevator.this )); |
127 |
} |
128 |
|
129 |
// invoked when elevatorDoor has closed |
130 |
public void doorClosed( DoorEvent doorEvent ) |
131 |
{ |
132 |
// get Location associated with DoorEvent |
133 |
Location location = doorEvent.getLocation(); |
134 |
String locationName = location.getLocationName(); |
135 |
|
136 |
// close Door on Floor Location |
137 |
if ( !locationName.equals( ELEVATOR_NAME ) ) |
138 |
location.getDoor().closeDoor( location ); |
139 |
|
140 |
// send DoorEvent to listener |
141 |
elevatorDoorListener.doorClosed( new DoorEvent( |
142 |
doorEvent.getSource(), Elevator.this )); |
143 |
} |
144} // end anonymous inner class
145);
146} // end Elevator constructor
147
148// swaps current Floor Location with opposite Floor Location
149private void changeFloors()
150{
151Location location = currentFloorLocation;
152currentFloorLocation = destinationFloorLocation;
153destinationFloorLocation = location;
154}
155
156// start Elevator thread
157public void start()
158{
159if ( thread == null )
160 thread = new Thread( this );
161
162elevatorRunning = true;
163thread.start();
164}
165
Fig. H.12 Class Elevator represents the Elevator traveling between two Floors, operating asynchronously with other objects (part 4 of 9).
1424 |
Elevator Model (on CD) |
Appendix H |
166// stop Elevator thread; method run terminates
167public void stopElevator()
168{
169elevatorRunning = false;
170}
171
172// Elevator thread's run method
173public void run()
174{
175while ( isElevatorRunning() ) {
177 |
// remain idle until awoken |
178 |
while ( !isMoving() ) |
179 |
pauseThread( 10 ); |
180 |
|
181 |
// close elevatorDoor |
182 |
getDoor().closeDoor( currentFloorLocation ); |
183 |
|
184 |
// closing Door takes one second |
185 |
pauseThread( ONE_SECOND ); |
186 |
|
187 |
// issue elevatorDeparted Event |
188 |
sendDepartureEvent( currentFloorLocation ); |
189 |
|
190 |
// Elevator needs 5 seconds to travel |
191 |
pauseThread( TRAVEL_TIME ); |
192 |
|
193 |
// stop Elevator |
194 |
setMoving( false ); |
195 |
|
196 |
// swap Floor Locations |
197 |
changeFloors(); |
198 |
|
199 |
// issue elevatorArrived Event |
200 |
sendArrivalEvent( currentFloorLocation ); |
201 |
|
202 |
} // end while loop |
203 |
|
204 |
} // end method run |
205 |
|
206// invoked when Person rides Elevator between Floors
207public synchronized void ride()
208{
209try {
210Thread.sleep( MAX_TRAVEL_TIME );
211}
212catch ( InterruptedException exception ) {
213 // method doorOpened in Person interrupts method sleep;
214// Person has finished riding Elevator
215}
216}
217
Fig. H.12 Class Elevator represents the Elevator traveling between two Floors, operating asynchronously with other objects (part 5 of 9).
Appendix H |
Elevator Model (on CD) |
1425 |
218// pause concurrent thread for number of milliseconds
219private void pauseThread( int milliseconds )
220{
221try {
222Thread.sleep( milliseconds );
223}
224
225// handle if interrupted while sleeping
226catch ( InterruptedException exception ) {
227exception.printStackTrace();
228}
229} // end method pauseThread
230
231// return Button on Elevator
232public Button getButton()
233{
234return elevatorButton;
235}
236
237// return Door on Elevator
238public Door getDoor()
239{
240return elevatorDoor;
241}
242
243// set if Elevator should move
244public void setMoving( boolean elevatorMoving )
245{
246moving = elevatorMoving;
247}
248
249// is Elevator moving?
250public boolean isMoving()
251{
252return moving;
253}
254
255// is Elevator thread running?
256private boolean isElevatorRunning()
257{
258return elevatorRunning;
259}
260
261// register ElevatorMoveListener for ElevatorMoveEvents
262public void addElevatorMoveListener(
263ElevatorMoveListener listener )
264{
265elevatorMoveListeners.add( listener );
266}
267
Fig. H.12 Class Elevator represents the Elevator traveling between two Floors, operating asynchronously with other objects (part 6 of 9).
1426 |
Elevator Model (on CD) |
Appendix H |
268// register ButtonListener for ButtonEvents
269public void setButtonListener( ButtonListener listener )
270{
271elevatorButtonListener = listener;
272}
273
274// register DoorListener for DoorEvents
275public void setDoorListener( DoorListener listener )
276{
277elevatorDoorListener = listener;
278}
279
280// register BellListener fpr BellEvents
281public void setBellListener( BellListener listener )
282{
283bellListener = listener;
284}
285
286// notify all ElevatorMoveListeners of arrival
287private void sendArrivalEvent( Location location )
288{
289// obtain iterator from Set
290Iterator iterator = elevatorMoveListeners.iterator();
292// get next DoorListener
293while ( iterator.hasNext() ) {
295 |
// get next ElevatorMoveListener from Set |
296 |
ElevatorMoveListener listener = |
297 |
( ElevatorMoveListener ) iterator.next(); |
298 |
|
299 |
// send event to listener |
300 |
listener.elevatorArrived( new |
301 |
ElevatorMoveEvent( this, location ) ); |
302 |
|
303 |
} // end while loop |
304 |
|
305// service queued request, if one exists
306if ( summoned ) {
307 pauseThread( Door.AUTOMATIC_CLOSE_DELAY );
308setMoving( true ); // start moving Elevator
309}
310
311 summoned = false; // request has been serviced
312
313 } // end method sendArrivalEvent
314
315// notify all ElevatorMoveListeners of departure
316private void sendDepartureEvent( Location location )
317{
318// obtain iterator from Set
319Iterator iterator = elevatorMoveListeners.iterator();
Fig. H.12 Class Elevator represents the Elevator traveling between two Floors, operating asynchronously with other objects (part 7 of 9).
Appendix H |
Elevator Model (on CD) |
1427 |
320
321// get next DoorListener
322while ( iterator.hasNext() ) {
324 |
// get next ElevatorMoveListener from Set |
325 |
ElevatorMoveListener listener = |
326 |
( ElevatorMoveListener ) iterator.next(); |
327 |
|
328 |
// send ElevatorMoveEvent to this listener |
329 |
listener.elevatorDeparted( new ElevatorMoveEvent( |
330 |
this, currentFloorLocation ) ); |
331 |
|
332} // end while loop
333} // end method sendDepartureEvent
335// request Elevator
336public void requestElevator( Location location )
337{
338// if Elevator is idle
339if ( !isMoving() ) {
340 |
|
341 |
// if Elevator is on same Floor of request |
342 |
if ( location == currentFloorLocation ) |
343 |
|
344 |
// Elevator has already arrived; send arrival event |
345 |
sendArrivalEvent( currentFloorLocation ); |
346 |
|
347 |
// if Elevator is on opposite Floor of request |
348 |
else { |
349 |
|
350 |
if ( getDoor().isDoorOpen() ) |
351 |
pauseThread( Door.AUTOMATIC_CLOSE_DELAY ); |
352 |
setMoving( true ); // move to other Floor |
353}
354}
355else // if Elevator is moving
357 // if Elevator departed from same Floor as request 358 if ( location == currentFloorLocation )
359 summoned = true;
360
361 // if Elevator is traveling to Floor of request, 362 // continue traveling
363
364 } // end method requestElevator
365
366// invoked when bell has rung
367public void bellRang( BellEvent bellEvent )
368{
369// send event to bellListener
370if ( bellListener != null )
371 bellListener.bellRang( bellEvent );
Fig. H.12 Class Elevator represents the Elevator traveling between two Floors, operating asynchronously with other objects (part 8 of 9).
1428 |
Elevator Model (on CD) |
Appendix H |
372}
373}
Fig. H.12 Class Elevator represents the Elevator traveling between two Floors, operating asynchronously with other objects (part 9 of 9).
According to Fig. H.2, class Elevator implements interfaces ButtonListener,
DoorListener and BellListener and therefore can listen for ButtonEvents,
DoorEvents and BellEvents. Class Elevator must send these events to a listener (in this case, the ElevatorShaft), so that these events can “bubble up” to the ElevatorView. Class Elevator contains a ButtonListener called elevatorButtonListener (line 32), a DoorListener called elevatorDoorListener (line 33) and a BellListener called bellListener (line 34). Lines 269–284 list methods setButtonListener, setDoorListener and setBellListener that allow an object—such as ElevatorShaft—to register as a listener for these events.
Class Elevator contains an anonymous ButtonListener (lines 84–106) that registers for ButtonEvents from the elevatorButton. When a Person has pressed the elevatorButton, the ButtonListener calls method buttonPressed (lines 88– 96) of the ButtonListener. Lines 91–92 of this method call method buttonPressed of the elevatorButtonListener, and line 95 informs the Elevator to move using method setMoving. When the Button has been reset, the ButtonListener calls method buttonReset (lines 99–104) of the ButtonListener. Lines 102–103 of this method calls method buttonReset of the elevatorButtonListener.
Class Elevator contains an anonymous DoorListener (lines 110–145) that registers for DoorEvents from the elevatorDoor. When the elevatorDoor has opened, the DoorListener calls method doorOpened (lines 114–127) of this DoorListener. Lines 121–122 open the Door on the Floor that generated the event, and lines 125–126 call method doorOpened of the elevatorDoorListener. Method doorOpened guarantees that the Door on the Floor opens before the passenger exits the Elevator. When the elevatorDoor has closed, the DoorListener calls method doorClosed (lines 130–143) of the DoorListener. Lines 137–138 close the Door on the Floor that generated the event, and lines 141–142 call method doorClosed of the elevatorDoorListener.
Class Elevator acts as a thread because it implements interface Runnable. Method run (lines 173–204) handles the travel between Floors. The method begins with the Elevator remaining idle in a while loop (lines 178–179). The loop exits when method buttonPressed in the anonymous ButtonListener calls method setMoving.
When the Elevator exits the loop, the Elevator closes the elevatorDoor (line 182) then calls private method sendDepartureEvent (lines 316–333), to inform all listeners—the elevatorButton, the elevatorDoor, the bell and the
ElevatorShaft—of the Elevator’s departure. Class Elevator contains Set elevatorMoveListeners (line 31), which stores all registered ElevatorMoveListeners. Objects wishing to receive ElevatorMoveEvents from the Elevator must call method addElevatorMoveListener (lines 262–266), which appends that object to elevatorMoveListeners. Method sendDepartureEvent invokes method elevatorDeparted of each listener object in Set elevatorMoveListeners.
Appendix H |
Elevator Model (on CD) |
1429 |
Line 191 of method run allows the Elevator to travel to the Floor by calling method pauseThread (lines 219–229)—this simulates travel by invoking method sleep of class Thread. The Elevator stops moving when its thread awakens after five seconds. Line 197 calls private method changeFloors (lines 149–154), which swaps currentFloorLocation and destinationFloorLocation. Line 200 calls private method sendArrivalEvent (lines 287–313), which invokes method elevatorArrived of all listeners in Set elevatorMoveListeners. Lines 306– 309 of method sendArrivalEvent service any queued request (e.g., a Person pressed a Button on the Floor from which the Elevator has departed). If a queued request exists, line 308 invokes method setMoving to move the Elevator to the opposite Floor.
Method requestElevator (lines 336–364) requests the Elevator and generates a queued request. In our model, the ButtonListener defined in the inner class of the ElevatorShaft calls this method when a Button on either Floor has been pressed. The activity diagram of Fig. 5.30 specifies the logic for method requestElevator. If the Elevator is idle and on the same Floor as the Floor of the request, line 345 calls method sendArrivalEvent, because the Elevator has already arrived. If the Elevator is idle but on the opposite Floor from the Floor of the request, line 352 moves the Elevator to the opposite Floor. If the Elevator is traveling to the Floor that generated the request, the Elevator should continue traveling to that Floor. If the Elevator is traveling away from the Floor that generated the request, the Elevator must remember to return to that Floor (lines 358–359).
Lastly, as mentioned in Section 15.12, class Elevator contains synchronized method ride (lines 207–216). The Person calls this method to guarantee exclusivity with the Elevator. Method ride ensures that two Person objects cannot occupy the Elevator at the same time. When a Person object invokes method ride, that Person object obtains a monitor on the Elevator object. Other objects may not access the Elevator until that Person releases the monitor by exiting method ride.
H.9 Class Person
Class Person (Fig. H.13) represents a Person that walks across the Floors and rides the Elevator in our simulation. According to the class diagram of Fig. 15.21, class Person contains one object of class Location (line 20) that represents the Person’s current location in the model (either on a Floor or in the Elevator). In addition, Fig. 15.21 specifies that Person requires int attribute ID (line 14) as a unique identifier and boolean attribute moving (line 17), which indicates whether Person is walking across the Floor or waiting for a Door to open.
1// Person.java
2// Person riding the elevator
3 package com.deitel.jhtp4.elevator.model;
4
5 // Java core packages
6import java.util.*;
Fig. H.13 Class Person represents the Person that rides the Elevator. The Person operates asynchronously with other objects (part 1 of 7).
1430 |
Elevator Model (on CD) |
Appendix H |
7
8// Deitel packages
9 import com.deitel.jhtp4.elevator.event.*;
10
11 public class Person extends Thread implements DoorListener {
12
13// identification number
14private int ID = -1;
15
16// represents whether Person is moving or waiting
17private boolean moving;
18
19// reference to Location (either on Floor or in Elevator)
20private Location location;
21
22// listener object for PersonMoveEvents
23private PersonMoveListener personMoveListener;
25// time in milliseconds to walk to Button on Floor
26private static final int TIME_TO_WALK = 3000;
27
28// maximum time Person will wait for Elevator (10 minutes)
29private static final int TIME_WAITING = 10 * 60 * 1000;
30
31// types of messages Person may send
32public static final int PERSON_CREATED = 1;
33public static final int PERSON_ARRIVED = 2;
34public static final int PERSON_ENTERING_ELEVATOR = 3;
35public static final int PERSON_PRESSING_BUTTON = 4;
36public static final int PERSON_EXITING_ELEVATOR = 5;
37public static final int PERSON_EXITED = 6;
38
39// Person constructor set initial location
40public Person( int identifier, Location initialLocation )
41{
42super();
43
44ID = identifier; // assign unique identifier
45location = initialLocation; // set Floor Location
46moving = true; // start moving toward Button on Floor
47}
48
49// set listener for PersonMoveEvents
50public void setPersonMoveListener(
51PersonMoveListener listener )
52{
53personMoveListener = listener;
54}
55
56// invoked when Door has opened
57public void doorOpened( DoorEvent doorEvent )
58{
Fig. H.13 Class Person represents the Person that rides the Elevator. The Person operates asynchronously with other objects (part 2 of 7).
Appendix H |
Elevator Model (on CD) |
1431 |
59// set Person on Floor where Door opened
60setLocation( doorEvent.getLocation() );
62// interrupt Person's sleep method in run method and
63// Elevator's ride method
64interrupt();
65}
66
67// invoked when Door has closed
68public void doorClosed( DoorEvent doorEvent ) {}
70// set Person Location
71private void setLocation( Location newLocation )
72{
73location = newLocation;
74}
75
76// get current Location
77private Location getLocation()
78{
79return location;
80}
81
82// get identifier
83public int getID()
84{
85return ID;
86}
87
88// set if Person should move
89public void setMoving( boolean personMoving )
90{
91moving = personMoving;
92}
93
94// get if Person should move
95public boolean isMoving()
96{
97return moving;
98}
99
100// Person either rides or waits for Elevator
101public void run()
102{
103sendPersonMoveEvent( PERSON_CREATED );
105// walk to Elevator
106pauseThread( TIME_TO_WALK );
107setMoving( false );
108
109// Person arrived at Floor Button
110sendPersonMoveEvent( PERSON_ARRIVED );
Fig. H.13 Class Person represents the Person that rides the Elevator. The Person operates asynchronously with other objects (part 3 of 7).
1432 |
Elevator Model (on CD) |
Appendix H |
111
112// get current Door on Floor
113Door currentFloorDoor = location.getDoor();
115// determine if Door on Floor is open
116try {
117 |
|
118 |
boolean doorOpen = currentFloorDoor.isDoorOpen(); |
119 |
|
120 |
// if Door on Floor is closed |
121 |
if ( !doorOpen ) { |
122 |
|
123 |
// press Floor Button |
124 |
sendPersonMoveEvent( PERSON_PRESSING_BUTTON ); |
125 |
pauseThread( 1000 ); |
126 |
|
127 |
// register for Floor Door's doorOpen event |
128 |
currentFloorDoor.addDoorListener( this ); |
129 |
|
130 |
// press Floor's Button to request Elevator |
131 |
Button floorButton = getLocation().getButton(); |
132 |
floorButton.pressButton( getLocation() ); |
133 |
|
134 |
// wait for Floor's Door to open |
135 |
sleep( TIME_WAITING ); |
136 |
|
137 |
// unregister with Floor's Door if too long |
138 |
currentFloorDoor.removeDoorListener( this ); |
139 |
} |
140 |
|
141 |
// if Door on Floor is open, ride Eelevator |
142 |
else |
143enterAndRideElevator();
144}
145
146// handle exception when interrupted from waiting
147catch ( InterruptedException interruptedException ) {
149 // Person unregisters for Floor's Door doorOpen event
150 currentFloorDoor.removeDoorListener( this );
151
152 // enter and ride Elevator when Door on Floor opens, 153 pauseThread( 1000 );
154enterAndRideElevator();
155}
156
157// waiting for Elevator's Door to open takes a second
158pauseThread( 1000 );
159
160// begin walking away from Elevator
161setMoving( true );
162
Fig. H.13 Class Person represents the Person that rides the Elevator. The Person operates asynchronously with other objects (part 4 of 7).
Appendix H |
Elevator Model (on CD) |
1433 |
163// Person exits Elevator
164sendPersonMoveEvent( PERSON_EXITING_ELEVATOR );
166// walking from elevator takes five seconds
167pauseThread( 2 * TIME_TO_WALK );
168
169// Person exits simulation
170sendPersonMoveEvent( PERSON_EXITED );
172 } // end method run
173
174// Person enters Elevator
175private void enterAndRideElevator()
176{
177// Person enters Elevator
178sendPersonMoveEvent( PERSON_ENTERING_ELEVATOR );
180// set Person Location to Elevator
181Floor floorLocation = ( Floor ) getLocation();
182setLocation(
183 floorLocation.getElevatorShaft().getElevator() );
184
185// Person takes one second to enter Elevator
186pauseThread( 1000 );
187
188// register for Elevator's Door's doorOpen event
189Door elevatorDoor = getLocation().getDoor();
190elevatorDoor.addDoorListener( this );
191
192// pressing Elevator Button takes one second
193sendPersonMoveEvent( PERSON_PRESSING_BUTTON );
194pauseThread( 1000 );
195
196// get Elevator's Button
197Button elevatorButton = getLocation().getButton();
199// press Elevator's Button
200elevatorButton.pressButton( location );
202// Door closing takes one second
203pauseThread( 1000 );
204
205// ride in Elevator
206Elevator elevator = ( Elevator ) getLocation();
207elevator.ride();
208
209 // Person finished riding Elevator
210
211// unregister for Elevator's Door's doorOpen event
212elevatorDoor.removeDoorListener( this );
213
214 } // end method enterAndRideElevator
Fig. H.13 Class Person represents the Person that rides the Elevator. The Person operates asynchronously with other objects (part 5 of 7).
1434 |
Elevator Model (on CD) |
Appendix H |
215
216// pause thread for desired number of milliseconds
217private void pauseThread( int milliseconds )
218{
219try {
220sleep( milliseconds );
221}
222
223// handle exception if interrupted when paused
224catch ( InterruptedException interruptedException ) {
225interruptedException.printStackTrace();
226}
227} // end method pauseThread
228
229// send PersonMoveEvent to listener, depending on event type
230private void sendPersonMoveEvent( int eventType )
231{
232// create new event
233PersonMoveEvent event =
234 new PersonMoveEvent( this, getLocation(), getID() );
235
236// send Event to this listener, depending on eventType
237switch ( eventType ) {
238 |
|
|
239 |
// Person |
has been created |
240 |
case PERSON_CREATED: |
|
241 |
personMoveListener.personCreated( event ); |
|
242 |
break; |
|
243 |
|
|
244 |
// Person |
arrived at Elevator |
245 |
case PERSON_ARRIVED: |
|
246 |
personMoveListener.personArrived( event ); |
|
247 |
break; |
|
248 |
|
|
249 |
// Person |
entered Elevator |
250 |
case PERSON_ENTERING_ELEVATOR: |
|
251 |
personMoveListener.personEntered( event ); |
|
252 |
break; |
|
253 |
|
|
254 |
// Person |
pressed Button object |
255 |
case PERSON_PRESSING_BUTTON: |
|
256 |
personMoveListener.personPressedButton( event ); |
|
257 |
break; |
|
258 |
|
|
259 |
// Person |
exited Elevator |
260 |
case PERSON_EXITING_ELEVATOR: |
|
261 |
personMoveListener.personDeparted( event ); |
|
262 |
break; |
|
263 |
|
|
264 |
// Person |
exited simulation |
265 |
case PERSON_EXITED: |
|
266 |
personMoveListener.personExited( event ); |
|
|
|
|
Fig. H.13 Class Person represents the Person that rides the Elevator. The Person operates asynchronously with other objects (part 6 of 7).
Appendix H |
Elevator Model (on CD) |
1435 |
|
|
|
267 |
break; |
|
268 |
|
|
269 |
default: |
|
270break;
271}
272} // end method sendPersonMoveEvent
273}
Fig. H.13 Class Person represents the Person that rides the Elevator. The Person operates asynchronously with other objects (part 7 of 7).
Class Person is subclass of class Thread. The Person performs all actions, such as walking across Floors and riding the Elevator, in method run (lines 101–172). Method run represents the lifetime of a Person described in the sequence diagram of Fig. 15.20. Class Person contains a PersonMoveListener object (line 23) to which the Person sends PersonMoveEvents. In our simulation, the ElevatorModel uses method setPersonMoveListener (lines 50–54) to register itself as the PersonMoveListener. The ElevatorModel, upon receiving a PersonMoveEvent, sends the event to the ElevatorView—therefore, the ElevatorView “knows” when a Person has performed certain actions discussed momentarily.
There are several types of actions a Person performs in its lifetime, so there exists several types of PersonMoveEvents that a Person may send to the personMoveListener. Lines 32–37 define a series of constants in which each constant represents a unique type of PersonMoveEvent. The Person sends events to personMoveListener when
•the Person has been created
•the Person arrives at the Elevator
•the Person enters the Elevator
•the Person presses a Button (either in the Elevator or on a Floor)
•the Person exits the Elevator
•the Person exits the simulation
When the Person decides to send an event to its PersonMoveListener, the Person calls private method sendPersonMoveEvent and passes the desired constant as a parameter. This method sends the event associated with the constant. For example, line 124 calls
sendPersonMoveEvent( PERSON_PRESSED_BUTTON );
when the Person presses a Button on a Floor. In method run, the Person walks to the Elevator, then sends a personArrived event upon arrival at the Elevator. We use the activity diagram of Fig. 5.29 to determine the Person’s next action. If the Door on the Floor is closed (line 121), the Person must wait for that Door to open. Specifically, line 128 registers the Person as a DoorListener for that Door, and lines 131–132 allow the Person to press the Button on that Floor. The Person waits for the Door to open by calling method sleep (line 135) of the Person’s superclass Thread. When the Door opens, that Door informs Person in doorOpened
1436 |
Elevator Model (on CD) |
Appendix H |
(lines 57–65). Line 64 of method doorOpened interrupts the Person’s thread, which terminates method sleep of line 135. Method interrupt throws an InterruptedException received by a catch block (lines 147–155). Line 150 of this catch block unregisters the Person with the Door on the Floor, and line 154 calls private method enterAndRideElevator (lines 175–214)—however, according to Fig. 5.29, if the Door on the Floor is already open when the Person arrives, the
Person calls method enterAndRideElevator immediately.
Line 178 of method enterAndRideElevator sends a personEntered event to personMoveListener, indicating that the Person is entering the Elevator. When the Person enters the Elevator, the Person’s Location references the Elevator (lines 181–183). When the Person has entered the Elevator, lines 189–190 register the Person as a DoorListener with the Door in the Elevator. Lines 197– 200 allow the Person to press the Button in the Elevator and to send a personPressedButton event to the personMoveListener. Lines 206–207 invoke the synchronized method ride in the Elevator, ensuring that other Persons cannot occupy the Elevator. When the Elevator arrives, it sends an elevatorArrived event to the Door in the Elevator, which opens that Door and invokes method doorOpened of the Person. Method doorOpened, as previously mentioned, interrupts the Person’s thread—in this case, method interrupt terminates the sleep in method ride and allows the Person to exit the Elevator (allowing a Person waiting for the Elevator to enter). Method enterAndRideElevator returns, and lines 161– 170 of method run make the Person exit the Elevator and exit the simulation shortly thereafter.
H.10 Component Diagrams Revisited
In Section 13.17, we introduced the component diagram for the elevator simulation. In our simulation, the each class in the model imports package event—we showed the components of package event in Fig. G.15. Figure H.14 presents the component diagram for package model. Each component in package model maps to a class from the class diagram of Fig. 15.21—package model aggregates package event.
H.11 Conclusion
This concludes discussion case study model. We hope you have enjoyed the design process of our elevator simulation using the UML, along with the presentation of object-oriented fundamentals and Java-specific topics, such as event handling and multithreading. Using the concepts discussed in this case study, you should now be able to tackle even larger systems. We encourage you to read Appendix I, which implements the ElevatorView, which transforms the ElevatorModel that we have designed into a vibrant and interactive program abundant with graphics, animation and sound.
Appendix H |
Elevator Model (on CD) |
1437 |
model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<<file>> |
|
|
|
|
<<file>> |
|
||
|
|
|
|
|
|
||||||
|
|
|
Bell.java |
|
|
|
|
Button.java |
|
||
|
|
|
|
|
|
|
|
||||
|
|
|
|
|
|
||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<<file>> |
|
|
|
|
<<file>> |
|
||
|
|
|
|
|
|
|
|||||
|
|
|
Door.java |
|
|
|
|
Elevator.java |
|
||
|
|
|
|
|
|
|
|
||||
|
|
|
|
|
|
|
|||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<<file>> |
|
|
|
|
<<file>> |
|
||
|
|
|
|
|
|
|
|||||
|
|
|
ElevatorModel.java |
|
|
|
|
ElevatorShaft.java |
|
||
|
|
|
|
|
|
|
|
||||
|
|
|
|
|
|
|
|||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<<file>> |
|
|
|
|
<<file>> |
|
||
|
|
|
|
|
|
|
|||||
|
|
|
Floor.java |
|
|
|
|
Light.java |
|
||
|
|
|
|
|
|
|
|
||||
|
|
|
|
|
|
|
|||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<<file>> |
|
|
|
|
<<file>> |
|
||
|
|
|
|
|
|
|
|||||
|
|
|
Location.java |
|
|
|
|
Person.java |
|
||
|
|
|
|
|
|
|
|
||||
|
|
|
|
|
|
|
|||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
event |
||
|
|
|
|
1 |
|||||||
|
|
|
|
|
|
|
|||||
|
|
|
|
|
|
|
|
|
|
|
|
Fig. H.14 Component diagram for package model.
I
Elevator View (on CD)
I.1 Introduction
This appendix contains the implementation for class ElevatorView (Fig. I.1). Familiarity with the “Thinking About Objects” sections from all chapters (Chapter 22, in particular) necessitates the understanding of material presented in this appendix. Class ElevatorView is the largest class in the simulation. To facilitate discussion, we have divided the discussion of the ElevatorView into five topics—Class Objects, Class Constants,
Class Constructor, Event Handling and Component Diagrams Revisited.
1// ElevatorView.java
2// View for ElevatorSimulation
3 package com.deitel.jhtp4.elevator.view;
4
5 // Java core packages
6import java.awt.*;
7 import java.awt.event.*;
8import java.util.*;
9 import java.applet.*;
10
11// Java extension package
12import javax.swing.*;
13
14// Deitel packages
15import com.deitel.jhtp4.elevator.event.*;
16import com.deitel.jhtp4.elevator.ElevatorConstants;
18public class ElevatorView extends JPanel
19implements ActionListener, ElevatorModelListener,
20ElevatorConstants {
21
Fig. I.1 ElevatorView displays the elevator simulation model (part 1 of 18).
Appendix I |
Elevator View (on CD) |
1439 |
22// ElevatorView dimensions
23private static final int VIEW_WIDTH = 800;
24private static final int VIEW_HEIGHT = 435;
26// offset for positioning Panels in ElevatorView
27private static final int OFFSET = 10;
28
29// Elevator repaints components every 50 ms
30private static final int ANIMATION_DELAY = 50;
32// horizontal distance constants
33private static final int PERSON_TO_BUTTON_DISTANCE = 400;
34private static final int BUTTON_TO_ELEVATOR_DISTANCE = 50;
35private static final int PERSON_TO_ELEVATOR_DISTANCE =
36PERSON_TO_BUTTON_DISTANCE + BUTTON_TO_ELEVATOR_DISTANCE;
38// times walking to Floor's Button and Elevator
39private static final int TIME_TO_BUTTON = 3000; // 3 seconds
40private static final int TIME_TO_ELEVATOR = 1000; // 1 second
42// time traveling in Elevator (5 seconds)
43private static final int ELEVATOR_TRAVEL_TIME = 5000;
45// Door images for animation
46private static final String doorFrames[] = {
47"images/door1.png", "images/door2.png", "images/door3.png",
48"images/door4.png", "images/door5.png" };
49
50// Person images for animation
51private static final String personFrames[] = {
52"images/bug1.png", "images/bug2.png", "images/bug3.png",
53"images/bug4.png", "images/bug5.png", "images/bug6.png",
54"images/bug7.png", "images/bug8.png" };
55
56// Light images for animation
57private static final String lightFrames[] = {
58"images/lightOff.png", "images/lightOn.png" };
60// Floor Light images for animation
61private static final String firstFloorLightFrames[] = {
62"images/firstFloorLightOff.png",
63"images/firstFloorLightOn.png" };
64
65private static final String secondFloorLightFrames[] = {
66"images/secondFloorLightOff.png",
67"images/secondFloorLightOn.png", };
68
69// Floor Button images for animation
70private static final String floorButtonFrames[] = {
71"images/floorButtonUnpressed.png",
72"images/floorButtonPressed.png",
73"images/floorButtonLit.png" };
74
Fig. I.1 ElevatorView displays the elevator simulation model (part 2 of 18).
1440 |
Elevator View (on CD) |
Appendix I |
75// Elevator Button images for animation
76private static final String elevatorButtonFrames[] = {
77"images/elevatorButtonUnpressed.png",
78"images/elevatorButtonPressed.png",
79"images/elevatorButtonLit.png" };
80
81// Bell images for animation
82private static final String bellFrames[] = {
83"images/bell1.png", "images/bell2.png",
84"images/bell3.png" };
85
86private static final String floorImage =
87"images/floor.png";
88private static final String ceilingImage =
89"images/ceiling.png";
90private static final String elevatorImage =
91"images/elevator.png";
92private static final String wallImage =
93"images/wall.jpg";
94private static final String elevatorShaftImage =
95"images/elevatorShaft.png";
96
97// audio files
98private static final String bellSound = "bell.wav";
99private static final String doorOpenSound = "doorOpen.wav"; 100 private static final String doorCloseSound = "doorClose.wav"; 101 private static final String elevatorSound = "elevator.au"; 102 private static final String buttonSound = "button.wav";
103 private static final String walkingSound = "walk.wav";
104
105 private static final String midiFile = "sounds/liszt.mid";
106
107// ImagePanels for Floors, ElevatorShaft, wall and ceiling
108private ImagePanel firstFloorPanel;
109private ImagePanel secondFloorPanel;
110private ImagePanel elevatorShaftPanel;
111private ImagePanel wallPanel;
112private ImagePanel ceilingPanel;
113
114// MovingPanels for Elevator
115private MovingPanel elevatorPanel;
117// AnimatedPanels for Buttons, Bell, Lights and Door
118private AnimatedPanel firstFloorButtonPanel;
119private AnimatedPanel secondFloorButtonPanel;
120private AnimatedPanel elevatorButtonPanel;
121private AnimatedPanel bellPanel;
122private AnimatedPanel elevatorLightPanel;
123private AnimatedPanel firstFloorLightPanel;
124private AnimatedPanel secondFloorLightPanel;
125private AnimatedPanel doorPanel;
126
Fig. I.1 ElevatorView displays the elevator simulation model (part 3 of 18).
Appendix I |
Elevator View (on CD) |
1441 |
127// List containing AnimatedPanels for all Person objects
128private java.util.List personAnimatedPanels;
129
130// AudioClips for sound effects
131private AudioClip bellClip;
132private AudioClip doorOpenClip;
133private AudioClip doorCloseClip;
134private AudioClip elevatorClip;
135private AudioClip buttonClip;
136private AudioClip walkClip;
137
138// ElevatorMusic to play in Elevator
139private ElevatorMusic elevatorMusic;
141// Timer for animation controller;
142private javax.swing.Timer animationTimer;
144// distance from top of screen to display Floors
145private int firstFloorPosition;
146private int secondFloorPosition;
147
148// Elevator's velocity
149private double elevatorVelocity;
151// ElevatorView constructor
152public ElevatorView()
153{
154// specifiy null Layout
155super( null );
156
157instantiatePanels();
158placePanelsOnView();
159initializeAudio();
161// calculate distance Elevator travels
162double floorDistance =
163 firstFloorPosition - secondFloorPosition;
164
165// calculate time needed for travel
166double time = ELEVATOR_TRAVEL_TIME / ANIMATION_DELAY;
168// determine Elevator velocity (rate = distance / time)
169elevatorVelocity = ( floorDistance + OFFSET ) / time;
171// start animation Thread
172startAnimation();
173
174 } // end ElevatorView constructor
175
176// instantiate all Panels (Floors, Elevator, etc.)
177private void instantiatePanels()
178{
Fig. I.1 ElevatorView displays the elevator simulation model (part 4 of 18).
1442 |
Elevator View (on CD) |
Appendix I |
179// instantiate ImagePanels representing Floors
180firstFloorPanel = new ImagePanel( 0, floorImage );
181secondFloorPanel = new ImagePanel( 0, floorImage );
183// calculate first and second Floor positions
184firstFloorPosition =
185VIEW_HEIGHT - firstFloorPanel.getHeight();
186secondFloorPosition =
187 ( int ) ( firstFloorPosition / 2 ) - OFFSET;
188
189firstFloorPanel.setPosition( 0, firstFloorPosition );
190secondFloorPanel.setPosition( 0, secondFloorPosition );
192 wallPanel = new ImagePanel( 0, wallImage );
193
194// create and position ImagePanel for ElevatorShaft
195elevatorShaftPanel =
196 new ImagePanel( 0, elevatorShaftImage );
197
198double xPosition = PERSON_TO_ELEVATOR_DISTANCE + OFFSET;
199double yPosition =
200 firstFloorPosition - elevatorShaftPanel.getHeight();
201
202 elevatorShaftPanel.setPosition( xPosition, yPosition );
203
204// create and position ImagePanel for ceiling
205ceilingPanel = new ImagePanel( 0, ceilingImage );
207 yPosition = elevatorShaftPanel.getPosition().getY() -
208 ceilingPanel.getHeight();
209
210 ceilingPanel.setPosition( xPosition, yPosition );
211
212// create and position MovingPanel for Elevator
213elevatorPanel = new MovingPanel( 0, elevatorImage );
215 yPosition = firstFloorPosition - elevatorPanel.getHeight();
216
217 elevatorPanel.setPosition( xPosition, yPosition );
218
219// create and position first Floor Button
220firstFloorButtonPanel =
221 new AnimatedPanel( 0, floorButtonFrames );
222
223xPosition = PERSON_TO_BUTTON_DISTANCE + 2 * OFFSET;
224yPosition = firstFloorPosition - 5 * OFFSET;
225firstFloorButtonPanel.setPosition( xPosition, yPosition );
227int floorButtonPressedFrameOrder[] = { 0, 1, 2 };
228firstFloorButtonPanel.addFrameSequence(
229 |
floorButtonPressedFrameOrder ); |
230 |
|
|
|
Fig. I.1 ElevatorView displays the elevator simulation model (part 5 of 18).
Appendix I |
Elevator View (on CD) |
1443 |
231// create and position second Floor Button
232secondFloorButtonPanel =
233 new AnimatedPanel( 1, floorButtonFrames );
234
235xPosition = PERSON_TO_BUTTON_DISTANCE + 2 * OFFSET;
236yPosition = secondFloorPosition - 5 * OFFSET;
237secondFloorButtonPanel.setPosition( xPosition, yPosition );
239 |
secondFloorButtonPanel.addFrameSequence( |
240 |
floorButtonPressedFrameOrder ); |
241 |
|
242// create and position Floor Lights
243firstFloorLightPanel =
244 new AnimatedPanel( 0, firstFloorLightFrames );
245
246xPosition = elevatorPanel.getLocation().x - 4 * OFFSET;
247yPosition =
248firstFloorButtonPanel.getLocation().y - 10 * OFFSET;
249firstFloorLightPanel.setPosition( xPosition, yPosition );
251 secondFloorLightPanel =
252 new AnimatedPanel( 1, secondFloorLightFrames );
253
254 yPosition =
255secondFloorButtonPanel.getLocation().y - 10 * OFFSET;
256secondFloorLightPanel.setPosition( xPosition, yPosition );
258// create and position Door AnimatedPanels
259doorPanel = new AnimatedPanel( 0, doorFrames );
260int doorOpenedFrameOrder[] = { 0, 1, 2, 3, 4 };
261int doorClosedFrameOrder[] = { 4, 3, 2, 1, 0 };
262doorPanel.addFrameSequence( doorOpenedFrameOrder );
263doorPanel.addFrameSequence( doorClosedFrameOrder );
265// determine where Door is located relative to Elevator
266yPosition =
267 elevatorPanel.getHeight() - doorPanel.getHeight();
268
269 doorPanel.setPosition( 0, yPosition );
270
271// create and position Light AnimatedPanel
272elevatorLightPanel = new AnimatedPanel( 0, lightFrames );
273elevatorLightPanel.setPosition( OFFSET, 5 * OFFSET );
274
275// create and position Bell AnimatedPanel
276bellPanel = new AnimatedPanel( 0, bellFrames );
278 yPosition = elevatorLightPanel.getPosition().getY() +
279 elevatorLightPanel.getHeight() + OFFSET;
280
281bellPanel.setPosition( OFFSET, yPosition );
282int bellRingAnimation[] = { 0, 1, 0, 2 };
283bellPanel.addFrameSequence( bellRingAnimation );
Fig. I.1 ElevatorView displays the elevator simulation model (part 6 of 18).
1444 |
Elevator View (on CD) |
Appendix I |
284
285// create and position Elevator's Button AnimatedPanel
286elevatorButtonPanel =
287 new AnimatedPanel( 0, elevatorButtonFrames );
288
289yPosition = elevatorPanel.getHeight() - 6 * OFFSET;
290elevatorButtonPanel.setPosition( 10 * OFFSET, yPosition );
292int buttonPressedFrameOrder[] = { 0, 1, 2 };
293elevatorButtonPanel.addFrameSequence(
294 |
buttonPressedFrameOrder ); |
295 |
|
296// create List to store Person AnimatedPanels
297personAnimatedPanels = new ArrayList();
298
299 } // end method instantiatePanels
300
301// place all Panels on ElevatorView
302private void placePanelsOnView()
303{
304// add Panels to ElevatorView
305add( firstFloorPanel );
306add( secondFloorPanel );
307add( ceilingPanel );
308add( elevatorPanel );
309add( firstFloorButtonPanel );
310add( secondFloorButtonPanel );
311add( firstFloorLightPanel );
312add( secondFloorLightPanel );
313add( elevatorShaftPanel );
314add( wallPanel );
315
316// add Panels to Elevator's MovingPanel
317elevatorPanel.add( doorPanel );
318elevatorPanel.add( elevatorLightPanel );
319elevatorPanel.add( bellPanel );
320elevatorPanel.add( elevatorButtonPanel );
322 } // end method placePanelsOnView
323
324// get sound effects and elevatorMusic
325private void initializeAudio()
326{
327// create AudioClip sound effects from audio files
328SoundEffects sounds = new SoundEffects();
329sounds.setPathPrefix( "sounds/" );
330
331bellClip = sounds.getAudioClip( bellSound );
332doorOpenClip = sounds.getAudioClip( doorOpenSound );
333doorCloseClip = sounds.getAudioClip( doorCloseSound );
334elevatorClip = sounds.getAudioClip( elevatorSound );
335buttonClip = sounds.getAudioClip( buttonSound );
336walkClip = sounds.getAudioClip( walkingSound );
Fig. I.1 ElevatorView displays the elevator simulation model (part 7 of 18).
Appendix I |
Elevator View (on CD) |
1445 |
337
338// create MIDI player using Java Media Framework
339elevatorMusic = new ElevatorMusic( midiFile );
340elevatorMusic.open();
341
342 } // end method initializeAudio
343
344// starts animation by repeatedly drawing images to screen
345public void startAnimation()
346{
347if ( animationTimer == null ) {
348 |
animationTimer = |
349 |
new javax.swing.Timer( ANIMATION_DELAY, this ); |
350animationTimer.start();
351}
352else
353
354 if ( !animationTimer.isRunning() )
355animationTimer.restart();
356}
357
358// stop animation
359public void stopAnimation()
360{
361animationTimer.stop();
362}
363
364// update AnimatedPanels animation in response to Timer
365public void actionPerformed( ActionEvent actionEvent )
366{
367elevatorPanel.animate();
368
369firstFloorButtonPanel.animate();
370secondFloorButtonPanel.animate();
372 |
Iterator iterator = getPersonAnimatedPanelsIterator(); |
373 |
|
374 |
while ( iterator.hasNext() ) { |
375 |
|
376 |
// get Person's AnimatedPanel from Set |
377 |
AnimatedPanel personPanel = |
378 |
( AnimatedPanel ) iterator.next(); |
379 |
|
380personPanel.animate(); // update panel
381}
382
383 repaint(); // paint all Components
384
385 } // end method actionPerformed
386
387private Iterator getPersonAnimatedPanelsIterator()
388{
Fig. I.1 ElevatorView displays the elevator simulation model (part 8 of 18).
1446 |
Elevator View (on CD) |
Appendix I |
389// obtain iterator from List
390synchronized( personAnimatedPanels )
391{
392return new ArrayList( personAnimatedPanels ).iterator();
393}
394}
395
396// stop sound clip of Person walking
397private void stopWalkingSound()
398{
399// stop playing walking sound
400walkClip.stop();
401
402 Iterator iterator = getPersonAnimatedPanelsIterator();
403
404// but if Person is still walking, then keep playing
405while ( iterator.hasNext() ) {
406 AnimatedPanel panel = ( AnimatedPanel ) iterator.next();
407
408 if ( panel.getXVelocity() != 0 )
409walkClip.loop();
410}
411} // end method stopWalkingSound
413// returns Person AnimatedPanel with proper identifier
414private AnimatedPanel getPersonPanel( PersonMoveEvent event )
415{
416Iterator iterator = getPersonAnimatedPanelsIterator();
417 |
|
418 |
while ( iterator.hasNext() ) { |
419 |
|
420 |
// get next AnimatedPanel |
421 |
AnimatedPanel personPanel = |
422 |
( AnimatedPanel ) iterator.next(); |
423 |
|
424 |
// return AnimatedPanel with identifier that matches |
425 |
if ( personPanel.getID() == event.getID() ) |
426return personPanel;
427}
428
429// return null if no match with correct identifier
430return null;
431
432 } // end method getPersonPanel
433
434// invoked when Elevator has departed from Floor
435public void elevatorDeparted( ElevatorMoveEvent moveEvent )
436{
437String location =
438 |
moveEvent.getLocation().getLocationName(); |
439 |
|
440// determine if Person is on Elevator
441Iterator iterator = getPersonAnimatedPanelsIterator();
Fig. I.1 ElevatorView displays the elevator simulation model (part 9 of 18).
Appendix I |
Elevator View (on CD) |
1447 |
|
|
|
|
|
442 |
|
|
|
443 |
while ( iterator.hasNext() ) { |
|
|
444 |
|
|
|
445 |
|
AnimatedPanel personPanel = |
|
446 |
|
( AnimatedPanel ) iterator.next(); |
|
447 |
|
|
|
448 |
|
double yPosition = personPanel.getPosition().getY(); |
|
449 |
|
String panelLocation; |
|
450 |
|
|
|
451 |
|
// determine on which Floor the Person entered |
|
452 |
|
if ( yPosition > secondFloorPosition ) |
|
453 |
|
panelLocation = FIRST_FLOOR_NAME; |
|
454 |
|
else |
|
455 |
|
panelLocation = SECOND_FLOOR_NAME; |
|
456 |
|
|
|
457 |
|
int xPosition = |
|
458 |
|
( int ) personPanel.getPosition().getX(); |
|
459 |
|
|
|
460 |
|
// if Person is inside Elevator |
|
461 |
|
if ( panelLocation.equals( location ) |
|
462 |
|
&& xPosition > PERSON_TO_BUTTON_DISTANCE + OFFSET ) { |
|
463 |
|
|
|
464 |
|
// remove Person AnimatedPanel from ElevatorView |
|
465 |
|
remove( personPanel ); |
|
466 |
|
|
|
467 |
|
// add Person AnimatedPanel to Elevator |
|
468 |
|
elevatorPanel.add( personPanel, 1 ); |
|
469 |
|
personPanel.setLocation( 2 * OFFSET, 9 * OFFSET ); |
|
470 |
|
personPanel.setMoving( false ); |
|
471 |
|
personPanel.setAnimating( false ); |
|
472 |
|
personPanel.setVelocity( 0, 0 ); |
|
473 |
|
personPanel.setCurrentFrame( 1 ); |
|
474}
475} // end while loop
477// determine Elevator velocity depending on Floor
478if ( location.equals( FIRST_FLOOR_NAME ) )
479elevatorPanel.setVelocity( 0, -elevatorVelocity );
480else
481 |
|
482 |
if ( location.equals( SECOND_FLOOR_NAME ) ) |
483 |
elevatorPanel.setVelocity( 0, elevatorVelocity ); |
484 |
|
485// begin moving Elevator and play Elevator music
486elevatorPanel.setMoving( true );
487 |
|
488 |
if ( elevatorClip != null ) |
489 |
elevatorClip.play(); |
490 |
|
491 |
elevatorMusic.play(); |
492 |
|
493 |
} // end method elevatorDeparted |
494 |
|
|
|
Fig. I.1 |
ElevatorView displays the elevator simulation model (part 10 of 18). |
1448 |
Elevator View (on CD) |
Appendix I |
495// invoked when Elevator has arrived at destination Floor
496public void elevatorArrived( ElevatorMoveEvent moveEvent )
497{
498// stop Elevator and music
499elevatorPanel.setMoving( false );
500elevatorMusic.getSequencer().stop();
501
502double xPosition = elevatorPanel.getPosition().getX();
503double yPosition;
504
505// set Elevator's position to either first or second Floor
506if ( elevatorPanel.getYVelocity() < 0 )
507 |
yPosition = |
508secondFloorPosition - elevatorPanel.getHeight();
509else
510 |
yPosition = |
511 |
firstFloorPosition - elevatorPanel.getHeight(); |
512 |
|
513 |
elevatorPanel.setPosition( xPosition, yPosition ); |
514 |
|
515 |
} // end method elevatorArrived |
516 |
|
517// invoked when Person has been created in model
518public void personCreated( PersonMoveEvent personEvent )
519{
520int personID = personEvent.getID();
521 |
|
522 |
String floorLocation = |
523 |
personEvent.getLocation().getLocationName(); |
524 |
|
525// create AnimatedPanel representing Person
526AnimatedPanel personPanel =
527 new AnimatedPanel( personID, personFrames );
528
529// determine where Person should be drawn initially
530// negative xPosition ensures Person drawn offscreen
531double xPosition = - personPanel.getWidth();
532double yPosition = 0;
533
534 if ( floorLocation.equals( FIRST_FLOOR_NAME ) ) 535 yPosition = firstFloorPosition +
536( firstFloorPanel.getHeight() / 2 );
537else
538 |
|
539 |
if ( floorLocation.equals( SECOND_FLOOR_NAME ) ) |
540 |
yPosition = secondFloorPosition + |
541 |
( secondFloorPanel.getHeight() / 2 ); |
542 |
|
543 |
yPosition -= personPanel.getHeight(); |
544 |
|
545 |
personPanel.setPosition( xPosition, yPosition ); |
546 |
|
|
|
Fig. I.1 ElevatorView displays the elevator simulation model (part 11 of 18).
Appendix I |
Elevator View (on CD) |
1449 |
547// add some animations for each Person
548int walkFrameOrder[] = { 1, 0, 1, 2 };
549int pressButtonFrameOrder[] = { 1, 3, 3, 4, 4, 1 };
550int walkAwayFrameOrder[] = { 6, 5, 6, 7 };
551personPanel.addFrameSequence( walkFrameOrder );
552personPanel.addFrameSequence( pressButtonFrameOrder );
553personPanel.addFrameSequence( walkAwayFrameOrder );
555// have Person begin walking to Elevator
556personPanel.playAnimation( 0 );
557personPanel.setLoop( true );
558personPanel.setAnimating( true );
559personPanel.setMoving( true );
560
561// determine Person velocity
562double time =
563 ( double ) ( TIME_TO_BUTTON / ANIMATION_DELAY );
564
565 double xDistance = PERSON_TO_BUTTON_DISTANCE -
5662 * OFFSET + personPanel.getSize().width;
567double xVelocity = xDistance / time;
568
569personPanel.setVelocity( xVelocity, 0 );
570personPanel.setAnimationRate( 1 );
571
572 walkClip.loop(); // play sound clip of Person walking
573
574// store in personAnimatedPanels
575synchronized( personAnimatedPanels )
576{
577personAnimatedPanels.add( personPanel );
578}
579
580 add( personPanel, 0 );
581
582 } // end method personCreated
583
584// invoked when Person has arrived at Elevator
585public void personArrived( PersonMoveEvent personEvent )
586{
587// find Panel associated with Person that issued event
588AnimatedPanel panel = getPersonPanel( personEvent );
590if ( panel != null ) { // if Person exists
592 |
// Person stops at Floor Button |
593 |
panel.setMoving( false ); |
594 |
panel.setAnimating( false ); |
595 |
panel.setCurrentFrame( 1 ); |
596 |
stopWalkingSound(); |
597 |
|
598 |
double xPosition = PERSON_TO_BUTTON_DISTANCE - |
599 |
( panel.getSize().width / 2 ); |
|
|
Fig. I.1 |
ElevatorView displays the elevator simulation model (part 12 of 18). |
1450 |
Elevator View (on CD) |
Appendix I |
600 double yPosition = panel.getPosition().getY();
601
602panel.setPosition( xPosition, yPosition );
603}
604} // end method personArrived
605
606// invoked when Person has pressed Button
607public void personPressedButton( PersonMoveEvent personEvent )
608{
609// find Panel associated with Person that issued event
610AnimatedPanel panel = getPersonPanel( personEvent );
611
612 if ( panel != null ) { // if Person exists
613
614 // Person stops walking and presses Button
615 panel.setLoop( false );
616 panel.playAnimation( 1 );
617
618 panel.setVelocity( 0, 0 );
619 panel.setMoving( false );
620 panel.setAnimating( true );
621stopWalkingSound();
622}
623} // end method personPressedButton
625// invoked when Person has started to enter Elevator
626public void personEntered( PersonMoveEvent personEvent )
627{
628// find Panel associated with Person that issued event
629AnimatedPanel panel = getPersonPanel( personEvent );
631if ( panel != null ) {
633 |
// determine velocity |
634 |
double time = TIME_TO_ELEVATOR / ANIMATION_DELAY; |
635 |
|
636 |
double distance = |
637 |
elevatorPanel.getPosition().getX() - |
638 |
panel.getPosition().getX() + 2 * OFFSET; |
639 |
|
640 |
panel.setVelocity( distance / time, -1.5 ); |
641 |
|
642 |
// Person starts walking |
643 |
panel.setMoving( true ); |
644 |
panel.playAnimation( 0 ); |
645panel.setLoop( true );
646}
647} // end method personEntered
649// invoked when Person has departed from Elevator
650public void personDeparted( PersonMoveEvent personEvent)
651{
Fig. I.1 ElevatorView displays the elevator simulation model (part 13 of 18).
Appendix I |
Elevator View (on CD) |
1451 |
652// find Panel associated with Person that issued event
653AnimatedPanel panel = getPersonPanel( personEvent );
655if ( panel != null ) { // if Person exists
657 |
// determine velocity (in opposite direction) |
658 |
double time = TIME_TO_BUTTON / ANIMATION_DELAY; |
659 |
double xVelocity = - PERSON_TO_BUTTON_DISTANCE / time; |
660 |
|
661 |
panel.setVelocity( xVelocity, 0 ); |
662 |
|
663 |
// remove Person from Elevator |
664 |
elevatorPanel.remove( panel ); |
665 |
|
666 |
double xPosition = |
667 |
PERSON_TO_ELEVATOR_DISTANCE + 3 * OFFSET; |
668 |
double yPosition = 0; |
669 |
|
670 |
String floorLocation = |
671 |
personEvent.getLocation().getLocationName(); |
672 |
|
673 |
// determine Floor onto which Person exits |
674 |
if ( floorLocation.equals( FIRST_FLOOR_NAME ) ) |
675 |
yPosition = firstFloorPosition + |
676 |
( firstFloorPanel.getHeight() / 2 ); |
677 |
else |
678 |
|
679 |
if ( floorLocation.equals( SECOND_FLOOR_NAME ) ) |
680 |
yPosition = secondFloorPosition + |
681 |
( secondFloorPanel.getHeight() / 2 ); |
682 |
|
683 |
yPosition -= panel.getHeight(); |
684 |
|
685 |
panel.setPosition( xPosition, yPosition ); |
686 |
|
687 |
// add Person to ElevatorView |
688 |
add( panel, 0 ); |
689 |
|
690 |
// Person starts walking |
691 |
panel.setMoving( true ); |
692 |
panel.setAnimating( true ); |
693 |
panel.playAnimation( 2 ); |
694 |
panel.setLoop( true ); |
695walkClip.loop();
696}
697} // end method PersonDeparted
699// invoked when Person has exited simulation
700public void personExited( PersonMoveEvent personEvent)
701{
702// find Panel associated with Person that issued moveEvent
703AnimatedPanel panel = getPersonPanel( personEvent );
704
Fig. I.1 ElevatorView displays the elevator simulation model (part 14 of 18).
1452 |
Elevator View (on CD) |
Appendix I |
705 |
if ( panel != null ) { // if Person exists |
706 |
|
707 |
panel.setMoving( false ); |
708 |
panel.setAnimating( false ); |
709 |
|
710 |
// remove Person permanently and stop walking sound |
711 |
synchronized( personAnimatedPanels ) |
712 |
{ |
713 |
personAnimatedPanels.remove( panel ); |
714 |
} |
715 |
remove( panel ); |
716stopWalkingSound();
717}
718} // end method personExited
720// invoked when Door has opened in model
721public void doorOpened( DoorEvent doorEvent )
722{
723// get DoorEvent Location
724String location =
725 |
doorEvent.getLocation().getLocationName(); |
726 |
|
727// play animation of Door opening
728doorPanel.playAnimation( 0 );
729doorPanel.setAnimationRate( 2 );
730doorPanel.setDisplayLastFrame( true );
732// play sound clip of Door opening
733if ( doorOpenClip != null )
734 |
doorOpenClip.play(); |
735 |
|
736 |
} // end method doorOpened |
737 |
|
738// invoked when Door has closed in model
739public void doorClosed( DoorEvent doorEvent )
740{
741// get DoorEvent Location
742String location =
743 |
doorEvent.getLocation().getLocationName(); |
744 |
|
745// play animation of Door closing
746doorPanel.playAnimation( 1 );
747doorPanel.setAnimationRate( 2 );
748doorPanel.setDisplayLastFrame( true );
750// play sound clip of Door closing
751if ( doorCloseClip != null )
752 |
doorCloseClip.play(); |
753 |
|
754 |
} // end method doorClosed |
755 |
|
Fig. I.1 ElevatorView displays the elevator simulation model (part 15 of 18).
Appendix I |
Elevator View (on CD) |
1453 |
756// invoked when Button has been pressed in model
757public void buttonPressed( ButtonEvent buttonEvent )
758{
759// get ButtonEvent Location
760String location =
761 |
buttonEvent.getLocation().getLocationName(); |
762 |
|
763// press Elevator Button if from Elevator
764if ( location.equals( ELEVATOR_NAME ) ) {
765elevatorButtonPanel.playAnimation( 0 );
766elevatorButtonPanel.setDisplayLastFrame( true );
767 |
} |
768 |
|
769// press Floor Button if from Floor
770else
771 |
|
772 |
if ( location.equals( FIRST_FLOOR_NAME ) ) { |
773 |
firstFloorButtonPanel.playAnimation( 0 ); |
774 |
firstFloorButtonPanel.setDisplayLastFrame( true ); |
775}
776else
778 |
if ( location.equals( SECOND_FLOOR_NAME ) ) { |
779 |
secondFloorButtonPanel.playAnimation( 0 ); |
780 |
secondFloorButtonPanel.setDisplayLastFrame( true ); |
781 |
} |
782 |
|
783 |
if ( buttonClip != null ) |
784 |
buttonClip.play(); // play button press sound clip |
785 |
|
786 |
} // end method buttonPressed |
787 |
|
788// invoked when Button has been reset in model
789public void buttonReset( ButtonEvent buttonEvent )
790{
791// get ButtonEvent Location
792String location =
793 |
buttonEvent.getLocation().getLocationName(); |
794 |
|
795// reset Elevator Button if from Elevator
796if ( location.equals( ELEVATOR_NAME ) ) {
798 |
// return to first frame if still animating |
799 |
if ( elevatorButtonPanel.isAnimating() ) |
800 |
elevatorButtonPanel.setDisplayLastFrame( false ); |
801 |
else |
802elevatorButtonPanel.setCurrentFrame( 0 );
803}
804
805// reset Floor Button if from Floor
806else
807
Fig. I.1 ElevatorView displays the elevator simulation model (part 16 of 18).
1454 |
Elevator View (on CD) |
Appendix I |
|
|
|
808 |
if ( location.equals( FIRST_FLOOR_NAME ) ) { |
|
809 |
|
|
810 |
// return to first frame if still animating |
|
811 |
if ( firstFloorButtonPanel.isAnimating() ) |
|
812 |
firstFloorButtonPanel.setDisplayLastFrame( |
|
813 |
false ); |
|
814 |
else |
|
815 |
firstFloorButtonPanel.setCurrentFrame( 0 ); |
816}
817else
819 |
if ( location.equals( SECOND_FLOOR_NAME ) ) { |
820 |
|
821 |
// return to first frame if still animating |
822 |
if ( secondFloorButtonPanel.isAnimating() ) |
823 |
secondFloorButtonPanel.setDisplayLastFrame( |
824 |
false ); |
825 |
else |
826 |
secondFloorButtonPanel.setCurrentFrame( 0 ); |
827 |
} |
828 |
|
829 |
} // end method buttonReset |
830 |
|
831// invoked when Bell has rung in model
832public void bellRang( BellEvent bellEvent )
833{
834bellPanel.playAnimation( 0 ); // animate Bell
836 if ( bellClip != null ) // play Bell sound clip
837bellClip.play();
838}
839
840// invoked when Light turned on in model
841public void lightTurnedOn( LightEvent lightEvent )
842{
843// turn on Light in Elevator
844elevatorLightPanel.setCurrentFrame( 1 );
845 |
|
846 |
String location = |
847 |
lightEvent.getLocation().getLocationName(); |
848 |
|
849// turn on Light on either first or second Floor
850if ( location.equals( FIRST_FLOOR_NAME ) )
851 |
firstFloorLightPanel.setCurrentFrame( 1 ); |
852 |
|
853 |
else |
854 |
|
855 |
if ( location.equals( SECOND_FLOOR_NAME ) ) |
856 |
secondFloorLightPanel.setCurrentFrame( 1 ); |
857 |
|
858 |
} // end method lightTurnedOn |
859 |
|
|
|
Fig. I.1 ElevatorView displays the elevator simulation model (part 17 of 18).
Appendix I |
Elevator View (on CD) |
1455 |
860// invoked when Light turned off in model
861public void lightTurnedOff( LightEvent lightEvent )
862{
863// turn off Light in Elevator
864elevatorLightPanel.setCurrentFrame( 0 );
865 |
|
866 |
String location = |
867 |
lightEvent.getLocation().getLocationName(); |
868 |
|
869// turn off Light on either first or second Floor
870if ( location.equals( FIRST_FLOOR_NAME ) )
871 |
firstFloorLightPanel.setCurrentFrame( 0 ); |
872 |
|
873 |
else |
874 |
|
875 |
if ( location.equals( SECOND_FLOOR_NAME ) ) |
876 |
secondFloorLightPanel.setCurrentFrame( 0 ); |
877 |
|
878 |
} // end method lightTurnedOff |
879 |
|
880// return preferred size of ElevatorView
881public Dimension getPreferredSize()
882{
883return new Dimension( VIEW_WIDTH, VIEW_HEIGHT );
884}
885
886// return minimum size of ElevatorView
887public Dimension getMinimumSize()
888{
889return getPreferredSize();
890}
891
892// return maximum size of ElevatorView
893public Dimension getMaximumSize()
894{
895return getPreferredSize();
896}
897}
Fig. I.1 ElevatorView displays the elevator simulation model (part 18 of 18).
I.2 Class Objects
The ElevatorView is a JPanel with a series of other JPanel “children” added to it. Each JPanel provides a visual representation of an object from the model. For example, the ElevatorView contains ImagePanels, MovingPanels and AnimatedPanels to represent the Elevator, Persons, the ElevatorShaft, the Buttons on the Floors, the Button in the Elevator, the Doors on the Floors, the Door in the Elevator, the Lights on the Floors, the two Floors and the Bell. Figure I.2 lists the ElevatorView’s objects and their counterparts in the model.
1456 |
Elevator View (on CD) |
Appendix I |
|
|
|
|
|
The object (in model) |
is represented by the object |
|
|
of Class... |
(in view)... |
of Class... |
|
|
|
|
|
Floor |
|
firstFloorPanel |
ImagePanel |
|
|
secondFloorPanel |
ImagePanel |
ElevatorShaft |
elevatorShaftPanel |
ImagePanel |
|
Elevator |
elevatorPanel |
MovingPanel |
|
Button (on Floor) |
firstFloorButtonPanel |
AnimatedPanel |
|
|
|
secondFloorButtonPanel |
AnimatedPanel |
Button (in Elevator) |
elevatorButtonPanel |
AnimatedPanel |
|
Bell |
|
bellPanel |
AnimatedPanel |
Light |
|
firstFloorLightPanel |
AnimatedPanel |
|
|
secondFloorLightPanel |
AnimatedPanel |
Door (in Elevator) |
doorPanel |
AnimatedPanel |
|
Door (on Floor) |
<not represented> |
<not represented> |
|
Person |
personAnimatedPanels |
List (of AnimatedPanels) |
Fig. I.2 Objects in the ElevatorView representing objects in the model.
Lines 108–128 of class ElevatorView declare the objects in the second column of Fig. I.2. The firstFloorPanel (line 108), secondFloorPanel (line 109) and elevatorShaftPanel (line 110) are ImagePanels, because neither the Floors nor the ElevatorShaft move in the simulation. The elevatorPanel (line 115) is a MovingPanel, because the Elevator’s only function is to move between Floors. The firstFloorButtonPanel (line 118), secondFloorButtonPanel (line 119) and elevatorButtonPanel (line 120) are AnimatedPanels, because each object animates when the associated Button in the model is pressed or reset. The bellPanel (line 121) is an AnimatedPanel to animate the ringing of the Bell. The firstFloorLightPanel (line 123) and secondFloorLightPanel (line 124) are
AnimatedPanels, because these objects animate when the associated Light turns on or off. The doorPanel (line 125) is an AnimatedPanel to animate the opening and closing of the Door. Note that the ElevatorView shows only the Door in the Elevator. The ElevatorView does not show the Doors on the Floors, which enables us to show the Elevator’s interior (these Doors would obstruct the objects inside the
Elevator). Lastly, the personAnimatedPanels (line 128) is a List of AnimatedPanels, because there can exist several Person objects during execution—the ElevatorView must need to store dynamically the AnimatedPanels associated with Persons in the model.
We add to the ElevatorView three more elements that we assume to be parts of the Elevator (Fig. I.3), although the model does not represent these elements—a light inside the Elevator of type AnimatedPanel called elevatorLightPanel (line 122), a ceiling over the Elevator of type ImagePanel called ceilingPanel (line 112), and wallpaper inside the building of type ImagePanel called wallPanel (line 111).
Appendix I |
|
Elevator View (on CD) |
1457 |
|
|
|
|
|
|
The object (in |
is represented by the object (in |
|
|
|
model) of Class... |
view)... |
|
of Class... |
|
|
|
|
|
|
<not represented> |
elevatorLightPanel |
|
AnimatedPanel |
|
<not represented> |
ceilingPanel |
|
ImagePanel |
|
<not represented> |
wallPanel |
|
ImagePanel |
|
Fig. I.3 Objects in the ElevatorView not represented in the model.
In addition, the class diagram of Fig. 22.9 shows that the ElevatorView contains one instance each of classes SoundEffects and ElevatorMusic. The SoundEffects object generates the AudioClips used to play sound effects, such as the Door opening and a Person walking. Lines 131–136 declare all AudioClips, line 139 declares the ElevatorMusic object, and line 328 (in method initializeAudio, which we discuss later in this section) declares the SoundEffects object.
I.3 Class Constants
The ElevatorView uses constants to specify or obtain such information as
•The initial placement of objects in the ElevatorView
•The rate at which the ElevatorView redraws the screen (animation rate)
•The names of image files used by the ImagePanels
•The names of sound files used by the SoundEffects object and the ElevatorMusic
•The distances in pixels the ImagePanels representing the Elevator and Person must travel
•The times needed to travel these distances
Lines 23–24 declare int constants VIEW_WIDTH and VIEW_HEIGHT, which specify the ElevatorView’s dimensions. Method getPreferredSize (lines 881– 884) returns this dimension. Method pack of class ElevatorSimulation uses this method to obtain the ElevatorView’s dimension to place the ElevatorView in the GUI properly.
The ElevatorView has a null layout, so we may place ImagePanels in any x- y coordinate in the ElevatorView. Line 27 of class ElevatorView declares int constant OFFSET, which helps to determine the exact positions of objects in the ElevatorView. Line 30 declares int constant ANIMATION_DELAY, which specifies the number of milliseconds between animation frames. In our simulation, we initialize ANIMATION_DELAY to 50 milliseconds. Lines 46–95 declare String constants specifying the image files used to instantiate the ImagePanels. Lines 98–105 declare the String constant specifying the audio files used to instantiate the AudioClips and the
ElevatorMusic.
Line 33 declares the int constant PERSON_TO_BUTTON_DISTANCE, which represents the horizontal distance between the on-screen location of the firstFloorBut-
1458 Elevator View (on CD) Appendix I
tonPanel or secondFloorButtonPanel and the initial on-screen location of an AnimatedPanel associated with Person. This AnimatedPanel uses this constant to calculate the travel distance to the firstFloorButtonPanel or secondFloorButtonPanel. The firstFloorButtonPanel and secondFloorButtonPanel use the constant to position themselves on screen. Line 34 declares the int constant BUTTON_TO_ELEVATOR_DISTANCE, describing the horizontal distance between the firstFloorButtonPanel or secondFloorButtonPanel and the elevatorPanel. The AnimatedPanel associated with a Person uses this constant to determine the travel distance when entering the elevatorPanel.
Line 39 declares int constant TIME_TO_BUTTON, which represents this AnimatedPanel’s travel time to the firstFloorButtonPanel or secondFloorButtonPanel. Line 40 declares int constant TIME_TO_ELEVATOR, which represents the time the AnimatedPanel associated with a Person needs to enter the elevatorPanel from the firstFloorButtonPanel or secondFloorButtonPanel. Using the equation rate = distance / time, the AnimatedPanel associated with the Person can determine the velocity needed to travel. Similarly, line 43 declares int constant ELEVATOR_TRAVEL_TIME, which represents the elevatorPanel’s travel time between the firstFloorPanel and secondFloorPanel—lines 166–169 use this constant to determine double attribute elevatorVelocity (line 149).
I.4 Class constructor
The responsibilities of the ElevatorView constructor (lines 152–174) are
•To instantiate all ImagePanels
•To add all ImagePanels to the ElevatorView
•To initialize the audio objects
•To compute the elevatorPanel’s initial velocity and distance traveled
•To start the animation Timer
Lines 157 calls private method instantiatePanels (lines 177–299), which instantiates all ImagePanels in the ElevatorView. Lines 180–181 instantiate the firstFloorPanel and secondFloorPanel, and lines 184–190 set these objects’ positions—the ElevatorView positions the firstFloorPanel on the bottom of the screen and positions the secondFloorPanel in the vertical center of the screen. Line 192 instantiates the wallPanel ImagePanel. The ElevatorView does not need to calculate the position for the wallPanel, because the wallPanel’s default screen position (i.e., xPosition = 0, yPosition = 0) is correct. Lines 195–202 and lines 205–210 instantiate and position the elevatorShaftPanel and ceilingPanel ImagePanels, respectively. The ElevatorView positions the elevatorShaftPanel in the right of the screen and positions the ceilingPanel above the elevatorShaftPanel. Lines 213–217 instantiate the elevatorPanel and position it over the elevatorShaftPanel above the firstFloorPanel. Lines 220– 229 instantiate the firstFloorButtonPanel AnimatedPanel, place it next to the elevatorShaftPanel, then create a frame sequence Button pressed animation. Lines 232–240 perform the same actions on the secondFloorButtonPanel. Lines 243–249 instantiate the firstFloorLightPanel AnimatedPanel and place it to
Appendix I |
Elevator View (on CD) |
1459 |
the left of the elevatorShaftPanel but above the firstFloorButtonPanel. Lines 251–256 position the secondFloorLightPanel above the secondFloorButtonPanel. Lines 259–269 instantiate the doorPanel AnimatedPanel, place it relative to the elevatorPanel’s position (because the elevatorPanel will contain the doorPanel) and assign frame sequences describing the Door animation opening and closing. Lines 272–273 instantiate the elevatorLightPanel AnimatedPanel and position it over the elevatorPanel and to the left of the doorPanel. Lines 276– 283 instantiate the bellPanel, position it below the elevatorLightPanel, then assign a frame sequence describing the Bell ringing animation. Lines 286–294 instantiate the elevatorButtonPanel, position it in the center of the elevatorPanel and assign a frame sequence describing the Button pressed animation. Lastly, line 297 instantiates the ArrayList holding the AnimatedPanels associated with the Persons in the model.
After the ElevatorView constructor has called method instantiatePanels, the constructor calls method placePanelsOnView (lines 302–322), which adds all instantiated Panels to the ElevatorView. Lines 317–320 add the doorPanel, elevatorLightPanel, bellPanel and elevatorButtonPanel to the elevatorPanel. The ElevatorView constructor then calls method initializeAudio (lines 325–342). Lines 328–329 instantiate a SoundEffects object, and lines 331–336 use method getAudioClip of the SoundEffects object to return the AudioClips for the simulation. Method play of class AudioClip plays the AudioClip—the ElevatorView uses this method for sounds that do not repeat, such as the Bell ring. Method loop of class AudioClip plays the clip continually—the ElevatorView uses this method for sounds that repeat, such as the sound of footsteps. Lines 339–340 instantiate the ElevatorMusic object and ensure that the MIDI data is valid.
Finally, lines 162–163 (in the ElevatorView constructor) calculate the distance between the two Floors (i.e., the distance the elevatorPanel will travel). Lines 166– 169 use the equation rate = distance / time to determine the elevatorPanel’s velocity when traveling. Finally, line 172 calls method startAnimation, which starts the animation timer.
The ElevatorView animates the ImagePanels using animationTimer (line 142), an instance of class javax.swing.Timer. The animationTimer starts in the ElevatorView constructor through method startAnimation (lines 345–356). Class
ElevatorView implements interface ActionListener to listen for ActionEvents. The animationTimer sends an ActionEvent to the ElevatorView every 50 (ANIMATION_DELAY) milliseconds. When the ElevatorView receives an ActionEvent, the ElevatorView calls method actionPerformed (lines 365–385). Line 367 in this method update the position and current image of the elevatorPanel and of the elevatorPanel’s children. Lines 369–370 allow the firstFloorButtonPanel and secondFloorButtonPanel to update themselves. Lines 374–381 iterate List personAnimatedPanels and update the position and current image of each AnimatedPanel associated with a Person in the model. Lastly, line 383 calls method repaint to redraw all ImagePanels added to the ElevatorView on screen.
We present an object diagram that lists all objects in the ElevatorView. Recall that an object diagram provides a snapshot of the structure when the system is running. The object diagram of Fig. I.4 represents the ElevatorView after invoking the constructor.
1460 |
|
|
Elevator View (on CD) |
|
|
|
|
|
|
|
|
|
|
|
Appendix I |
||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|||||
|
|
|
|
firstFloorButtonPanel : AnimatedPanel |
|
|
|
|
|
|
|
|
|
||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
firstFloorPanel : ImagePanel |
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||
|
|
|
secondFloorButtonPanel : AnimatedPanel |
|
|
|
|
|
|
|
|
|
|||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
||||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
secondFloorPanel : ImagePanel |
||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|||||
|
|
|
|
firstFloorLightPanel : AnimatedPanel |
|
|
|
|
|
|
|
|
|
||||||||||
|
|
|
|
|
|
|
|
|
|||||||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
elevatorShaftPanel : ImagePanel |
||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|||||
|
|
|
|
secondFloorLightPanel : AnimatedPanel |
|
|
|
|
|
|
|
|
|
||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ceilingPanel : ImagePanel |
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
wallPanel : ImagePanel |
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
elevatorPanel : MovingPanel |
|
|
|
: ElevatorView |
|
|
|
|
|
|||||||||||||
|
|
|
|
|
|
|
|
|
|||||||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
bellClip : AudioClip |
|
|
|
|
|
|
|
|
: ElevatorMusic |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
doorOpenClip : AudioClip |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
lightPanel : AnimatedPanel |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
doorCloseClip : AudioClip |
|
|
|
|||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
: SoundEffects |
|
|
|
|
|
|||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||||
|
|
bellPanel : AnimatedPanel |
|
|
|
|
|
|
|
|
|
|
|
elevatorClip : AudioClip |
|
|
|
||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
doorPanel : AnimatedPanel |
|
|
|
|
|
|
|
|
|
|
|
buttonClip : AudioClip |
|
|
|
||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
walkClip : AudioClip |
|
|
|
|
elevatorButtonPanel : AnimatedPanel |
|
|
|
|
|
|
|
|
|
|
||||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
||||||||||||
|
|
|
|
|
|
||||||||||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Fig. I.4 |
Object diagram for the ElevatorView after initialization. |
The ElevatorView object links (contains an association) with all objects presented in Fig. I.4. The elevatorPanel links with objects elevatorLightPanel, bellPanel, doorPanel and elevatorButtonPanel. This association provides a visualization of what is happening in the model—the Elevator contains a Light, Bell, Door and Button. The SoundEffects object links with the AudioClip objects, because the SoundEffects object generates the AudioClip objects.
I.5 Event Handling
Figure 13.19 specified that the ElevatorView implements interface ElevatorModelListener, which implements all interfaces in the simulation. The ElevatorSimulation registers the ElevatorView as a listener for events from the ElevatorModel; in other words, the ElevatorModel sends all events generated in the model to the ElevatorView.
Every method implementing an interface receives an event object of type ElevatorModelEvent (or a subclass) as a parameter. For example, the doorOpened method
Appendix I |
Elevator View (on CD) |
1461 |
receives a DoorEvent. Appendix G contains further reference on events and listeners. The following sections discuss the types of events that the ElevatorView handles.
I.5.1 ElevatorMoveEvent types
The ElevatorModel sends an ElevatorMoveEvent when the Elevator has either departed or arrived in the model. The ElevatorModel invokes method elevatorDeparted (lines 435–493) when the Elevator has departed from a Floor. Lines 441–475 determine if an AnimatedPanel associated with a Person overlaps the elevatorPanel by iterating personAnimatedPanels and testing whether any AnimatedPanel in the List has an on-screen x-coordinate greater than that of the elevatorPanel. If this is the case, then the Person is inside the Elevator, and lines 465–468 add the AnimatedPanel associated with that Person to the elevatorPanel. Regardless of whether a Person is inside the Elevator, lines 478–515 set the elevatorPanel’s velocity according to the direction the Elevator must travel. Line 500 plays the elevatorMusic.
The ElevatorModel invokes method elevatorArrived (lines 496–515) when the Elevator has arrived at a Floor. Line 499 stops the elevatorPanel, and line 512 stops the elevatorMusic. Lines 506–513 change the direction of the elevatorPanel for the next travel.
I.5.2 PersonMoveEvent types
The ElevatorModel sends a PersonMoveEvent when a Person has performed some action in the model that the ElevatorView must represent. The ElevatorModel invokes method personCreated (lines 518–582) when the model instantiates a new Person. Lines 526–527 instantiate an AnimatedPanel for a Person. Lines 531–545 determine on which Floor to situate the AnimatedPanel, depending on the Floor on which the event was generated. Lines 548–553 add frame sequences to the AnimatedPanel describing the Person walking and pressing a Button. Lines 556–572 animate the Person walking, determine the Person’s velocity necessary to reach the Button on the Floor and play the sound effect of footsteps. Lastly, lines 575–580 add the AnimatedPanel associated with the Person to List personAnimatedPanels, using a synchronized block (lines 575–578) to guarantee no other object can access the List.
The ElevatorModel invokes method personArrived (lines 585–604) when a Person has arrived at the Elevator. Line 588 calls method getPersonPanel (lines 414–432), which determines the AnimatedPanel associated with the Person that issued the event. Specifically, method getPersonPanel iterates List personAnimatedPanels and returns the AnimatedPanel whose identifier matches the identifier of the PersonMoveEvent. Lines 590–603 in method personArrived stop this AnimatedPanel from moving. Line 596 stops the sound of footsteps by calling method stopWalkingSound (lines 397–411), which stops the AudioClip playing the footstep sound only if no Persons are walking.
The ElevatorModel invokes method personPressedButton (lines 607–623) when a Person pressed a Button. Line 610 determines the AnimatedPanel associated with the Person who pressed the Button. Line 616 calls method playAnimation, which plays the animation sequence of that Person pressing the Button.
1462 |
Elevator View (on CD) |
Appendix I |
The ElevatorModel invokes method personEntered (lines 626–647) when a Person is about to enter the Elevator. Line 629 retrieves the AnimatedPanel associated with the Person entering the Elevator. Line 634–640 determine the velocity needed to walk into the Elevator. Line 643–645 animate this AnimatedPanel to walk in the elevatorPanel.
The ElevatorModel invokes method personDeparted (lines 650–697) when a Person is about to exit the Elevator. Line 653 determines the AnimatedPanel associated with the Person departing from the Elevator. Lines 658–661 determine that Person’s velocity needed to walk to across the Floor to exit the simulation. Lines 664– 688 position the AnimatedPanel associated with the Person on the Floor in front of the Elevator by removing the AnimatedPanel from the elevatorPanel and adding the AnimatedPanel to the ElevatorView. Lines 691–695 animate this AnimatedPanel to walk across either the firstFloorPanel or secondFloorPanel and start the sound of footsteps.
The ElevatorModel invokes method personExited (lines 700–718) when a Person has exited from the simulation. Line 703 determines the AnimatedPanel associated with the Person who exited the simulation. Lines 711–716 remove the AnimatedPanel associated with that Person from the ElevatorView and stop the sound of footsteps.
I.5.3 DoorEvent types
The ElevatorModel sends a DoorEvent to the ElevatorView when a Door has opened or closed in the model. The ElevatorModel invokes method doorOpened (lines 721–736) when a Door has opened. Lines 724–730 animate the doorPanel opening, and lines 733–734 plays the doorOpenClip, which is the sound effect associated with the Door’s opening.
The ElevatorModel invokes method doorClosed (lines 739–754) when a Door has closed. Lines 742–748 animate the doorPanel closing, and lines 751–752 plays the doorClosedClip, which is the sound effect associated with the Door’s closing.
I.5.4 ButtonEvent types
The ElevatorModel sends a ButtonEvent to the ElevatorView when a Button has been pressed or reset in the model. The ElevatorModel invokes method buttonPressed (lines 757–786) when a Button has been pressed. Lines 760–761 determine the Location where the Button was pressed. If the Location is the Elevator, then lines 764–767 play the Button pressed animation inside the Elevator. If the Location is the first Floor, then lines 772–767 play the Button pressed animation on the first Floor. If the Location is the second Floor, then lines 778–781 play the Button pressed animation on the second Floor being pressed. Lines 783–784 play the buttonClip, which is the sound effect associated with the Button being pressed.
The ElevatorModel invokes method buttonReset (lines 789–829) when a Button has been reset. Lines 792–793 determine the Location where the Button was reset. If the Location is the Elevator, then lines 796–803 change the elevatorButtonPanel’s image to that of the Button reset. If the Location is the first Floor, then lines 808–816 change the firstFloorButtonPanel’s image associated with the
Appendix I |
Elevator View (on CD) |
1463 |
Button reset. If the Location is the second Floor, then lines 819–827 change the secondFloorButtonPanel’s image associated with the Button reset.
I.5.5 BellEvent types
The ElevatorModel sends a BellEvent to the ElevatorView by invoking method bellRang (lines 832–838) when a Bell has rung in the model. Line 834 animates the bellPanel, and lines 836–837 play the bellClip, which is the sound effect associated with the Bell ringing.
I.5.6 LightEvent types
The ElevatorModel sends a LightEvent to the ElevatorView when a Light has changed state in the model. The ElevatorModel invokes method lightTurnedOn (lines 841–858) when a Light has turned on. Line 844 turns on elevatorLightPanel. Lines 846–856 determine on which Floor the Light has turned on, then illuminates the AnimatedPanel associated with that Light in the ElevatorView.
The ElevatorModel invokes method lightTurnedOff (lines 861–878) when a Light has turned off. Line 864 turns on elevatorLightPanel. Lines 866–876 determine on which Floor the Light has turned on, then turns off the AnimatedPanel associated with that Light in the ElevatorView.
I.6 Component Diagrams Revisited
In Section 13.17, we introduced the component diagram for the elevator simulation, and in Appendix G and Appendix H, we added components to packages event and model, respectively. Figure I.5 presents the component diagram for package view, which contains components ElevatorView.java, ImagePanel.java, MovingPanel.java, AnimatedPanel.java, ElevatorMusic.java and SoundEffects.java. ElevatorView.java aggregates packages images, sounds and event. Packages images and sounds contain all image files and sound files (components) used by ElevatorView.java, respectively. The diagram does not show the components of these directories, because there exist far to many graphics and audio files to represent on one page—the contents of these packages can be found in the directory structures
com/deitel/jhtp4/elevator/view/images
com/deitel/jhtp4/elevator/view/sounds
(i.e., in the images and sounds directory where the classes for the view are located in the file system).
I.7 Conclusion
Congratulations! You have completed an “industrial-strength” OOD/UML case study. You are well prepared to tackle more substantial design problems and to go on to deeper study of OOD with the UML. Hopefully you have developed a greater appreciation and understanding of design and implementation processes. Now, you can use Java to implement substantial object-oriented system designs generated by the UML. We hope you have
1464 |
Elevator View (on CD) |
Appendix I |
enjoyed using Java and the UML to construct this case study while learning what features the two technologies have to offer. In addition, we hope you have enjoyed using Java’s GUI, graphics and sound capabilities, while learning important object-oriented and Javarelated concepts, such as classes, objects, GUI construction, inheritance, event handling and multithreading.
|
view |
|
|
|
|
<<file>> |
|
|
|
|
|
ElevatorView.java |
|
|
|
1 |
1 |
1 |
|
|
<<file>> |
|
<<file>> |
|
|
ImagePanel.java |
|
MovingPanel.java |
|
|
<<file>> |
|
<<file>> |
|
|
AnimatedPanel.java |
ElevatorMusic.java |
|
|
|
<<file>> |
|
|
|
|
SoundEffects.java |
|
|
|
|
|
1 |
|
|
1 |
images |
sounds |
event |
1 |
|
|
Fig. I.5 Component diagram for package view.
J
Career Opportunities
(on CD)
Objectives
•To explore the various online career services.
•To examine the advantages and disadvantages of posting and finding jobs online.
•To review the major online career services Web sites available to job seekers.
•To explore the various online services available to employers seeking to build their workforces.
What is the city but the people?
William Shakespeare
A great city is that which has the greatest men and women, If it be a few ragged huts it is still the greatest city in the whole world.
Walt Whitman
To understand the true quality of people, you must look into their minds, and examine their pursuits and aversions.
Marcus Aurelius
The soul is made for action, and cannot rest till it be employed. Idleness is its rust. Unless it will up and think and taste and see, all is in vain.
Thomas Traherne
1466 Career Opportunities (on CD) Appendix J
Outline
J.1 |
Introduction |
|
J.2 |
Resources for the Job Seeker |
|
J.3 |
Online Opportunities for Employers |
|
|
|
|
|
J.3.1 |
Posting Jobs Online |
|
J.3.2 Problems with Recruiting on the Web |
|
|
|
|
|
J.3.3 Diversity in the Workplace |
|
J.4 |
Recruiting Services |
|
|
J.4.1 Testing Potential Employees Online |
|
J.5 |
Career Sites |
|
|
J.5.1 |
Comprehensive Career Sites |
|
|
|
|
J.5.2 |
Technical Positions |
|
J.5.3 |
Wireless Positions |
|
|
|
|
J.5.4 |
Contracting Online |
|
J.5.5 |
Executive Positions |
|
|
|
|
J.5.6 Students and Young Professionals |
|
|
J.5.7 Other Online Career Services |
|
J.6 |
Internet and World Wide Web Resources |
|
|
|
|
Summary • Terminology • Self-Review Exercises • Answers to Self-Review Exercises • Exercises • Works Cited
J.1 Introduction
There are approximately 40,000 career-advancement services on the Internet today.1 These services include large, comprehensive job sites, such as Monster.com (see the upcoming Monster.com feature), as well as interest-specific job sites such as JustJavaJobs.com. Companies can reduce the amount of time spent searching for qualified employees by building a recruiting feature on their sites or establishing an account with a career site. This results in a larger pool of qualified applicants, as online services can automatically select and reject resumes based on user-designated criteria. Online interviews, testing services and other resources also expedite the recruiting process.
Applying for a position online is a relatively new method of exploring career opportunities. Online recruiting services streamline the process and allow job seekers to concentrate their energies in careers that are of interest to them. Job seekers can explore opportunities according to geographic location, position, salary or benefits packages.
Job seekers can learn how to write a resume and cover letter, post them online and search through job listings to find the jobs that best suit their needs. Entry-level positions, or positions commonly sought by individuals who are entering a specific field or the job market for the first time; contracting positions; executive-level positions and middle-man- agement-level positions are all available on the Web.
Appendix J |
Career Opportunities (on CD) |
1467 |
Job seekers will find a number of time-saving features when searching for a job online. These include storing and distributing resumes digitally, e-mail notification of possible positions, salary and relocation calculators, job coaches, self-assessment tools and information on continuing education.
In this appendix, we explore online career services from the employer and employee’s perspective. We suggest sites on which applications can be submitted, jobs can be searched for and applicants can be reviewed. We also review services that build recruiting pages directly into an e-business.
J.2 Resources for the Job Seeker
Finding a job online can greatly reduce the amount of time spent applying for a position. Instead of searching through newspapers and mailing resumes, job seekers can request a specific position in a specific industry through a search engine. Some sites allow job seekers to setup intelligent agents to find jobs that meet their requirements. Intelligent agents are programs that search and arrange large amounts of data, and report answers based on that data. When the agent finds a potential match, it sends it to the job seeker’s inbox. Resumes can be stored digitally, customized quickly to meet job requirements and e-mailed instantaneously. Potential candidates can also learn more about a company by visiting its Web site. Most employment sites are free to job seekers. These sites typically generate their revenues by charging employers for posting job opportunities and by selling advertising space on their Web pages (see the Monster.com feature).
Career services, such as FlipDog.com, search a list of employer job sites to find positions. By searching links to employer Web sites, FlipDog.com is able to identify positions from companies of all sizes. This feature enables job seekers to find jobs that employers may not have posted outside the corporation’s Web site.
Monster.com
Super Bowl ads and effective marketing have made Monster.com one of the most recognizable online brands (see Fig. B.1). In fact, in the 24 hours following Super Bowl XXXIV, 5 million job searches occurred on Monster.com.2 The site allows people looking for jobs to post their resumes, search job listings, read advice and information about the job-search process and take proactive steps to improve their careers. These services are free to job seekers. Employers can post job listings, search resume databases and become featured employers.
Posting a resume at Monster.com is simple and free. Monster.com has a resume builder that allows users to post a resume to its site in 15–30 minutes. Each user can store up to 5 resumes and cover letters on the Monster.com server. Some companies offer their employment applications directly through the Monster.com site. Monster.com has job postings in every state and all major categories. Users can limit access to their personal identification information. As one of the leading recruiting sites on the Web, Monster.com is a good place to begin a job search or to find out more about the search process.
1468 |
Career Opportunities (on CD) |
Appendix J |
Monster.com (Cont.)
Fig. J.1 The Monster.com home page. (Courtesy of Monster.com.)
Job seekers can visit FlipDog.com and choose, by state, the area in which they are looking for a position. Applicants can also conduct worldwide searches. After a user selects a region, FlipDog.com requests the user to specify a job category containing several specific positions. The user’s choice causes a list of local employers to appear. The user can choose a specific employer or request that FlipDog.com search the employment databases for jobs offered by all employers (see Fig. B.2).
Other services, such as employment networks, also help job seekers in their search. Sites such as Vault.com (see the Vault.com feature) and WetFeet.com allow job seekers to post questions about employers and positions in designated chat rooms and on bulletin boards.
J.3 Online Opportunities for Employers
Recruiting on the Internet provides several benefits over traditional recruiting. For example, Web recruiting reaches a much larger audience than posting an advertisement in a local newspaper. Given the breadth of the services provided by most online career services Web sites, the cost of posting online can be considerably less expensive than posting positions through traditional means. Even newspapers, which depend greatly on career opportunity advertising, are starting online career sites.3
Appendix J |
Career Opportunities (on CD) |
1469 |
Fig. J.2 FlipDog.com job search. (Courtesy of Flipdog.com.)
Vault.com: Finding the Right Job on the Web4
Vault.com allows potential employees to seek out additional, third-party information for over 3000 companies. By visiting the Insider Research page, Web users have access to a profile on the company of their choice, as long as it exists in Vault.com’s database. In addition to Vault.com’s profile, there is a link to additional commentary by company employees. Most often anonymous, these messages can provide prospective employees with potentially valuable decision-making information. However, users must consider the integrity of the source. For example, a disgruntled employee may leave a posting that is not an accurate representation of the corporate culture of his or her company.
The Vault.com Electronic Watercooler™ is a message board that allows visitors to post stories, questions and concerns and to advise employees and job seekers. In addition, the site provides e-newsletters and feature stories designed to help job seekers in their search. Individuals seeking information on business, law and graduate schools can also find information on Vault.com.
Job-posting and career-advancement services for the job seeker are featured on Vault.com. These services include VaultMatch, a career service that e-mails job postings as requested, and Salary Wizard™, which helps job seekers determine the salary they are worth. Online guides with advice for fulfilling career ambitions are also available.
1470 |
Career Opportunities (on CD) |
Appendix J |
Vault.com: Finding the Right Job on the Web4 (Cont.)
Employers can also use the site. HR Vault, a feature of Vault.com, provides employers with a free job-posting site. It offers career-management advice, employer- to-employee relationship management and recruiting resources.
e-Fact J.1
According to Forrester Research, 33 percent of today’s average company’s hiring budget goes toward online career services, while the remaining 66 percent is used toward traditional recruiting mechanisms. Online use is expected to increase to 42 percent by 2004, while traditional mechanisms may be reduced to 10 percent.5
Generally, jobs posted online are viewed by a larger number of job seekers than jobs posted through traditional means. However, it is important not to overlook the benefits of combining online efforts with human-to-human interaction. There are many job seekers who are not yet comfortable with the process of finding a job online. Often, online recruiting is used as a means of freeing up a recruiter’s time for the interviewing process and final selection.
e-Fact J.2
Cisco Systems cites a 39 percent reduction in cost-per-hire expenses, and a 60 percent re- duction in the time spent hiring.6
J.3.1 Posting Jobs Online
When searching for job candidates online, there are many things employers need to consider. The Internet is a valuable tool for recruiting, but one that takes careful planning to acquire the best results. It provides a good supplementary tool, but should not be considered the complete solution for filling positions. Web sites, such as WebHire (www.webhire.com), enhance a company’s online employment search (see the WebHire feature).
There are a variety of sites that allow employers to post jobs online. Some of these sites require a fee, which generally runs between $100–200. Postings typically remain on the Web site for 30–60 days. Employers should be careful to post to sites that are most likely to be visited by eligible candidates. As we discovered in the previous section, there are a variety of online career services focused on specific industries, and many of the larger, more comprehensive sites have categorized their databases by job category.
When designing a posting, the recruiter should consider the vast number of postings already on the Web. Defining what makes the job position unique, including information such as benefits and salary, might convince a qualified candidate to further investigate the position (see Fig. B.3).7
HotJobs.com career postings are cross-listed on a variety of other sites, thus increasing the number of potential employees who see the job listings. Like Monster.com and jobfind.com, hotjobs.com requires a fee per listing. Employers also have the option of becoming HotJob.com members. Employers can gain access to HotJob’s Private Label Job Boards (private corporate employment sites), online recruiting technology and online career fairs.
Appendix J |
Career Opportunities (on CD) |
1471 |
WebHire™8
Designed specifically for recruiters and employers, WebHire is a multifaceted service that provides employers with end-to-end recruiting solutions. The service offers jobposting services as well as candidate searches. The most comprehensive of the services, WebHire™ Enterprise, locates and ranks candidates found through resume-scanning mechanisms. Clients will also receive a report indicating the best resources for their search. Other services available through the WebHire™ Employment Services Network include preemployment screening, tools for assessing employees’ skill levels and information on compensation packages. An employment law advisor helps organizations design interview questions.
WebHire™ Agent is an intelligent agent that searches for qualified applicants based on job specifications. When WebHire Agent identifies a potential candidate, an e-mail is automatically sent to the candidate to generate interest. WebHire Agent then ranks applicants according to the skills information it gains from the Web search; the information is stored so that new applicants are distinguished from those who have already received an e-mail from the site.
Yahoo!® Resumes, a feature of WebHire, allows recruiters to find potential employees by typing in keywords on the Yahoo! Resumes search engine. Employers can purchase a year’s membership to the recruiting solution for a flat fee; there are no per-use charges.
Job Seeker’s Criteria
Position (responsibilities)
Salary
Location
Benefits (health, dental, stock options)
Advancement
Time Commitment
Training Opportunities
Tuition Reimbursement
Corporate Culture
Fig. J.3 List of a job seeker’s criteria.
Boston Herald Job Find (www.jobfind.com) also charges employers to post on its site. The initial fee entitles the employer to post up to three listings. Employers have no limitations on the length of their postings.
Other Web sites providing employers with employee recruitment services include
CareerPath.com, America’s Job Bank (www.ajb.dni.us/employer), CareerWeb (www.cweb.com), Jobs.com and Career.com.
1472 |
Career Opportunities (on CD) |
Appendix J |
J.3.2 Problems with Recruiting on the Web
The large number of applicants presents a challenge to both job seekers and employers. On many recruitment sites, matching resumes to positions is conducted by resume-filtering software. The software scans a pool of resumes for keywords that match the job description. While this software increases the number of resumes that receive attention, it is not a foolproof system. For example, the resume-filtering software might overlook someone with similar skills to those listed in the job description, or someone whose abilities would enable them to learn the skills required for the position. Digital transmissions can also create problems because certain software platforms are not always acceptable by the recruiting software. This sometimes results in an unformatted transmission, or a failed transmission.
A lack of confidentiality is another disadvantage of online career services. In many cases, a job candidate will want to search for job opportunities anonymously. This reduces the possibility of offending the candidate’s current employer. Posting a resume on the Web increases the likelihood that the candidate’s employer might come across it when recruiting new employees. The traditional method of mailing resumes and cover letters to potential employers does not impose the same risk.
According to recent studies, the number of individuals researching employment positions through traditional means, such as referrals, newspapers and temporary agencies, far outweighs the number of job seekers researching positions through the Internet.9 Optimists feel, however, that this disparity is largely due to the early stages of e-business development. Given time, online career services will become more refined in their posting and searching capabilities, decreasing the amount of time it takes for a job seeker to find jobs and employers to fill positions.
J.3.3 Diversity in the Workplace
Every workplace inevitably develops its own culture. Responsibilities, schedules, deadlines and projects all contribute to a working environment. Perhaps the most defining elements of a corporate culture are the employees. For example, if all employees were to have the same skills and the same ideas, the workplace would lack diversity. It might also lack creativity and enthusiasm. One way to increase the dynamics of an organization is to employ people of all backgrounds and cultures.
The Internet hosts demographic-specific sites for employers seeking to increase diversity in the workplace. By recruiting people from different backgrounds, new ideas and perspectives are brought forth, helping businesses meet the needs of a larger, more diverse target audience.10
Blackvoices.com and hirediversity.com are demographic-specific Web sites. BlackVoices™, which functions primarily as a portal (a site offering news, sports and weather information, as well as the ability to search the Web), features job searching capabilities and the ability for prospective employees to post resumes. HireDiversity is divided into several categories, including opportunities for African Americans, Hispanics and women. Other online recruiting services place banner advertisements on ethnic Web sites for companies seeking diverse workforces.
The Diversity Directory (www.mindexchange.com) offers international careersearching capabilities. Users selecting the Diversity site can find job opportunities, information and additional resources to help them in their career search. The site can be searched
Appendix J |
Career Opportunities (on CD) |
1473 |
according to demographics (African American, Hispanic, alternative lifestyle, etc.) or by subject (employer, position, etc.) via hundreds of links. Featured sites include BilingualJobs.com, Latin World and American Society for Female Entrepreneurs.
Many sites have sections dedicated to job seekers with disabilities. In addition to providing job-searching capabilities, these sites include additional resources, such as equal opportunity documents and message boards. The National Business and Disability Council (NBDC) provides employers with integration and accessibility information for employing people with disabilities, and the site also lists opportunities for job seekers.
J.4 Recruiting Services
There are many services on the Internet that help employers match individuals to positions. The time saved by conducting preliminary searches on the Internet can be dedicated to interviewing qualified candidates and making the best matches possible.
Advantage Hiring, Inc. (www.advantagehiring.com) provides employers with a resume-screening service. When a prospective employee submits a resume for a particular position, Advantage Hiring, Inc. presents Net-Interview™, a small questionnaire to supplement the information presented on the resume. The site also offers SiteBuilder, a service that helps employers build an employee recruitment site. An online demonstration can be found at www.advantagehiring.com. The demonstration walks the user through the Net-Interview software, as well as a number of other services offered by Advantage Hiring (see Fig. B.4).
Recruitsoft.com is an application service provider (ASP) that offers companies recruiting software on a pay-per-hire basis (Recruitsoft receives a commission on hires made via its service). Recruiter WebTop™ is the company’s online recruiting software. It includes features such as Web-site hosting, an employee-referral program, skill-based resume screening, applicant-tracking capabilities and job-board posting capabilities. A demonstration of Recruiter WebTop’s Corporate Recruiting Solutions can be found at www.recruitsoft.com/process. The demonstration shows how recruiting solutions find and rank potential candidates. More information about Recruitsoft’s solution can be viewed in a QuickTime media player demonstration, found at www.recruitsoft.com/corpoVideo.
Peoplescape.com is an online service that helps employers recruit employees and maintain a positive work environment once the employee has been hired. In addition to searches for potential candidates, Peoplescape offers PayCheck™, LegalCheck™ and PeopleCheck™. These services help to ensure that compensation offers are adequate, legal guidelines are met and candidates have provided accurate information on their resumes and during the hiring process. For job seekers, Peoplescape offers searching capabilities, insights to career transitions, a job compensation calculator that takes benefits and bonuses into consideration when exploring a new job possibility and a series of regularly posted articles relevant to the job search.11
To further assist companies in their recruiting process, Web sites such as Refer.com reward visitors for successful job referrals. Highly sought-after positions can earn thousands of dollars. If a user refers a friend or a family member and he or she is hired, the user receives a commission.
Other online recruiting services include SkillsVillage.com, Hire.com, MorganWorks.com and Futurestep.com™.
1474 |
Career Opportunities (on CD) |
Appendix J |
Fig. J.4 Advantage Hiring, Inc.’s Net-Interview™ service. (Courtesy of Advantage Hiring, Inc.)
J.4.1 Testing Potential Employees Online
The Internet also provides employers with a cost-effective means of testing their prospective employees in such categories as decision making, problem solving and personality. Services such eTest help to reduce the cost of in-house testing and to make the interview process more effective. Test results, given in paragraph form, present employers with the interested individual’s strengths and weaknesses. Based on these results, the report suggests interview methods, such as asking open-ended questions, which are questions that require more than a “yes” or “no” response. Sample reports and a free-trial test can be found at www.etest.net.
Employers and job seekers can also find career placement exercises at www.advisorteam.net/AT/User/kcs.asp. Some of these services require a fee. The tests ask several questions regarding the individual’s interests and working style. Results help candidates determine the best career for their skills and interests.
Appendix J |
Career Opportunities (on CD) |
1475 |
J.5 Career Sites
Online career sites can be comprehensive or industry specific. In this section, we explore a variety of sites on the Web that accommodate the needs of both the job seeker and the employer. We review sites offering technical positions, free-lancing opportunities and contracting positions.
J.5.1 Comprehensive Career Sites
As mentioned previously, there are many sites on the Web that provide job seekers with career opportunities in multiple fields. Monster.com is the largest of these sites, attracting the greatest number of unique visitors per month. Other popular online recruiting sites include
JobsOnline.com, HotJobs.com, www.jobtrak.com and Headhunter.net. Searching for a job online can be a conducted in a few steps. For example, during an
initial visit to JobsOnline.com, a user is required to fill out a registration form. The form requests basic information, such as name, address and area of interest. After registering, members can search through job postings according to such criteria as job category, location and the number of days the job has been posted. Contact information is provided for additional communication. Registered members are offered access to XDrive™ (www.xdrive.com), which provides 25 MB of storage space for resumes, cover letters and additional communication. Stored files can be shared through any Web browser or Wireless Application Protocol (WAP)-enabled device. Driveway.com offers a similar service, allowing individuals to store, share and organize job search files online. An online demonstration of the service can be found at www.driveway.com. The animated demo walks the user through the features offered by the service. Driveway.com offers 100 MB of space, and the service is free.12 Other sites, such as Cruel World (see the Cruel World feature), allow users to store and send their resumes directly to employers.
Cruel World13
Cruel World is a free, online career advancement service for job seekers. After becoming a registered member, your information is matched with available positions in the Cruel World database. When an available job matches your criteria, JobCast®, a feature of Cruel World, sends an e-mail alerting you of the available position. If you are interested, you can send your resume to the employer that posted the position, customized to the job’s requirements. If you do not wish to continue your search, you can simply send a negative response via e-mail.
The client list, or the list of companies seeking new employees through Cruel World, can be viewed at www.cruelworld.com/corporate/aboutus.asp
(Fig. B.5). Additional features on the site include hints for salary negotiation; a selfassessment link to CareerLeader.com, where, for a small fee, members can reassess their career goals under the advisement of career counselors and a relocation calculator for job seekers who are considering changing location.
Employers seeking to hire new talent can post opportunities through Cruel World. posting positions requires a fee. A demonstration of the service can be viewed at www.cruelworld.com/clients/quicktour1.asp. The demonstration is a three-step slide of JobCast.
1476 |
Career Opportunities (on CD) |
Appendix J |
Cruel World13 (Cont.)
Fig. J.5 Cruel World online career services. (Courtesy of Cruel World.)
J.5.2 Technical Positions
Technical positions are becoming widely available as the Internet grows more pervasive. Limited job loyalty and high turnover rates in technical positions allow job seekers to find jobs that best suit their needs and skills. Employers are required to rehire continuously to keep positions filled and productivity levels high. The amount of time for an employer to fill a technical position can be greatly reduced by using an industry-specific site. Career sites designed for individuals seeking technical positions are among the most popular online career sites. In this section, we review several sites that offer recruiting and hiring opportunities for technical positions.
e-Fact J.3
It costs a company 25 percent more to hire a new technical employee than it does to pay an already employed individual’s salary.14
Dice.com (www.dice.com) is a recruiting Web site that focuses on technical fields. Company fees are based on the number of jobs the company posts and the frequency
Appendix J |
Career Opportunities (on CD) |
1477 |
with which the postings are updated. Job seekers can post their resumes and search the job database for free. JustComputerJobs.com directs job seekers toward 39 specific computer technologies for their job search. Language-specific sites include JustJavaJobs.com, JustCJobs.com and JustPerlJobs.com. Hardware, software and communications technology sites are also available. Other technology recruiting sites include HireAbility.com, Bid4Geeks.com, HotDispatch.com and www.cmpnet.com/careerdirect.
J.5.3 Wireless Positions
The wireless industry is developing rapidly. According to WirelessResumes.com, the number of wireless professionals is 328,000. This number is expected to increase 40 percent each year for the next five years. To accommodate this growth, and the parallel demand for professionals, WirelessResumes.com has created an online career site specifically for the purpose of filling wireless jobs (see the WirelessResumes.com feature).
The Caradyne Group (www.pcsjobs.com), an executive search firm, connects job seekers to employers in the wireless technology field. Interested job seekers must first fill out a “Profile Questionnaire.” This information is then entered into The Caradyne Group’s database and is automatically matched to an open position in the job seeker’s field of expertise. If there are no open positions, a qualified consultant from The Caradyne Group will contact the job seeker for further a interview and discussion. Jobs4wireless.com also provides job seekers with employment opportunities in the wireless industry.
J.5.4 Contracting Online
The Internet also serves as a forum for job seekers to find employment on a project-by- project basis. Online contracting services allow businesses to post positions for which they wish to hire outside resources, and individuals can identify projects that best suit their interests, schedules and skills.
e-Fact J.4
Approximately six percent of America’s workforce falls into the category of independent con- tractor.15
WirelessResumes.com: Filling Wireless Positions
WirelessResumes.com is an online career site focused specifically on matching wireless professionals with careers in the industry. This narrow focus enables businesses to locate new employees quickly—reducing the time and expense attached to traditional recruiting methods. Similarly, candidates can limit their searches to precisely the job category of interest. Wireless carriers, device manufacturers, WAP and Bluetooth developers, e-commerce companies and application service providers (ASPs) are among those represented on the site.
In addition to searching for jobs and posting a resume, WirelessResumes.com provides job seekers with resume writing tips, interviewing techniques, relocation tools and assistance in obtaining a Visa or the completion of other necessary paperwork. Employers can use the site to search candidates and post job opportunities.
1478 Career Opportunities (on CD) Appendix J
Guru.com (www.guru.com) is a recruiting site for contract employees. Independent contractors, private consultants and trainers use guru.com to find short-term and long-term contract assignments. Tips, articles and advice are available for contractors who wish to learn more about their industry. Other sections of the site teach users how to manage their businesses, buy the best equipment and deal with legal issues. Guru.com includes an online store where contractors can buy products associated with small-business management, such as printing services and office supplies. Companies wishing to hire contractors must register with guru.com, but individuals seeking contract assignments do not.
Monster.com’s Talent Market™ offers online auction-style career services to free agents. Interested users design a profile, listing their qualifications. After establishing a profile, free agents “Go Live” to start the bidding on their services. The bidding lasts for five days during which users can view the incoming bids. At the close of five days, the user can choose the job of his or her choice. The service is free for users, and bidding employers pay a commission on completed transactions.
eLance.com is another site where individuals can find contracting work. Interested applicants can search eLance’s database by category, including business, finance and marketing (see Fig. B.6). These projects, or requests for proposals (RFPs), are posted by companies worldwide. When users find projects for which they feel qualified, they submit bids on the projects. Bids must contain a user’s required payment, a statement detailing the user’s skills and a feedback rating drawn from other projects on which the user has worked. If a user’s bid is accepted, the user is given the project, and the work is conducted over eLance’s file-sharing system, enabling both the contractor and the employer to contact one another quickly and easily. For an online demonstration, visit www.elance.com and click on the demonstration icon.
FreeAgent (www.freeagent.com) is another site designed for contracting projects. Candidates create an e.portfolio that provides an introductory “snapshot” of their skills, a biography, a list of their experience and references. The interview section of the portfolio lists questions and the applicant’s answers. Examples of e.portfolios can be found at www.freeagent.com/splash/models.asp. Free Agent’s e.office offers a benefits package to outside contractors, including health insurance, a retirement plan and reimbursement for business-related expenses.
Other Web sites that provide contractors with projects and information include eWork® Exchange (www.ework.com), MBAFreeAgent.com, Aquent.com and WorkingSolo.com.
J.5.5 Executive Positions
Next, we discuss the advantages and disadvantages of finding an executive position online. Executive career advancement sites usually include many of the features found on comprehensive job-search sites. Searching for an executive position online differs from finding an entry-level position online. The Internet allows individuals to continually survey the job market. However, candidates for executive-level positions must exercise a higher level of caution when determining who is able to view their resume. Applying for an executive position online is an extensive process. As a result of the high level of scrutiny passed on a candidate during the hiring process, the initial criteria presented by an executive level candidate often are more specific than the criteria presented by the first-time job seeker. Executive positions often are difficult to fill, due to the high demands and large amount of experience required for the jobs.
Appendix J |
Career Opportunities (on CD) |
1479 |
Fig. J.6 eLance.com request for proposal (RFP) example. (Courtesy of eLance, Inc.]
SixFigureJobs (www.sixfigurejobs.com) is a recruitment site designed for experienced executives. Resume posting and job searching is free to job seekers. Other sites, including www.execunet.com, Monster.com’s ChiefMonster™ (www.chiefmonster.com) and www.nationjob.com are designed for helping executives find positions.
J.5.6 Students and Young Professionals
The Internet provides students and young professionals with tools to get them started in the job market. Individuals still in school and seeking internships, individuals who are just graduating and individuals who have been in the workforce for a few years make up the target market. Additional tools specifically designed for this demographic (a population defined by a specific characteristic) are available. For example, journals kept by previous interns provide prospective interns with information regarding what to look for in an internship, what to expect and what to avoid. Many sites will provide information to lead young professionals in the right direction, such as matching positions to their college or university major.
Experience.com is a career services Web site geared toward the younger population. Members can search for positions according to specific criteria, such as geo-
1480 |
Career Opportunities (on CD) |
Appendix J |
graphic location, job category, keywords, commitment (i.e. full time, part time, internship), amount of vacation and amount of travel time. After applicants register, they can send their resumes directly to the companies posted on the site. In addition to the resume, candidates provide a personal statement, a list of applicable skills and their language proficiency. Registered members also receive access to the site’s Job Agent. Up to three Job Agents can be used by each member. The agents search for available positions,
based on the criteria posted by the member. If a match is made, the site contacts the candidate via e-mail.16,17
Internshipprograms.com helps students find internships. In addition to posting a resume and searching for an internship, students can use the relocation calculator to compare the cost of living in different regions. Tips on building resumes and writing essays are provided. The City Intern program provides travel, housing and entertainment guides to interns interviewing or accepting a position in an unfamiliar city, making them feel more at home in a new location.
In addition to its internship locators, undergraduate, graduate, law school, medical school and business school services, the Princeton Review’s Web site (www.review.com) offers career services to graduating students. While searching for a job, students and young professionals can also read through the site’s news reports or even increase their vocabulary by visiting the “word for the day.” Other career sites geared toward the younger population include campuscareercenter.com, brassringcampus.com and collegegrads.com.
J.5.7 Other Online Career Services
In addition to Web sites that help users find and post jobs online, there are a number of Web sites that offer features that will enhance searches, prepare users to search online, help applicants design resumes or help users calculate the cost of relocating.
Salary.com helps job seekers gauge their expected income, based on position, level of responsibility and years of experience. The search requires job category, ZIP code and specific job title. Based on this information, the site will return an estimated salary for an individual living in the specified area and employed in the position described. Estimates are returned based on the average level of income for the position.
In addition to helping applicants find employment, www.careerpower.com provides individuals with tests that will help them realize their strengths, weaknesses, values, skills and personality traits. Based on the results, which can be up to 10–12 pages per test, users can best decide what job categories they are qualified for and what career choice will be best suited to their personal ambitions. The service is available for a fee.
InterviewSmart™ is another service offered through CareerPower that prepares job seekers of all levels for the interviewing process. The service can be downloaded for a minimal fee or can be used on the Web for free. Both versions are available at www.careerpower.com/CareerPerfect/interviewing.htm#is.start.anchor.
Additional services will help applicants find positions that meet their unique needs, or design their resumes to attract the attention of specific employers. Dogfriendly.com, organized by geographic location, helps job seekers find opportunities that allow them to bring their pets to work, and cooljobs.com is a searchable database of unique job opportunities.
Appendix J |
Career Opportunities (on CD) |
1481 |
J.6 Internet and World Wide Web Resources
Information Technology (IT) Career Sites
www.dice.com
This is a recruiting Web site that focuses on the computer industry. www.guru.com
This is a recruiting site for contract employees. Independent contractors, private consultants and trainers can use guru.com to find short-term and long-term work.
www.hallkinion.com
This is a Web recruiting service for individuals seeking IT positions.
www.techrepublic.com
This site provides employers and job seekers with recruiting capabilities and information regarding developing technology.
www.justcomputerjobs.com
This site serves as a portal with access to language-specific sites, including Java, Perl, C and C++.
www.bid4geeks.com
This career services site is geared toward the technical professional.
www.hotdispatch.com
This forum provides software developers with the opportunity to share projects, discuss code and ask questions.
www.techjobs.bizhosting.com/jobs.htm
This site directs job seekers to links of numerous technological careers listed by location, internet, type of field, etc.
Career Sites
www.careerbuilder.com
A network of career sites, including IT Careers, USA Today and MSN, CareerBuilder attracts 3 million unique job seekers per month. The site provides resume-builder and job-searching agents.
www.recruitek.com
This free site caters to jobs seekers, employers and contractors.
www.monster.com
This site, the largest of the online career sites, allows people looking for jobs to post their resumes, search job listings and read advice and information about the job-search process. It also provides a variety of recruitment services for employers.
www.jobsonline.com
Similar to Monster.com, this site provides opportunities for job seekers and employers.
www.hotjobs.com
This online recruiting site offers cross-listing possibilities on additional sites.
www.jobfind.com
This job site is an example of locally targeted job-search resources. JobFind.com targets the Boston area.
www.flipdog.com
This site allows online job candidates to search for career opportunities. It employs intelligent agents to scour the Web and return jobs matching the candidate’s request.
1482 |
Career Opportunities (on CD) |
Appendix J |
www.cooljobs.com
This site highlights unique job opportunities.
www.careerhighway.com
This site presents an opportunity for job seekers and employers to match up and register the careerspecific information for which they are searching.
www.inetsupermall.com
This site aids job searchers in creating professional resumes and connecting with employers.
www.wirelessnetworksonline.com
This site helps connect job searchers to careers for which they are qualified.
www.careerweb.com
This site highlights featured employers and jobs and allows job seekers and employers to post and view resumes, respectively.
Executive Positions
www.sixfigurejobs.com
This is a recruitment site designed for experienced executives.
www.leadersonline.com
This career services Web site offers confidential job searches for mid-level professionals. Potential job matches are e-mailed to job candidates.
www.ecruitinginc.com
This site is designed to search for employees for executive positions.
Diversity
www.latpro.com
This site is designed for Spanish-speaking and Portuguese-speaking job seekers. In addition to providing resume-posting services, the site enables job seekers to receive matching positions via e-mail. Advice and information services are available.
www.blackvoices.com
This portal site hosts a career center designed to match African American job seekers with job opportunities.
www.hirediversity.com
In addition to services for searching for and posting positions, resume-building and updating services are also available on this site. The site targets a variety of demographics including African Americans, Asian Americans, people with disabilities, women and Latin Americans.
People with Disabilities
www.halftheplanet.com
This site represents people with disabilities. The site is large and includes many different resources and information services. A special section is dedicated to job seekers and employers.
www.wemedia.com
This site is designed to meet the needs of people with disabilities. It includes a section for job seekers and employers.
www.disabilities.com
This site provides users with a host of links to information resources on career opportunities.
Appendix J |
Career Opportunities (on CD) |
1483 |
www.rileyguide.com
This site includes a section with opportunities for people with disabilities, which can be viewed at www.dbm.com/jobguide/vets.html#abled.
www.mindexchange.com
The diversity section of this site provides users with several links to additional resources regarding people with disabilities and employment.
www.usdoj.gov/crt/ada/adahom1.htm
This is the Americans with Disabilities Act home page.
www.abanet.org/disability/home.html
This is the Web site for The Commission on Mental and Physical Disability Law.
janweb.icdi.wvu.edu
The Job Accommodation Web site offers consulting services to employers regarding integration of people with disabilities into the workplace.
General Resources
www.vault.com
This site provides potential employees with “insider information” on over 3000 companies. In addition, job seekers can search through available positions and post and answer questions on the message board.
www.wetfeet.com
Similar to vault.com, this site allows visitors to ask questions and receive “insider information” on companies that are hiring.
Free Services
www.sleuth.com
On this site job seekers can fill out a form that indicates their desired field of employment. Job Sleuth™ searches the Internet and returns potential matches to the user’s inbox. The service is free.
www.ajb.org
America’s Job Bank is an online recruiting service provided through the Department of Labor and the state employment service. Searching for and posting positions on the site are free.
www.xdrive.com
This free site provides members with 25 MB of storage space for housing documents related to a user’s job search. XDrive is able to communicate with all browser types and has wireless capabilities.
www.driveway.com
Similar to XDrive.com, this Web site provides users with 100 MB of storage space. Users can back up, share and organize information about various job searches. Driveway.com works on all platforms.
Special Interest
www.eharvest.com/careers/index.cfm
This Web site provides job seekers interested in agricultural positions with online career services.
www.opportunitynocs.org
This career services site is for both employers and job seekers interested in non-profit opportunities.
www.experience.com
This Web site is designed specifically for young professionals and students seeking full-time, parttime and internship positions.
1484 |
Career Opportunities (on CD) |
Appendix J |
www.internshipprograms.com
Students seeking internships can search job listings on this site. It also features City Intern, to help interns become acquainted with a new location.
www.brassringcampus.com
This site provides college grads and young professionals with less than five years of experience with job opportunities. Additional features help users buy cars or find apartments.
Online Contracting
www.ework.com
This online recruiting site matches outside contractors with companies needing project specialists. Other services provided through eWork include links to online training sites, benefits packages and payment services and online meeting and management resources.
www.elance.com
Similar to eWork.com, eLance matches outside contractors with projects.
www.freeagent.com
FreeAgent matches contractors with projects.
www.MBAFreeAgent.com
This site is designed to match MBAs with contracting opportunities.
www.aquent.com
This site provides access to technical contracting positions.
www.WorkingSolo.com
This site helps contractors begin their own projects.
Recruiting Services
www.advantagehiring.com
This site helps employers screen resumes.
www.etest.net
This site provides employers with testing services to assess the strengths and weaknesses of prospective employees. This information can be used for better hiring strategies.
www.hire.com
Hire.com’s eRecruiter is an application service provider that helps organizations streamline their Web-recruiting process.
www.futurestep.com
Executives can register confidentially at Futurestep.com to be considered for senior executive positions. The site connects registered individuals to positions. It also offers career management services.
www.webhire.com
This site provides employers with end-to-end recruiting solutions.
Wireless Career Resources
www.wirelessresumes.com
This site connects employers and job seekers with resumes that focus on jobs revolving around wireless technology.
www.msua.org/job.htm
This site contains links to numerous wireless job-seeking Web sites.
Appendix J |
Career Opportunities (on CD) |
1485 |
www.jobs4wireless.com
This site searches for jobs in the wireless telecommunications field.
www.staffing.net
This site allows job seekers to discover openings in the world of wireless technology and communications.
www.wiwc.org
This site’s focus is wireless communication job searching for women.
www.firstsearch.com
At this site a job seeker is able to discover part-time, full-time and salary-based opportunities in the wireless industry.
www.pcsjobs.com
This is the site for The Caradyne Group, which is an executive search firm that focuses on finding job seekers wireless job positions.
www.cnijoblink.com
CNI Career Networks offers confidential, no-charge job placement in the wireless and telecommunications industries.
SUMMARY
•The Internet can improve an employer’s ability to recruit employees and help users find career opportunities worldwide.
•Job seekers can learn how to write a resume and cover letter, post them online and search through job listings to find the jobs that best suit their needs.
•Employers can post jobs that can be searched by an enormous pool of applicants.
•Job seekers can store and distribute resumes digitally, receive e-mail notification of possible positions, use salary and relocation calculators, consult job coaches and use self-assessment tools when searching for a job on the Web.
•There are approximately 40,000 career-advancement services on the Internet today.
•Finding a job online can greatly reduce the amount of time spent applying for a position. Potential candidates can also learn more about a company by visiting its Web site.
•Most sites are free to job seekers. These sites typically generate their revenues by charging employers who post their job opportunities, and by selling advertising space on their Web pages.
•Sites such as Vault.com and WetFeet.com allow job seekers to post questions about employers and positions in chat rooms and on bulletin boards.
•On many recruitment sites, the match of a resume to a position is conducted with resume-filtering software.
•A lack of confidentiality is a disadvantage of online career services.
•According to recent studies, the number of individuals researching employment positions through means other than the Internet, such as referrals, newspapers and temporary agencies, far outweighs the number of Internet job seekers.
•Career sites designed for individuals seeking technical positions are among the most popular online career sites.
•Online contracting services allow businesses to post positions for which they wish to hire outside resources, and allow individuals to identify projects that best suit their interests, schedules and skills.
•The Internet provides students and young professionals with some of the necessary tools to get them started in the job market. The target market is made up of individuals still in school and seek-
1486 |
Career Opportunities (on CD) |
Appendix J |
ing internships, individuals who are just graduating and individuals who have been in the workforce for a few years.
•There are a number of Web sites that offer features that enhance job searches, prepare users to search online, help design applicants’ resumes or help users calculate the cost of relocating.
•Web recruiting reaches a much larger audience than posting an advertisement in the local newspaper.
•There are a variety of sites that allow employers to post jobs online. Some of these sites require a fee, which generally runs between $100–200. Postings remain on the Web site for approximately 30–60 days.
•Employers should try to post to sites that are most likely to be visited by eligible candidates.
•When designing a job posting, defining what makes a job position unique and including information such as benefits and salary might convince a qualified candidate to further investigate the position.
•The Internet hosts demographic-specific sites for employers seeking to increase diversity in the workplace.
•The Internet has provided employers with a cost-effective means of testing their prospective employees in such categories as decision making, problem solving and personality.
TERMINOLOGY
corporate culture |
open-ended question |
demographic |
pay-per-hire |
end-to-end recruiting solutions |
|
entry-level position |
request for proposal (RFP) |
online contracting service |
resume-filtering software |
SELF-REVIEW EXERCISES
J.1 State whether each of the following is true or false. If false, explain why.
a)Online contracting services allow businesses to post job listings for specific projects that can be viewed by job seekers over the Web.
b)Employment networks are Web sites designed to provide information on a selected company to better inform job seekers of the corporate environment.
c)The large number of applications received over the Internet is considered an advantage by most online recruiters.
d)There is a greater number of individuals searching for work on the Web than through all other mediums combined.
e)Sixteen percent of America’s workforce is categorized as independent contractors.
J.2 |
Fill in the blanks in each of the following statements: |
|
|
||
|
a) |
There are approximately |
online career services Web sites on the Internet to- |
||
|
|
day. |
|
|
|
|
b) |
The Internet hosts demographic-specific sites for |
employers seeking to |
increase |
|
|
|
in the workplace. |
|
|
|
|
c) |
In the 24 hours following the Super Bowl, |
job searches occurred on Mon- |
||
|
|
ster.com. |
|
|
|
|
d) |
Many recruitment sites use |
to filter through received resumes. |
|
|
|
e) |
Employers should try to post to sites that are most likely to be visited by |
can- |
||
|
|
didates. |
|
|
|
Appendix J |
Career Opportunities (on CD) |
1487 |
ANSWERS TO SELF-REVIEW EXERCISES
J.1 a) True. b) True. c) False. The large number of applicants reduces the amount of time a recruiter can spend interviewing and making decisions. Despite screening processes, many highly qualified applicants can be overlooked. d) False. The number of individuals researching employment positions through other means, such as referrals, newspapers and temporary agencies, far outweighs the number of Internet job seekers. e) False. Six percent of America’s workforce is categorized as independent consultants.
J.2 a) 40,000. b) diversity. c) 5 million. d) resume-filtering software. e) eligible.
EXERCISES
J.3 State whether each of the following is true or false. If false, explain why.
a)RFP is the acronym for request for proposal.
b)The Internet has provided employers with a cost-effective means of testing their prospective employees in such categories as decision making, problem solving and personality.
c)Online job recruiting can completely replace other means of hiring employees.
d)Posting a job online is less expensive than placing ads in more traditional media.
e)A lack of confidentiality is a disadvantage of online career services.
J.4 Fill in the blanks in each of the following statements:
a) Finding a job online can greatly |
|
the amount of time spent applying for a po- |
sition. |
|
|
b)is an example of a Web site in which contractors can bid on projects.
c)When designing a job posting, defining what makes the position unique and including
|
information such as |
|
|
and |
|
|
|
might convince a qualified candidate |
||||
|
to further investigate the position. |
|
|
|
|
|
|
|
||||
d) |
The Internet hosts |
|
|
for employers seeking to increase diversity in the work- |
||||||||
|
place. |
|
|
|
|
|
|
|
|
|
|
|
e) |
The Internet provides employers with a cost-effective means of testing their prospective |
|||||||||||
|
employees in such categories as |
|
|
, |
|
|
and |
. |
||||
|
|
|
|
|
|
|
|
|
|
|
|
|
J.5 Define the following
a)corporate culture
b)pay-per-hire
c)request for proposal (RFP)
d)resume-filtering software
J.6 (Class discussion). In this appendix, we discuss the shortcomings and advantages of recruiting on the Internet. Using the text, additional reading material and personal accounts answer the following questions. Be prepared to discuss your answers.
a)Do you think finding a job is easier on the Web? Why or why not?
b)What disadvantages can you identify?
c)What are some of the advantages?
d)Which online recruiting services do you think will be most successful? Why?
J.7 Many of the career services Web sites we have discussed in this appendix offer resumebuilding capabilities. Begin building your resume, choosing an objective that is of interest to you. Think of your primary concerns. Are you searching for a paid internship or a volunteer opportunity? Do you have a specific location in mind? Do you have an opportunity for future employment? Are stock options important to you? Find several entry-level jobs that meet your requirements. Write a short summary of your results. Include any obstacles and opportunities.
1488 |
Career Opportunities (on CD) |
Appendix J |
J.8 In this appendix, we have discussed online contracting opportunities. Visit FreeAgent (www.freeagent.com) and create your own e.portfolio, or visit eLance (www.elance.com) and search the requests for proposals for contracting opportunities that interest you.
J.9 In this appendix, we have discussed many career services Web sites. Choose three sites. Explore the opportunities and resources offered by the sites. Visit any demonstrations, conduct a job search, build your resume and calculate your salary or relocation expenses. Answer the following questions.
a)Which site provides the best service? Why?
b)What did you like? Dislike?
c)Write a brief summary of your findings, including descriptions of any features that you would add.
WORKS CITED
The notation <www.domain-name.com> indicates that the citation is for information found at the Web site.
1.J. Gaskin, “Web Job Sites Face Tough Tasks,” Inter@ctive Week 14 August 2000: 50.
2.J. Gaskin, 50.
3.M. Berger, “Jobs Supermarket,” Upside November 2000: 224.
4.<www.vault.com>
5.M. Berger, 224.
6.Cisco Advertisement, The Wall Street Journal 19 October 2000: B13.
7.M. Feffer, “Posting Jobs on the Internet,” <www.webhire.com/hr/spotlight.asp>
18August 2000.
8.<www.webhire.com>
9.J. Gaskin, 51.
10.C. Wilde, “Recruiters Discover Diverse Value in Web Sites,” Information Week 7 February 2000: 144.
11.<www.jobsonline.com>
12.<www.driveway.com>
13.<www.cruelworld.com>
14.A.K. Smith, “Charting Your Own Course,” U.S. News and World Report 6 November 2000: 58.
15.D. Lewis, “Hired! By the Highest Bidder,” The Boston Globe 9 July 2000: G1.
16.<www.experience.com>
17.M. French, “Experience Inc., E-Recruiting for Jobs for College Students,” Mass High Tech 7 February–13 February 2000: 29.
K
Unicode® (on CD)
Objectives
•To become familiar with Unicode.
•To discuss the mission of the Unicode Consortium.
•To discuss the design basis of Unicode.
•To understand the three Unicode encoding forms: UTF-8, UTF-16 and UTF-32.
•To introduce characters and glyphs.
•To discuss the advantages and disadvantages of using Unicode.
•To provide a brief tour of the Unicode Consortium’s Web site.
1490 |
Unicode® (on CD) |
Appendix K |
Outline
K.1 Introduction
K.2 Unicode Transformation Formats
K.3 Characters and Glyphs
K.4 Advantages/Disadvantages of Unicode
K.5 Unicode Consortium’s Web Site
K.6 Using Unicode
K.7 Character Ranges
Summary • Terminology • Self-Review Exercises • Answers to Self-Review Exercises • Exercises
K.1 Introduction
The use of inconsistent character encodings (i.e., numeric values associated with characters) when developing global software products causes serious problems because computers process information using numbers. For instance, the character “a” is converted to a numeric value so that a computer can manipulate that piece of data. Many countries and corporations have developed their own encoding systems that are incompatible with the encoding systems of other countries and corporations. For example, the Microsoft Windows operating system assigns the value 0xC0 to the character “A with a grave accent” while the Apple Macintosh operating system assigns that same value to an upside-down question mark. This results in the misrepresentation and possible corruption of data because data is not processed as intended.
In the absence of a widely-implemented universal character encoding standard, global software developers had to localize their products extensively before distribution. Localization includes the language translation and cultural adaptation of content. The process of localization usually includes significant modifications to the source code (such as the conversion of numeric values and the underlying assumptions made by programmers), which results in increased costs and delays releasing the software. For example, some Englishspeaking programmers might design global software products assuming that a single character can be represented by one byte. However, when those products are localized in Asian markets, the programmer’s assumptions are no longer valid, thus the majority, if not the entirety, of the code needs to be rewritten. Localization is necessary with each release of a version. By the time a software product is localized for a particular market, a newer version, which needs to be localized as well, is ready for distribution. As a result, it is cumbersome and costly to produce and distribute global software products in a market where there is no universal character encoding standard.
In response to this situation, the Unicode Standard, an encoding standard that facilitates the production and distribution of software, was created. The Unicode Standard outlines a specification to produce consistent encoding of the world’s characters and symbols. Software products which handle text encoded in the Unicode Standard need to be localized, but the localization process is simpler and more efficient because the numeric values need not be converted and the assumptions made by programmers about the character encoding are universal. The Unicode Standard is maintained by a non-profit organization called the
Appendix K |
Unicode® (on CD) |
1491 |
Unicode Consortium, whose members include Apple, IBM, Microsoft, Oracle, Sun Microsystems, Sybase and many others.
When the Consortium envisioned and developed the Unicode Standard, they wanted an encoding system that was universal, efficient, uniform and unambiguous. A universal encoding system encompasses all commonly used characters. An efficient encoding system allows text files to be parsed easily. A uniform encoding system assigns fixed values to all characters. An unambiguous encoding system represents a given character in a consistent manner. These four terms are referred to as the Unicode Standard design basis.
K.2 Unicode Transformation Formats
Although Unicode incorporates the limited ASCII character set (i.e., a collection of characters), it encompasses a more comprehensive character set. In ASCII each character is represented by a byte containing 0s and 1s. One byte is capable of storing the binary numbers from 0 to 255. Each character is assigned a number between 0 and 255, thus ASCII-based systems can support only 256 characters, a tiny fraction of world’s characters. Unicode extends the ASCII character set by encoding the vast majority of the world’s characters. The Unicode Standard encodes all of those characters in a uniform numerical space from 0 to 10FFFF hexadecimal. An implementation will express these numbers in one of several transformation formats, choosing the one that best fits the particular application at hand.
Three such formats are in use, called UTF-8, UTF-16 and UTF-32, depending on the size of the units—in bits—being used. UTF-8, a variable width encoding form, requires one to four bytes to express each Unicode character. UTF-8 data consists of 8-bit bytes (sequences of one, two, three or four bytes depending on the character being encoded) and is well suited for ASCII-based systems when there is a predominance of one-byte characters (ASCII represents characters as one-byte). Currently, UTF-8 is widely implemented in UNIX systems and in databases.
The variable width UTF-16 encoding form expresses Unicode characters in units of 16-bits (i.e., as two adjacent bytes, or a short integer in many machines). Most characters of Unicode are expressed in a single 16-bit unit. However, characters with values above FFFF hexadecimal are expressed with an ordered pair of 16-bit units called surrogates. Surrogates are 16-bit integers in the range D800 through DFFF, which are used solely for the purpose of “escaping” into higher numbered characters. Approximately one million characters can be expressed in this manner. Although a surrogate pair requires 32-bits to represent characters, it is space-efficient to use these 16-bit units. Surrogates are rare characters in current implementations. Many string-handling implementations are written in terms of UTF-16. [Note: Details and sample-code for UTF-16 handling are available on the Unicode Consortium Web site at www.unicode.org.]
Implementations that require significant use of rare characters or entire scripts encoded above FFFF hexadecimal, should use UTF-32, a 32-bit fixed-width encoding form that usually requires twice as much memory as UTF-16 encoded characters. The major advantage of the fixed-width UTF-32 encoding form is that it uniformly expresses all characters, so it is easy to handle in arrays.
There are few guidelines that state when to use a particular encoding form. The best encoding form to use depends on computer systems and business protocols, not on the data itself. Typically, the UTF-8 encoding form should be used where computer systems and business protocols require data to be handled in 8-bit units, particularly in legacy systems
1492 |
Unicode® (on CD) |
Appendix K |
being upgraded because it often simplifies changes to existing programs. For this reason, UTF-8 has become the encoding form of choice on the Internet. Likewise, UTF-16 is the encoding form of choice on Microsoft Windows applications. UTF-32 is likely to become more widely used in the future as more characters are encoded with values above FFFF hexadecimal. Also, UTF-32 requires less sophisticated handling than UTF-16 in the presence of surrogate pairs.
Figure K.1 shows the different ways in which the three encoding forms handle character encoding.
K.3 Characters and Glyphs
The Unicode Standard consists of characters, written components (i.e., alphabets, numbers, punctuation marks, accent marks, etc.) that can be represented by numeric values. Examples of characters include: U+0041 LATIN CAPITAL LETTER A. In the first character representation, U+yyyy is a code value, in which U+ refers to Unicode code values, as opposed to other hexadecimal values. The yyyy represents a four-digit hexadecimal number of an encoded character. Code values are bit combinations that represent encoded characters. Characters are represented using glyphs, various shapes, fonts and sizes for displaying characters. There are no code values for glyphs in the Unicode Standard. Examples of glyphs are shown in Fig. K.2.
The Unicode Standard encompasses the alphabets, ideographs, syllabaries, punctuation marks, diacritics, mathematical operators, etc. that comprise the written languages and scripts of the world. A diacritic is a special mark added to a character to distinguish it from another letter or to indicate an accent (e.g., in Spanish, the tilde “~” above the character “n”). Currently, Unicode provides code values for 94,140 character representations, with more than 880,000 code values reserved for future expansion.
Character |
UTF-8 |
UTF-16 |
UTF-32 |
|
|
|
|
LATIN CAPITAL LETTER A |
0x41 |
0x0041 |
0x00000041 |
GREEK CAPITAL LETTER |
0xCD 0x91 |
0x0391 |
0x00000391 |
ALPHA |
|
|
|
CJK UNIFIED IDEOGRAPH- |
0xE4 0xBA 0x95 |
0x4E95 |
0x00004E95 |
4E95 |
|
|
|
OLD ITALIC LETTER A |
0xF0 0x80 0x83 0x80 |
0xDC00 0xDF00 |
0x00010300 |
Fig. K.1 Correlation between the three encoding forms.
Fig. K.2 Various glyphs of the character A.
Appendix K |
Unicode® (on CD) |
1493 |
K.4 Advantages/Disadvantages of Unicode
The Unicode Standard has several significant advantages that promote its use. One is the impact it has on the performance of the international economy. Unicode standardizes the characters for the world’s writing systems to a uniform model that promotes transferring and sharing data. Programs developed using such a schema maintain their accuracy because each character has a single definition (i.e., a is always U+0061, % is always U+0025). This enables corporations to manage the high demands of international markets by processing different writing systems at the same time. Also, all characters can be managed in an identical manner, thus avoiding any confusion caused by different character code architectures. Moreover, managing data in a consistent manner eliminates data corruption, because data can be sorted, searched and manipulated using a consistent process.
Another advantage of the Unicode Standard is portability (i.e., software that can execute on disparate computers or with disparate operating systems). Most operating systems, databases, programming languages and Web browsers currently support, or are planning to support, Unicode.
A disadvantage of the Unicode Standard is the amount of memory required by UTF16 and UTF-32. ASCII character sets are 8-bits in length, so they require less storage than the default 16-bit Unicode character set. However, the double-byte character set (DBCS) and the multi-byte character set (MBCS) that encode Asian characters (ideographs) require two to four bytes, respectively. In such instances, the UTF-16 or the UTF-32 encoding forms may be used with little hindrance on memory and performance.
Another disadvantage of Unicode is that although it includes more characters than any other character set in common use, it does not yet encode all of the world’s written characters.
Another disadvantage of the Unicode Standard is that UTF-8 and UTF-16 are variable width encoding forms, so characters occupy different amounts of memory.
K.5 Unicode Consortium’s Web Site
If you would like to learn more about the Unicode Standard, visit www.unicode.org. This site provides a wealth of information about the Unicode Standard that is insightful to those new to Unicode. Currently, the home page is organized into various sections—New to Unicode, General Information, The Consortium, The Unicode Standard, Work in Progress and For Members.
The New to Unicode section consists of two subsections: What is Unicode and How to Use this Site. The first subsection provides a technical introduction to Unicode by describing design principles, character interpretations and assignments, text processing and Unicode conformance. This subsection is recommended reading for anyone new to Unicode. Also, this subsection provides a list of related links that provide the reader with additional information about Unicode. The How to Use this Site subsection contains information about using and navigating the site as well hyperlinks to additional resources.
The General Information section contains six subsections: Where is my Character,
Display Problems, Useful Resources, Enabled Products, Mail Lists and Conferences. The main areas covered in this section include a link to the Unicode code charts (a complete listing of code values) assembled by the Unicode Consortium as well as a detailed outline on how to locate an encoded character in the code chart. Also, the section contains advice on how to configure different operating systems and Web browsers so that
1494 |
Unicode® (on CD) |
Appendix K |
the Unicode characters can be viewed properly. Moreover, from this section, the user can navigate to other sites that provide information on various topics such as, fonts, linguistics and other standards such as the Armenian Standards Page and the Chinese GB 18030 Encoding Standard.
The Consortium section consists of five subsections: Who we are, Our Members, How to Join, Press Info and Contact Us. This section provides a list of the current Unicode Consortium members as well as information on how to become a member. Privileges for each member type—full, associate, specialist and individual—and the fees assessed to each member are listed here.
The Unicode Standard section consists of nine subsections: Start Here, Latest Version, Technical Reports, Code Charts, Unicode Data, Update & Errata, Unicode Policies, Glossary and Technical FAQ. This section describes the updates applied to the latest version of the Unicode Standard as well as categorizing all defined encoding. The user can learn how the latest version has been modified to encompass more features and capabilities. For instance, one enhancement of Version 3.1 is that it contains additional encoded characters. Also, if users are unfamiliar with vocabulary terms used by the Unicode Consortium, then they can navigate to the Glossary subsection.
The Work in Progress section consists of three subsections: Calendar of Meetings,
Proposed Characters and Submitting Proposals. This section presents the user with a catalog of the recent characters included into the Unicode Standard scheme as well as those characters being considered for inclusion. If users determine that a character has been overlooked, then they can submit a written proposal for the inclusion of that character. The Submitting Proposals subsection contains strict guidelines that must be adhered to when submitting written proposals.
The For Members section consists of two subsections: Member Resources and Working Documents. These subsections are password protected; only consortium members can access these links.
K.6 Using Unicode
Numerous programming languages (e.g., C, Java, JavaScript, Perl, Visual Basic, etc.) provide some level of support for the Unicode Standard. Figure K.3 shows a Java program that prints the text “Welcome to Unicode!” in eight different languages: English, Russian, French, German, Japanese, Portuguese, Spanish and Traditional Chinese. [Note: The Unicode Consortium’s Web site contains a link to code charts that lists the 16-bit Unicode code values.]
1// Fig. K.3: Unicode.java
2 // Demonstrating how to use Unicode in Java programs.
3
4 // Java core packages
5 import java.awt.*;
6
7 // Java extension packages
8 import javax.swing.*;
9
Fig. K.3 Java program that uses Unicode encoding (part 1 of 3).
Appendix K |
Unicode® (on CD) |
1495 |
10public class Unicode extends JFrame {
11private JLabel english, chinese, cyrillic, french, german,
12japanese, portuguese, spanish;
13
14// Unicode constructor
15public Unicode()
16{
17super( "Demonstrating Unicode" );
19// get content pane and set its layout
20Container container = getContentPane();
21container.setLayout( new GridLayout( 8, 1 ) );
23// JLabel constructor with a string argument
24english = new JLabel( "\u0057\u0065\u006C\u0063\u006F" +
25"\u006D\u0065\u0020\u0074\u006F\u0020Unicode\u0021" );
26english.setToolTipText( "This is English" );
27container.add( english );
28
29 chinese = new JLabel( "\u6B22\u8FCE\u4F7F\u7528\u0020" +
30"\u0020Unicode\u0021" );
31chinese.setToolTipText( "This is Traditional Chinese" );
32container.add( chinese );
33 |
|
|
34 |
cyrillic = new JLabel( "\u0414\u043E\u0431\u0440\u043E" |
+ |
35 |
"\u0020\u043F\u043E\u0436\u0430\u043B\u043E\u0432" + |
|
36"\u0430\u0422\u044A\u0020\u0432\u0020Unicode\u0021" );
37cyrillic.setToolTipText( "This is Russian" );
38container.add( cyrillic );
39 |
|
|
40 |
french = new JLabel( "\u0042\u0069\u0065\u006E\u0076" |
+ |
41 |
"\u0065\u006E\u0075\u0065\u0020\u0061\u0075\u0020" |
+ |
42"Unicode\u0021" );
43french.setToolTipText( "This is French" );
44container.add( french );
45 |
|
|
46 |
german = new JLabel( "\u0057\u0069\u006C\u006B\u006F" |
+ |
47 |
"\u006D\u006D\u0065\u006E\u0020\u007A\u0075\u0020" |
+ |
48"Unicode\u0021" );
49german.setToolTipText( "This is German" );
50container.add( german );
51
52 japanese = new JLabel( "Unicode\u3078\u3087\u3045\u3053" +
53"\u305D\u0021" );
54japanese.setToolTipText( "This is Japanese" );
55container.add( hiragana );
56 |
|
57 |
portuguese = new JLabel( "\u0053\u00E9\u006A\u0061\u0020" + |
58 |
"\u0042\u0065\u006D\u0076\u0069\u006E\u0064" + |
59"\u006F\u0020Unicode\u0021" );
60portuguese.setToolTipText( "This is Portuguese" );
61container.add( portuguese );
62
Fig. K.3 Java program that uses Unicode encoding (part 2 of 3).
1496 |
Unicode® (on CD) |
Appendix K |
|
|
|
63 |
spanish = new JLabel( "\u0042\u0069\u0065\u006E\u0076" + |
|
64 |
"\u0065\u006E\u0069\u0064\u0061\u0020\u0061\u0020" + |
65"Unicode\u0021" );
66spanish.setToolTipText( "This is Spanish" );
67container.add( spanish );
68
69 } // end Unicode constructor
70
71// execute application
72public static void main( String args[] )
73{
74Unicode application = new Unicode();
75application.setDefaultCloseOperation(
76JFrame.EXIT_ON_CLOSE );
77application.pack();
78application.setVisible( true );
80 } // end method main
81
82 } // end class Unicode
Fig. K.3 Java program that uses Unicode encoding (part 3 of 3).
The Unicode.java program uses escape sequences to represent characters. An escape sequence is in the form \uyyyy, where yyyy represents the four-digit hexadecimal code value. Lines 24 and 25 contain the series of escape sequences necessary to print “Welcome to Unicode!” in English. The first escape sequence (\u0057) equates to the character “W,” the second escape sequence (\u0065) equates to the character “e,” and so on. The \u0020 escape sequence (line 25) is the encoding for the space character. The \u0074 and \u006F escape sequences equate to the word “to.” Note that “Unicode” is not encoded because it is a registered trademark and has no equivalent translation in most languages. Line 25 also contains the \u0021 escape sequence for the exclamation mark (!).
Lines 29–65 contain the escape sequences for the other seven languages. The English, French, German, Portuguese and Spanish characters are located in the Basic Latin block, the Japanese characters are located in the Hiragana block, the Russian characters are located in the Cyrillic block and the Traditional Chinese characters are located in the CJK Unified Ideographs block.
[Note: To display the output of Unicode.java properly, copy the font.properties.zh file to the font.properties files (located in the C:\Program Files\JavaSoft\JRE\1.3.1\lib and in the C:\jdk1.3.1\jre\lib directories). Save the contents of font.properties prior to overwriting them with the contents from font.properties.zh.
Appendix K |
Unicode® (on CD) |
1497 |
K.7 Character Ranges
The Unicode Standard assigns code values, which range from 0000 (Basic Latin) to E007F (Tags), to the written characters of the world. Currently, there are code values for 94,140 characters. To simplify the search for a character and its associated code value, the Unicode Standard generally groups code values by script and function (i.e., Latin characters are grouped in a block, mathematical operators are grouped in another block, etc.). As a rule, a script is a single writing system that is used for multiple languages (e.g., the Latin script is used for English, French, Spanish, etc.). The Code Charts page on the Unicode Consortium Web site lists all the defined blocks and their respective code values. Figure K.4 lists some blocks (scripts) from the Web site and their range of code values.
SUMMARY
•Before Unicode, software developers were plagued by the use of inconsistent character encoding (i.e., numeric values for characters). Most countries and organizations had their own encoding systems, which were incompatible. A good example is the individual encoding systems on the Windows and Macintosh platforms.
Script |
Range of Code Values |
|
|
Arabic |
U+0600–U+06FF |
Basic Latin |
U+0000–U+007F |
Bengali (India) |
U+0980–U+09FF |
Cherokee (Native America) |
U+13A0–U+13FF |
CJK Unified Ideographs (East Asia) |
U+4E00–U+9FAF |
Cyrillic (Russia and Eastern Europe) |
U+0400–U+04FF |
Ethiopic |
U+1200–U+137F |
Greek |
U+0370–U+03FF |
Hangul Jamo (Korea) |
U+1100–U+11FF |
Hebrew |
U+0590–U+05FF |
Hiragana (Japan) |
U+3040–U+309F |
Khmer (Cambodia) |
U+1780–U+17FF |
Lao (Laos) |
U+0E80–U+0EFF |
Mongolian |
U+1800–U+18AF |
Myanmar |
U+1000–U+109F |
Ogham (Ireland) |
U+1680–U+169F |
Runic (Germany and Scandinavia) |
U+16A0–U+16FF |
Sinhala (Sri Lanka) |
U+0D80–U+0DFF |
Telugu (India) |
U+0C00–U+0C7F |
Thai |
U+0E00–U+0E7F |
Fig. K.4 Some character ranges.
1498 |
Unicode® (on CD) |
Appendix K |
•Computers process data by converting characters to numeric values. For instance, the character “a” is converted to a numeric value so that a computer can manipulate that piece of data.
•Localization of global software requires significant modifications to the source code, which results in the increased cost and delays releasing the product.
•Localization is necessary with each release of a version. By the time a software product is localized for a particular market, a newer version, which needs to be localized as well, is ready for distribution. As a result, it is cumbersome and costly to produce and distribute global software products in a market where there is no universal character encoding standard.
•The Unicode Consortium developed the Unicode Standard in response to the serious problems created by multiple character encodings and the use of those encodings.
•The Unicode Standard facilitates the production and distribution of localized software. It outlines a specification for the consistent encoding of the world’s characters and symbols.
•Software products which handle text encoded in the Unicode Standard need to be localized, but the localization process is simpler and more efficient because the numeric values need not be converted.
•The Unicode Standard is designed to be universal, efficient, uniform and unambiguous.
•A universal encoding system encompasses all commonly used characters; an efficient encoding system parses text files easily; a uniform encoding system assigns fixed values to all characters; and a unambiguous encoding system represents the same character for any given value.
•Unicode extends the limited ASCII character set to include all the major characters of the world.
•Unicode makes use of three Unicode Transformation Formats (UTF): UTF-8, UTF-16 and UTF32, each of which may be appropriate for use in different contexts.
•UTF-8 data consists of 8-bit bytes (sequences of one, two, three or four bytes depending on the character being encoded) and is well suited for ASCII-based systems when there is a predominance of one-byte characters (ASCII represents characters as one-byte).
•UTF-8 is a variable width encoding form that is more compact for text involving mostly Latin characters and ASCII punctuation.
•UTF-16 is the default encoding form of the Unicode Standard. It is a variable width encoding form that uses 16-bit code units instead of bytes. Most characters are represented by a single 16-bit unit, but some characters require surrogate pairs.
•Without surrogate pairs, the UTF-16 encoding form can only encompass 65,000 characters, but with the surrogate pairs, this is expanded to include over a million characters.
•UTF-32 is a 32-bit encoding form. The major advantage of the fixed-width encoding form is that it uniformly expresses all characters, so that they are easy to handle in arrays and so forth.
•The Unicode Standard consists of characters. A character is any written component that can be represented by a numeric value.
•Characters are represented using glyphs, which are various shapes, fonts and sizes for displaying characters.
•Code values are bit combinations that represent encoded characters. The Unicode notation for a code value is U+yyyy in which U+ refers to the Unicode code values, as opposed to other hexadecimal values. The yyyy represents a four-digit hexadecimal number.
•Currently, the Unicode Standard provides code values for 94,140 character representations.
•An advantage of the Unicode Standard is its impact on the overall performance of the international economy. Applications that conform to an encoding standard can be processed easily by computers.
•Another advantage of the Unicode Standard is its portability. Applications written in Unicode can be easily transferred to different operating systems, databases, Web browsers, etc. Most companies currently support, or are planning to support Unicode.
Appendix K |
Unicode® (on CD) |
1499 |
•To obtain more information about the Unicode Standard and the Unicode Consortium, visit www.unicode.org. It contains a link to the code charts, which contain the 16-bit code values for the currently encoded characters.
•Numerous programming languages provide some level of support for the Unicode Standard.
•In Java programs, the \uyyyy escape sequence represents a character, where yyyy is the four-digit hexadecimal code value. The \u0020 escape sequence is the universal encoding for the space character.
TERMINOLOGY
\uyyyy escape sequence |
portability |
ASCII |
script |
block |
surrogate |
character |
symbol |
character set |
unambiguous (Unicode design basis) |
code value |
Unicode Consortium |
diacritic |
Unicode design basis |
double-byte character set (DBCS) |
Unicode Standard |
efficient (Unicode design basis) |
Unicode Transformation Format (UTF) |
encode |
uniform (Unicode design basis) |
escape sequence |
universal (Unicode design basis) |
glyph |
UTF-8 |
hexadecimal notation |
UTF-16 |
localization |
UTF-32 |
multi-byte character set (MBCS) |
|
SELF-REVIEW EXERCISES
K.1 |
Fill in the blanks in each of the following. |
|
|
|||
|
a) |
Global software developers had to |
|
|
their products to a specific market before |
|
|
|
distribution. |
|
|
||
|
b) |
The Unicode Standard is an |
|
standard that facilitates the uniform production |
||
|
|
and distribution of software products. |
|
|
c) |
The four |
design |
basis that |
constitute the Unicode Standard are: |
, |
|||||||||
|
|
|
, |
|
|
|
and |
. |
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|||
d) |
A |
|
|
|
|
is the smallest written component the can be represented with a numeric |
||||||||
|
value. |
|
|
|
|
|
|
|
|
|
|
|
|
|
e) |
Software that can execute on different operating systems is said to be |
|
|
. |
|
K.2 State whether each of the following is true or false. If false, explain why.
a)The Unicode Standard encompasses all the world’s characters.
b)A Unicode code value is represented as U+yyyy, where yyyy represents a number in binary notation.
c)A diacritic is a character with a special mark that emphasizes an accent.
d)Unicode is portable.
e)When designing Java programs, the escape sequence is denoted by/uyyyy.
SELF-REVIEW ANSWERS
K.1 a) localize. b) encoding. c) universal, efficient, uniform, unambiguous. d) character. e) portable.
1500 |
Unicode® (on CD) |
Appendix K |
K.2 a) False. It encompasses the majority of the world’s characters. b) False. The yyyy represents a hexadecimal number. c) False. A diacritic is a special mark added to a character to distinguish it from another letter or to indicate an accent. d) True. e) False. The escape sequence is denoted by
\uyyyy.
EXERCISES
K.3 Navigate to the Unicode Consortium Web site (www.unicode.org) and write the hexadecimal code values for the following characters. In which block were they located?
a)Latin letter ‘Z.’
b)Latin letter ‘n’ with the ‘tilde (~).’
c)Greek letter ‘delta.’
d)Mathematical operator ‘less than or equal to.’
e)Punctuation symbol ‘open quote (“).’
K.4 Describe the Unicode Standard design basis.
K.5 Define the following terms:
a)code value.
b)surrogates.
c)Unicode Standard.
K.6 Define the following terms:
a)UTF-8.
b)UTF-16.
c)UTF-32.
K.7 Describe a scenario where it is optimal to store your data in UTF-16 format.
K.8 Using the Unicode Standard code values, write a Java program that prints your first and last name. The program should print your name in all uppercase letters and in all lowercase letters. If you know other languages, print your first and last name in those languages as well.