Archive for September, 2007

Web design course - 146 Introduction to Java Applets Chapter 3 b)

Monday, September 10th, 2007

146 Introduction to Java Applets Chapter 3 b) If class Double provides method parseDouble to convert a Stringto a double and class Integer provides method parseIntto convert a String to an int, then class Floatprobably provides method to convert a String to a float. c) Data type declares a double-precision floating-point variable. d) The or a browser can be used to execute a Java applet. e) To load an applet into a browser you must first define a(n) file. f) The and HTML tags specify that an applet should be loaded into an applet container and executed. 3.5 State whether each of the following is true or false. If false, explain why. a) All browsers support Java 2. b) When using an import of the form javax.swing.*, all classes in the package are imported. c) You do not need import statements if the full package name and class name are specified each time you refer to a class in a program. 3.6 Write an applet that asks the user to enter two floating-point numbers, obtains the two numbers from the user and draws the sum, product (multiplication), difference and quotient (division) of the two numbers. Use the techniques shown in Fig. 3.12. 3.7 Write an applet that asks the user to enter two floating-point numbers, obtains the numbers from the user and displays the larger number followed by the words islarger as a string on the applet. If the numbers are equal, print the message Thesenumbersareequal. Use the techniques shown in Fig. 3.12. 3.8 Write an applet that inputs three floating-point numbers from the user and displays the sum, average, product, smallest and largest of these numbers as strings on the applet. Use the techniques shown in Fig. 3.12. 3.9 Write an applet that inputs from the user the radius of a circle as a floating-point number and draws the circle s diameter, circumference and area. Use the value 3.14159 for p. Use the techniques shown in Fig. 3.12. [Note: You may also use the predefined constant Math.PI for the value of p. This constant is more precise than the value 3.14159. Class Math is defined in the java.lang package, so you do not need to import it.] Use the following formulas (r is the radius): diameter = 2r circumference = 2pr area = pr2 3.10 Write an applet that draws a box, an oval, an arrow and a diamond using asterisks (*) as follows: ********* *** * * * * * * *** * * * * * * ***** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ********* *** * * 3.11 Write an applet that reads five integers and determines and prints the largest and smallest integers in the group. Use only the programming techniques you learned in this chapter and Chapter 2. Draw the results on the applet. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 3 Introduction to Java Applets 145 SELF-REVIEW (Cedant web hosting)

Sunday, September 9th, 2007

Chapter 3 Introduction to Java Applets 145 SELF-REVIEW EXERCISES 3.1 Fill in the blanks in each of the following. a) Class provides methods for drawing. b) Java applets begin execution with a series of three method calls: , and . c) Methods and display lines and rectangles. d) Keyword indicates that a new class is a subclass of an existing class. e) Every Java applet should extend either class or class . f) Java s eight primitive data types are , , , , ,, and . 3.2 State whether each of the following is true or false. If false, explain why. a) To draw a rectangle, method drawRect requires four arguments that specify two points on the applet. b) Method drawLine requires four arguments that specify two points on the applet to draw a line. c) Type Doubleis a primitive data type. d) Data type int is used to declare a floating-point number. e) Method Double.parseDouble converts a String to a primitive double value. 3.3 Write Java statements to accomplish each of the following: a) Display a dialog asking the user to enter a floating-point number. b) Convert a String to a floating-point number and store the converted value in double variable age. Assume that the String is stored in stringValue. c) Draw the message “This is a Java program” on one line on an applet (assume you are defining this statement in the applet s paintmethod) at position (10, 10). d) Draw the message “This is a Java program” on two lines on an applet (assume these statements are defined in applet method paint) starting at position (10, 10) and where the first line ends with Java. Make the two lines start at the same x coordinate. ANSWERS TO SELF-REVIEW EXERCISES 3.1 a) Graphics. b) init, start, paint. c) drawLine, drawRect. d) extends. e) JApplet, Applet. f) byte, short, int, long, float, double, charand boolean. 3.2 a) False. Method drawRect requires four arguments two that specify the upper-left corner of the rectangle and two that specify the width and height of the rectangle. b) True. c) False. Type Double is a class in the java.lang package. Remember that names that start with a capital letter are normally class names. d) False. Data type double or data type float can be used to declare a floating-point number. Data type int is used to declare integers. e) True. 3.3 a) stringValue = JOptionPane.showInputDialog( “Enter a floating-point number” ); b) age = Double.parseDouble( stringValue ); c) g.drawString( “This is a Java program”, 10, 10 ); d) g.drawString( “This is a Java”, 10, 10 ); g.drawString( “program”, 10, 25 ); EXERCISES 3.4 Fill in the blanks in each of the following: a) Data type declares a single-precision floating-point variable. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

144 Introduction to Java Applets Chapter 3 (Web design conference)

Sunday, September 9th, 2007

144 Introduction to Java Applets Chapter 3 Method Double.parseDouble (a static method of class Double) converts its String argument to a double floating-point value. Class Double is part of the package java.lang. Method drawRect draws a rectangle based on its four arguments. The first two integer values represent the upper-left x-coordinate and upper-left y-coordinate where the Graphicsobject begins drawing the rectangle. The third and fourth arguments are non-negative integers that represent the width of the rectangle in pixels and the height of the rectangle in pixels, respectively. To use the features of Java 2 in an applet, Sun provides the Java Plug-in to bypass a browser s Java support and use a complete version of the Java 2 Runtime Environment (J2RE) that is installed on the user s local computer. To specify that an applet should use the Java Plug-in rather than the browser s Java support, use the HTML Converter to convert the applet s and tags in the HTML file to indicate that the applet container should use the Plug-in to execute the applet. Sun provides the Java Plug-in 1.3 HTML Converter to perform the conversion for you. TERMINOLOGY applet int primitive type applet container interface tag invoke a method Applet menu JApplet class appletviewer java.awt package boolean primitive type Java Plug-in browser Java 2 Runtime Environment (J2RE) built-in data type javax.swing package byteprimitive type local variable char primitive type logic error command-line argument long primitive type coordinate message create an object method call derived class Microsoft Internet Explorer doubleprimitive data type Netscape Communicator Double.parseDoublemethod object double-precision floating-point number paint method of class JApplet drawLine method of class Graphics parameter list drawRect method of class Graphics pixel (picture element) drawString method of class Graphics primitive data type extends keyword Quit menu item float primitive type references floating-point number Reload menu item Graphics class short primitive type heightof an applet single-precision floating-point number HTML Converter source code HTML tag start method of class JApplet Hypertext Markup Language (HTML) subclass import statement superclass information hiding text file init method of class JApplet widthof an applet instance variable World Wide Web instantiate an object Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Cool web site - Chapter 3 Introduction to Java Applets 143

Saturday, September 8th, 2007

Chapter 3 Introduction to Java Applets 143 Many HTML codes (referred to as tags) come in pairs. HTML tags begin with a left angle bracket < and end with a right angle bracket >. Normally, the applet and its corresponding HTML file are stored in the same directory on disk. The first component of the tag indicates the file containing the compiled applet class. The second and third components of the tag indicate the width and the heightof the applet in pixels. Generally, each applet should be less than 800 pixels wide and 600 pixels tall. The appletviewer only understands the and HTML tags, so it is sometimes referred to as the minimal browser. It ignores all other HTML tags. Method drawLine of class Graphics draws lines. The method requires four arguments representing the two end points of the line on the applet the x-coordinate and y-coordinate of the first end point in the line and the x-coordinate and y-coordinate of the second end point in the line. All coordinate values are specified with respect to the upper-left corner (0, 0) coordinate of the applet. Primitive data type double stores double-precision floating-point numbers. Primitive data type float stores single-precision floating-point numbers. A double requires more memory to store a floating-point value, but stores it with approximately twice the precision of a float (15 significant digits for double vs. seven significant digits for float). The importstatements are not required if you always use the complete name of a class, including the full package name and class name (e.g., java.awt.Graphics). The asterisk (*) notation after a package name in an importindicates that all classes in the package should be available to the compiler so the compiler can ensure that the classes are used correctly. This allows programmers to use the shorthand name (the class name by itself) of any class from the package in the program. Every instance (object) of a class contains one copy of each of that class s instance variables. Instance variables are declared in the body of a class definition, but not in the body of any method of that class definition. An important benefit of instance variables is that their identifiers can be used in all methods of the class. Variables defined in the body of a method are known as local variables and can be used only in the body of the method in which they are defined. Instance variables are always assigned a default value, and local variables are not. Method initnormally initializes the applet s instance variables (if they need to be initialized to a value other than their default value) and performs any tasks that should occur only once when the applet begins execution There are actually two types of variables in Java primitive data type variables and references. References refer to objects in a program. References actually contain the location in the computer s memory of an object. A reference is used to send messages to (i.e., call methods on) the object in memory. As part of the message (method call), we provide the data (arguments) that the method requires to do its task. A variable is similar to an object. The primary difference between a variable and an object is that an object is defined by a class definition that can contain both data (instance variables) and methods, whereas a variable is defined by a primitive (or built-in) data type (one of char, byte, short, int, long, float, doubleor boolean) that can contain only data. A variable can store exactly one value at a time, whereas one object can contain many individual data members. If the data type used to declare a variable is a class name, the identifier is a reference to an object and that reference can be used to send messages to (call methods on) that object. If the data type used to declare a variable is one of the primitive data types, the identifier is a variable that can be used to store in memory or retrieve from memory a single value of the declared primitive type. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

142 Introduction to Java Applets (Yahoo web hosting) Chapter 3 each

Friday, September 7th, 2007

142 Introduction to Java Applets Chapter 3 each of which may pick up and discharge passengers at every floor in a large building? 3. For simplicity, we have given our elevator and each floor a capacity of one passenger. What problems and opportunities do you foresee in being able to increase these capacities? SUMMARY Applets are Java programs that can be embedded in Hypertext Markup Language (HTML) documents (i.e., Web pages). When a browser loads a Web page containing an applet, the applet downloads into the Web browser and begins execution. In the appletviewer, you can execute an applet again by clicking the appletviewer s Applet menu and selecting the Reload option from the menu. To terminate an applet, click the applet- viewer s Applet menu and select the Quit option. Class Graphicsis located in package java.awt. Import the Graphics class so the program can draw graphics. Class JApplet is located in package javax.swing. When you create an applet in Java, you must import the JApplet class. Java uses inheritance to create new classes from existing class definitions. Keyword extends followed by a class name indicates the class from which a new class inherits. In the inheritance relationship, the class following extends is called the superclass or base class and the new class is called the subclass or derived class. Using inheritance results in a new class definition that has the attributes (data) and behaviors (methods) of the superclass as well as the new features added in the subclass definition. A benefit of extending class JApplet is that someone else already has defined what it means to be an applet. The appletviewerand World Wide Web browsers that support applets expect every Java applet to have certain capabilities (attributes and behaviors), and class JApplet already provides those capabilities. Classes are used as templates or blueprints to instantiate (or create) objects in memory for use in a program. An object (or instance) is a region in the computer s memory in which information is stored for use by the program. The term object normally implies that attributes (data) and behaviors (methods) are associated with the object and that those behaviors perform operations on the attributes of the object. Method paintis one of three methods (behaviors) that an applet container calls when any applet begins execution. These three methods are init, start and paint, and they are guaranteed to be called in that order. The parameter list is where methods receive data required to complete their tasks. Normally, this data is passed by the programmer to the method through a method call (also known as invoking a method). In the case of method paint, the applet container calls the method and passes the Graphics argument. Method drawString of class Graphicsdraws a string at the specified location on the applet. The first argument to drawString is the String to draw. The last two arguments in the list are the coordinates (or position) at which the string should be drawn. Coordinates are measured from the upper-left (0, 0) coordinate of the applet in pixels. You must create an HTML (Hypertext Markup Language) file to load an applet into an applet container, so the applet container can execute the applet. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 3 Introduction to Java Applets 141 firstFloorLight (Web hosting company)

Friday, September 7th, 2007

Chapter 3 Introduction to Java Applets 141 firstFloorLight : Light : ElevatorModel firstFloor : Floor firstFloorDoor : FloorDoor : ElevatorDoor : ElevatorShaft : Elevator : Bell firstFloorButton: FloorButton : ElevatorButton secondFloor : Floor secondFloorButton : FloorButtonsecondFloorDoor : FloorDoor secondFloorLight : Light Fig. 3.2424 Object diagram of an empty building in our elevator model. Fig. Now we have identified the classes for our system (although we may discover others in later phases of the design process). In Thinking About Objects, Section 4.14, we determine the attributes for each of these classes, and in Thinking About Objects, Section 5.11, we use these attributes to examine how the system changes over time and to introduce its behavioral aspects. As we expand our knowledge, we will discover new information that will enable us to describe our classes more completely. Because the real world is inherently object oriented, it will be quite natural for you to pursue this project, even though you might have just begun your study of object orientation. Questions 1. Why might it be more complicated to implement a three-story (or taller) building? 2. It is common for large buildings to have many elevators. We will see in Chapter 9 that once we have created one elevator object, it is easy to create as many as we like. What problems or opportunities do you foresee in having several elevators, Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Web design templates - 140 Introduction to Java Applets Chapter 3 Creates

Thursday, September 6th, 2007

140 Introduction to Java Applets Chapter 3 Creates Light ElevatorModel Floor FloorDoor ElevatorDoor ElevatorShaft Elevator Bell FloorButton ElevatorButton Person Presses Presses 1 1 1 1 1 1 1 1 22 1 1 1 1 1 1 1 2 1 1 0..* 2 1 Requests 1 1 Rides 1 1 Signals to move Resets Resets Walks across Opens Opens 1 Rings Turns on/off Signals arrival 1 1 1 1 Fig. 3.2323 Class diagram for the elevator model. Fig. Object Diagrams The UML also defines object diagrams, which are similar to class diagrams in that both diagrams model the structure of the system. However, object diagrams model objects (instances of classes) at a specific time in program execution. Object diagrams present a snapshot of the structure while the system is running, providing information about which objects are participating in the system at a definite point in time. Object diagrams represent relationships between objects as solid lines these relationship are called links. Figure 3.24 models a snapshot of the system when no people are in the building (i.e., no objects of class Personexist in the system at this point in time). Objects usually are written in the form objectName:ClassName objectNamerefers to the name of the object, and ClassNamerefers to the class to which that object belongs. All names in an object diagram are underlined. The UML permits us to omit the object names for objects in the diagram where there exists only one object of that class (e.g., one object of class Bellat the bottom of the diagram). In large systems, object diagrams can contain many objects. This can result in cluttered, hard-to-read diagrams. If the name of a particular object is unknown, or if it is not necessary to include the name (i.e., we care only about the object type), we can disregard the object name and display only the colon and the class name. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 3 Introduction to Java Applets 139 Requests (Hosting your own web site)

Wednesday, September 5th, 2007

Chapter 3 Introduction to Java Applets 139 Requests FloorButton ElevatorShaft Elevator 1 1 1 2 2 1 Resets Signals arrival Fig. 3.2121 Class diagram showing associations among classes. Fig. Symbol Meaning 0 None. 1 One. m An integer value. 0..1 Zero or one. m, n m or n m..n At least m, but not more than n. * Zero or more. 0..* Zero or more 1..* One or more Fig. 3.2222 Multiplicity types. Fig. Figure 3.23 shows the complete class diagram for the elevator model. We model all classes that we created, as well as the associations between these classes. [Note: In Chapter 9, we expand our class diagram by using the object-oriented concept of inheritance.] Class ElevatorModelis represented near the top of the diagram and aggregates one object of class ElevatorShaft and two objects of class Floor. The Elevator- Shaftclass is an aggregation of one object of class Elevatorand two objects each of classes Light, FloorDoor and FloorButton. (Notice the two-to-one relationships between each of these classes and ElevatorShaft.) Class Elevatoris an aggregation of classes ElevatorDoor, ElevatorButtonand Bell. Class Personhas associations with both FloorButton and ElevatorButton (and other classes, as we will soon see). The association name Presses and the name-direction arrowheads indicate that the object of class Person presses these buttons. The object of class Person also rides the object of class Elevatorand walks across the object of class Floor. The name Requests indicates that an object of class FloorButton requests the object of class Elevator. The name Signalstomoveindicates that the object of class Elevator- Button signals the object of class Elevator to move to the other floor. The diagram indicates many other associations, as well. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

138 Introduction to Java Applets Chapter 3 (Business web hosting) Elevator

Wednesday, September 5th, 2007

138 Introduction to Java Applets Chapter 3 Elevator Fig. 3.20 Representing a class in the UML. Classes relate to one another via associations. Figure 3.21 shows how our classes ElevatorShaft, Elevatorand FloorButtonrelate to one another. Notice that the rectangles in this diagram are not subdivided into three sections. The UML allows the suppression of class attributes and operations in this manner to create more readable diagrams. Such a diagram is said to be an elided diagram, (i.e., some information, such as the contents for the second and bottom compartments), is not modeled. We place information in these compartments in Section 4.14 and Section 6.17, respectively. In this class diagram, a solid line that connects classes represents an association. An association is a relationship between classes. The numbers near the lines express multiplicity values. Multiplicity values indicate how many objects of a class participate in the association. From the diagram, we see that two objects of class FloorButtonparticipate in the association with one object of class ElevatorShaft, because the two Floor- Buttons are located on the ElevatorShaft. Therefore, class FloorButton has a two-to-one relationship with class ElevatorShaft; we can also say that class ElevatorShaft has a one-to-two relationship with class FloorButton. We also see that class ElevatorShaft has a one-to-one relationship with class Elevator and vice versa. Using the UML, we can model many types of multiplicity. Figure 3.22 shows the multiplicity types and how to represent them. An association can be named. For example, the word Requestsabove the line connecting classes FloorButtonand Elevator indicates the name of that association the arrow shows the direction of the association. This part of the diagram reads one object of class FloorButtonrequests one object of class Elevator. Note that associations are directional with the direction indicated by the arrowhead next to the association name so it would be improper, for example, to read the preceding association as one object of class Elevator requests one object of class FloorButton. In addition, the word Resetsindicates that one object of class ElevatorShaftresets two objects of class FloorButton. Lastly, the phrase Signals arrival indicates that one object of class Elevator signals the Elevator object s arrival to one object of class ElevatorShaft. The diamond attached to the association lines of class ElevatorShaft indicates that class ElevatorShafthas an aggregation relationship with classes FloorButton and Elevator. Aggregation implies a whole/part relationship. The class that has the aggregation symbol (the hollow diamond) on its end of an association line is the whole (in this case, ElevatorShaft), and the class on the other end of the association line is the part (in this case, classes FloorButton and Elevator). In this example, the elevator shaft has an elevator and two floor buttons. The has a/has an relationship defines aggregation (we will see in Section 9.23 that the is a/is an relationship defines inheritance). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 3 Introduction to Java Applets 137 (Top web site)

Tuesday, September 4th, 2007

Chapter 3 Introduction to Java Applets 137 model elevator shaft elevator person floor (first floor, second floor) elevator door floor door elevator button floor button bell light These categories are likely to be classes we will need to implement our system. Notice that we create one category for the buttons on the floors and one category for the button on the elevator. The two types of buttons perform different duties in our simulation the buttons on the floors summon the elevator, and the button in the elevator informs the elevator to move to the other floor. We can now model the classes in our system based on the categories we created. By convention, we capitalize class names in the design process (as we will do when we write the actual Java program that implements our design). If the name of a class contains more than one word, we run the words together and capitalize each word (e.g., Multiple- WordName). Using this convention, we create classes ElevatorModel,3 Elevator- Shaft, Elevator, Person, Floor, ElevatorDoor, FloorDoor, ElevatorButton, FloorButton, Bell and Light. We construct our system using all of these classes as building blocks. Before we begin building the system, however, we must gain a better understanding of how the classes relate to one another. Class Diagrams The UML enables us to model, via the class diagram, the classes in the elevator system and their interrelationships. Class diagrams model the structure of the system by providing the classes, or building blocks, of the system. Figure 3.20 represents class Elevator using the UML. In a class diagram, each class is modeled as a rectangle. We then divide this rectangle into three parts. The top part contains the name of the class. The middle part contains the class attributes. (We discuss attributes in Thinking About Objects Section 4.14 and Section 5.11.) The bottom part of the rectangle contains the class operations (discussed in Thinking About Objects, Section 6.17). 3. When we refer to the elevator model, we imply all classes composing the model describing the operation of our elevator system in other words, in our simulation, several classes comprise the model. We will see in Section 13.17 that our system requires a single class to represent the model we create class ElevatorModel to act as the representative for the model, because, as we will see in Fig. 3.23, ElevatorModel is the class that aggregates all other classes comprising the model. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01