Download presentation
Presentation is loading. Please wait.
1
Manipulating Data Using Methods
Chapter 3 Manipulating Data Using Methods
2
Objectives Identify, declare, and use primitive data types
Use the System class to create data streams Instantiate the BufferedReader class in code Use the readLine() method to handle user input Remind students that need to have their data disk. If they don’t have a data disk then have them follow the instructions on page xvi of book for downloading the data disk.
3
Objectives Convert strings to numbers using the parse() method
Use assignment statements to store data with proper identifiers Use operators and parentheses correctly in numeric and conditional expressions Round an answer using the round() method of the Math class No notes, just use slide.
4
Objectives Use Swing components to build the GUI for a Swing program
Use the exit() method to close a Swing program Implement an ActionListener to handle events Add interface components to an applet No notes, just use slide.
5
Objectives Use the init() and paint() methods to load the applet interface Use the actionPerformed() method Run and test an interactive applet Manage Java source code files and Java class files No notes, just use slide.
6
Introduction Data are collections of raw facts or figures
A program performs operations on input data to output information Input data can come from a variety of sources The program itself Users of the program External files No notes, just use slide.
7
The Body Mass Index Calculator
An interactive program Accepts the weight and height from the user Calculates the BMI to gauge total body fat Displays the result Three versions Mobile devices use the command prompt Notebooks use dialog boxes Web environments use an applet interface The Body Mass Index Calculator is the program that will be developed throughout this chapter. BMI is a method used by doctors to calculate total body fat by measuring the relationship of weight to height. Adults should strive for a BMI of between 20 and 24
8
Screen snapshots of the three versions of this application.
(a) console application in a command prompt window (b) console application using dialog boxes (c) applet Screen snapshots of the three versions of this application. One of the advantages of creating a console operation is that the user does not need a GUI based operating system or a mouse to run the application For example, the console versions of the program could run under UNIX or on a PDA (handheld personal digital assistant) Another reason for creating a console application is that the user interface is much easier than that of the applet. You can get the logic of the program working as a console application and then convert it to a GUI version.
9
User’s Request for New application.
10
Problem Analysis Convert user input to metric measurements
Calculate the BMI Display the result BMI is based on metric measurements, therefore user input will have to be converted. Meters = inches / 39.36 Kilograms = pounds / 2.2 BMI = kilograms / meters * meters
11
Design the Solution Design the three kinds of user interfaces with storyboards Design the logic of the program Use pseudocode for sequential flow for all programs Use an event diagram for the applet Validate the design Compare the program design with the original requirements See page 133 for storyboards Page 133 of text shows storyboard
12
This just creates a new program, we’re not coding anything yet.
Pseudo code for program and event diagram for Calculate button. Have students follow direction on Page 136, figure 3-6, to start a new Java program in Textpad. This just creates a new program, we’re not coding anything yet. Warn students not to press enter after typing in the file name: BodyMass. They have to change the “Save As” type to Java.
13
Coding the Program For simple I/O as with printlin, the java.lang package is enough. For more complex I/O you required the java.io package Import the java.io package Provides classes to support system input and output Add a throws IOException clause to the method header Warns the compiler that the possibility of input or output errors exists Gives the program the opportunity to handle input or output errors during run-time without aborting We’ll need to code the comments, a class header, and the main() method. Programmers will frequently cannibalize an old program when creating a new one. However, in this case we will create our program from scratch by following the instructions in the book. Remember from the last chapter that there are many many external packages in the Java SDK (software development kit) to assist programmers in developing code. By default, only the java.lang package is automatically included. You must import any others that you might need. This program will require the java.io package which provides classes to support system input and output. Most programs will require java.io When performing I/O, various errors can occur. A user might not have authority to access a file. A disk might not be mounted. The system might be busy with other input. By adding throws IOException to the method header, you give the program a way to help you handle many problems and still compile correctly.
14
Coding the Program Have students follow the instructions on Page 138,
public says can be accessed by anything in program static says can be accessed directly without referencing an object Normally we need to access something as class.object.method void says will not return a value main required name of console program (not reqd in applet) (String[] args) accepts 1 parm named args of type string throws IOException (see last slide) Have students follow the instructions on Page 138, figure Tell them to use their own name and the current date in the comments. Warn them, again, about case sensitivity
15
Storing Data Java is strongly typed
Variables must be declared with a data type Variable locations can hold only that data type Java has two categories of data types Primitive data types hold single data items Integers, characters, floating point, and booleans are primitive types Reference data types hold a value that refers to the location of the data All Objects and arrays are reference types There is a difference between the way character data and numeric data are stored internally. The number 15 would be stored as: 0F The character string 15 would be stored as: You can perform math on the first one, but you can’t print it. You can print the second one, but you can’t perform math on it. This aspect of character/numeric conversion is one of the biggest challenges in programming. It is almost always accomplished with the use of pre-written routines. Some programming environments, such as UNIX, will allow you to store either numeric, or character data in the same variable. For instance Number = 10 and then later Number = “ten”. This is an example of a Weakly Typed environment. Java has very strict rules on the type of data that you can put in a variable. Java is a Strongly Typed environment. Primitive data types hold data values Reference data types hold the address or location of data
16
Cover chart and then elaborate:
Boolean data types are used to store the result of comparisons. Float comes from scientists that use very large or very small numbers in a format called Scientific Notation Data entered by the user will take on a default value. You can change the default value as they did on the chart Under float 954 would normally be treated as an integer, by coding the F you can tell the system to treat it as a Float. Same thing with the D in Double and the L in Long Note, the char type will hold one and only one character. If you want more than one character then you need to use a string class.
17
Declaring Variables Because Java is Strongly Typed, you have to declare or define, your variables before you use them. This is not the case in other environments, such as UNIX. If you want to define variables with different data types, you have to have a separate declaration statement for each type. However, if you have more than one variable of the same type, you can define them all on one line, separated by commas. You can also initialize your data when you define it. Data items must be defined before they are used. Generally data items are all defined at the beginning of a method. It makes it much easier to follow and maintain a program. Have students follow the instructions on Page 142, figure 3.10 16 // declare and construct variables 17 String height, weight; 18 Int inches, pounds; 19 Double kilograms, meters, index; Tip pg 142: Sun has no suggested naming convention for variables. Customary to begin var names with lowercase
18
User Input - Streams In Java, the act of data flowing in and out of a program is called a stream The System class creates three streams when a pgm executes. The System class comes automatically packaged In java.lang. For simple I/O as with printlin, java.lang is enough. For more complex I/O you required the java.io package No notes, just use slide.
19
User Input - Streams cont.
Data from keyboards are sent in bytes, however java uses Unicode which requires 2 bytes to represent a character Data from input streams are first sent to a buffer. Since most I/P devices, such as keyboards, are very slow. This makes the process of reading data more efficient, by minimizing the number of times the system has to access the device. The java.io package contains several stream classes InputStreamReader Decodes the bytes from the System.in buffer into Unicode characters BufferedReader Increases efficiency by temporarily storing the input received from another class, such as InputStreamReader. This mean the system does not have to read every byte from the keyboard as it is entered, rather it can read a whole buffer at a time. Performing I/O is one of the most complex programming tasks. Because I/O depends on mechanical devices, it is, in CPU terms, a VERY slow process. In order to expedite the process and free the CPU to perform other tasks, most programming languages make use of Buffers to hold data. Buffers are areas of memory used to temporarily hold data. When a program requests data from a user, that data is first sent to a buffer to await processing. The techniques used to perform I/O can be very confusing to the beginning programmer. A quote from Programming with C# : One of the problems with learning a new computer language is you must use some of the advanced features before you fully understand them. For now, you can treat the declaration of the Main method [or whatever else is difficult] as tantamount to magic. There are two classes for reading and writing. Stream, or Byte, classes and Reader, or Character, Classes. Stream classes allow reading or writing bytes of data. However "Java is designed to be used internationally, and eight bits is simply not enough to handle the many different character sets used around the world. Script-based languages like Arabic and Indian languages, and pictographic languages like Chinese and Japanese, each have many more than 256 characters, the maximum that can be represented in an eight-bit code. The unification of these many character code sets is called, not surprisingly, Unicode...Both Java and XML use Unicode as their character sets, allowing you to read and write text in any of these human languages. But you have to use Readers and Writers, not streams for textual data....” From Java Cookbook by O’Reilly Publishing The Java.io package contains several classes to help you perform I/O. the InputStreamReader wraps itself around the Input buffer. InputStreamReader(System.in) In this case. System.in (see previous slide) is essentially the buffer that contains the stream input data – the raw data. InputStreamReader converts your raw data to Reader format which accepts Unicode. Finally, in order to enhance processing, the Reader data needs to be buffered and is done so by passing the data to BufferedReader
20
Using the BufferedReader class
Call the BufferedReader constructor to instantiate a BufferedReader object Instantiation is the act of constructing a new instance of an object The argument of the BufferedReader() method instantiates an InputStreamReader BufferedReader() returns a reference to the input data from System.in BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); System.in will contain the raw stream data entered by user – the individual bytes. InputStreamReader will convert the raw stream data to Reader format which is, essentially, 2 byte Unicode format. BufferedReader will take the data converted by InputStreamReader and put it in a buffer to make the I/O process more efficient. This converted data will be held in the dataIn buffer, or variable, which is a new creation of the data type BufferedReader. Tell students that if they don’t understand this at this point to just do it. Virtually all the books have this exact same example for getting input from the user. Also, remember the concept of Encapsulation – you don’t need to know the details behind what’s going. Like driving a car, you don’t need to know how an internal combustion engine works in order to drive the car.
21
BufferedReader dataIn= new BufferedReader(new
InputStreamReader(System.in)); Try going over these bullets but, again, remind students of the Nike slogan: Just Do It Have students complete the instructions in the gray box on Page 146 Point out that in the text line 20 covers two lines however this is just to fit it in the book. Students should keep typing it all on one line. If it wraps on their screen naturally, that’s fine, but don’t press enter to force a line break.
22
User Prompts, Inputs, and Conversions
The readLine() method reads a line of input text and returns a String containing the line The returned String must be explicitly converted if the data is to be used as another data type Each primitive data type has a wrapper class allowing the primitive to be treated as an object The wrapper classes provides a parse() method to convert Strings to primitives, and vice versa Example: height = dataIn.readLine(); inches = Integer.parseInt(height); height = dataIn.readLine(); The readLine() method belongs to the BufferedReader class and is used to get input from standard input (keyboard by default) When this statement is executed, readLine will get data from user and store it in the dataIn buffer one character at a time. The data in this buffer will then be assigned to the variable height. height was defined as a String (and had to be to support readLine): 17 String height, weight; Before we can perform calculations on height, it must be converted to primitive data type such as int. Primitive data types are not objects, therefore, every primitive data type has a wrapper class that allows the primitive to be treated as an object. A wrapper class provides a way to let primitive data types, such as ints to conform to their Object class counterparts such as Strings. The Integer class wraps itself around an Integer data type in order to let the data type be treated as an object. (not intuitively obvious from the syntax in next line) inches = Integer.parseInt(height); height is defined as string, inches is defined as: int Integer is the wrapper class. The Integer class, has a parseInt method which converts data from strings to integers. When referring to primitive types, lower case is used as first letter: int When referring to wrapper classes, upper case is used: Integer From SUN API: “Every Class has Object as a Superclass”
23
Assignment Statements
General syntax: location = value Any programming language has to allow for the assigning of one variable or constant to another variable. The assignment operator is the equal sign = The value on the right side of the equal sign is assigned to the variable on the left side of the equal sign. Cover examples on slide. Point out that example 6 is not algebraically correct, but it is correct in computer syntax. Mention that when using this technique, we almost always at some point initialize the counter with a value of zero: int counter = 0; Have students follow the instructions on Page 150 figure 3-15
24
Arithmetic Operators What’s the difference between Division, and Integer division? They both use the same operator / but the results can be different. Num = 55D / 4D yields an answer of 13.75 Num = 55 / 4 yields an answer of 13 Modulus division returns the remainder: Num = 55 % 4 yields an answer of 3 The cast operator allows you to convert one primitive data type to another. Assume we’ve defined 3 variables: double average; int num=55, ctr = 4; The equation: average = num / ctr will yield a value of 13 because both values on right of = are integers so answer will be stored as an integer However, the equation: average = (double) num / ctr would yield a value of because we have cast the integer variable num to be a double. When Java performs math on mixed data types, the result is always the larger data type. If questions: see /java programs/examples/_01_cast_example.java
25
Arithmetic Operators The order of operator precedence is a predetermined order that defines the sequence in which operators are evaluated in an expression Addition, subtraction, multiplication, and division can manipulate any numeric data type When Java performs math on mixed data types, the result is always the larger data type Casts allow programmers to force a conversion from one primitive type to another Wait for 2 slides for examples
26
Comparison Operators A comparison operation results in a true or false value that can be stored in a boolean variable Comparison operators include two values as do arithmetic operators, however, they compare numbers rather than performing math on them. boolean isCost; isCost = ( price > 100); isCost is defined as a boolean variable. isCost will have a value of True if price is greater than 100 isCost will have a value of False if price is less than 100. Convention has us start the name of our boolean variables with: is The first 4 are called relational operators because they compare 2 values. The last 2 are sometimes called equality operators. Note the equality operator is a double equal sign == to differentiate it from the numeric assignment operator isCost = ( price == 100); IsCost will have a value of True if price is equal to 100 IsCost will have a value of False if price is not equal to 100 Show: java_programs\examples\_02_boolean_example_pg153
27
Numeric Expressions Numeric expressions evaluate to a number
Only numeric primitive data types may be used in a numeric expression – no Strings A value and variable must be separated by an arithmetic operator Unless parentheses supercede, an expression is evaluated left to right with the following rules of precedence: Multiplication and/or division Integer division Modular division Addition and/or subtraction All things being equal expressions are evaluated left to right. Answer = 16 / 4 / Sets answer to 2 not 8 Answer = 16 / ( 4 / 2) Sets answer to 8 30 – 5 * 5 = 5 not 125 (30 – 5) * 5 = 125 Order of precedence also called Rules of Precedence, or Hierarchy of operations. See page 156 for more examples if questions arise. Book also gives suggestion for students that really don’t “get it” of scanning an equation 4 times. First time, perform all mult and div, 2nd all integer division, 3rd modular division, and last scan add and sub.
28
Conditional Expressions
Conditional expression evaluate to either true or false Comparison operators, values, variables, methods, and Strings may be used in a conditional expression Two operands must be separated by a comparison operator Unless parentheses supercede, an expression is evaluated left to right with relational operators (<, <=, >, >=) taking precedence over equality operators (==, !=) When evaluating scan twice, left to right. First scan evaluate all relational operators ( < <= > >=) On second scan evaluate all equality operators ( == !=) 10 < > Evaluate left to right. No equality operators False True False All evaluations must be true for result to be true Book’s example pg 157 10 < = = True False = = True? First scan evaluate 10 < 5 False Second scan evaluate False == True Typically surround a Boolean test with an If statement. If statement is covered in chapter 4. If (10 < 5 == TRUE) System.out.println(“True”) else System.out.println(“False”); Don’t cover this one unless asked: java_programs\examples\_03_boolean_pg157.java
29
Parentheses in Expressions
Parentheses may be used to change the order of operations The part of the expression within the parentheses is evaluated first Parentheses can provide clarity in complex expressions Numeric and conditional expressions should be grouped with parentheses Parentheses can be nested Java evaluates the innermost expression first and then moves on to the outermost expression 1st Example at top of page 158 is wrong Cover 2nd example from pg 158 (see below) before showing program that illustrates error mentioned above Parenthesis can be nested – Evaluate inner parenthesis first. Example from book: Remove a paren to show different result: 18 / 3 * 2 + (3 * (2 + 5)) 18 / 3 * 2 + (3 * 2 + 5) = 18 / 3 * 2 + (3 * 7) 18 / 3 * 2 + (6 + 5) = 18 / 3 * / 3 * = 6 * * = = 33 23 Show java_programs\examples\_04_parenthesis_test_pg158.java This shows both the 1st example error, and the second example
30
Construction of Error-Free Expressions
Java may not be able to evaluate a validly formed expression due to the following logic errors: Dividing by zero Taking the square root of a negative value Raising a negative value to a non-integer value Using a value too great or too small for a given data type A Byte data type can hold a value up to 127, an Int up to billion+ Comparing different data types in a conditional expression Comparing an Integer to a String. See pg 140 for chart on data types (this is back several pages in the book from the point that this slide is at)
31
The Math Class Java contains the basic numeric operators. However, for more advanced functions such as square root or absolute value, you have to use methods supplied by the Math class. The Math class is part of the Java.lang package. Most Math class members are intuitively named and can be accessed by prefacing the name of the member with Math. Pythagorean Theorem A squared + B squared = C squared Side_C_sq = Math.pow(side_A, 2) + Math.pow(side_B, 2); Side_C = Math.sqrt(Side_C_sq); Remember that values inside of the parenthesis of methods are called arguments and arguments are separated by commas. The pow method takes two arguments, the sqrt method only takes one argument. Could simply: Side_C = Math.sqrt(Math.pow(side_A,2) + Math.pow(side_B,2)); Have students follow the instructions on Page 160, figure 3-18 BMI = kilograms / meters (squared) Side_A Side_B Side_C
32
Using Variables in Output
We’ve already seen how to use the println method to display literals. println can also be used to display constants. Remember System.out refers to the default output device, usually the monitor. Cover examples on slide. Point out that examples 4 and 5 are two different methods for doing the same thing. Have students follow the instructions in the gray box on Page 162
33
Compiling, Running, and Documenting the Application
Compile the Body Mass Index Calculator program Execute the program Test the program by entering the sample input data supplied in the requirements phase at the prompts Verify the results Print the source code and screen images for documentation Have students follow the instructions on Page 164 and 165 to compile, execute, and test the application.
34
Using Swing Components
Save the previous version of the Body Mass Index Calculator with a new filename Import the javax.swing.JOptionPane class Contains methods to create dialog boxes for input, confirmation, and messages Delete the IOException and BufferedReader code The swing dialog boxes buffer data from the user and handle IO errors In 1997 Sun introduced a new set of GUI components commonly referred to as Swing components. These Swing components are part of the new Java classes that facilitate the building of graphical user interfaces in a console environment. For the most part the Swing components have replaced the earlier techniques, thereby eliminating the need for certain functions such as BufferedReader (The swing components do their own buffering) The next section of the chapter will have us convert the existing application to use Swing components. We will need to create a new program name and make some global changes in the new version of the program to reflect the new name. The text will have you use Textpad to make some of these changes. Have students copy their BodyMass.java file to BodyMassSwing.java Have students follow the instructions on Pages 167 thru 170 Remind them to go slowly and follow the directions exactly or their program will have problems. Especially the instructions on page 170. Do not do these out of order or your line numbers will be wrong. (Double click on a line number to delete the whole line)
35
Swing Dialog Boxes Dialog boxes are created with the JOptionPane “show” methods The showInputDialog() and showConfirmDialog return a String containing the user input The JOptionPane class has many methods that make it easy for programmers to display standard dialog boxes showInputDialog() is used to request information from a user. This takes 2 arguments Name = JoptionPane.showInputDialog(null, “What is your name?”); null is a required parameter that claims to center the dialog box on the open window. However, it doesn’t seem to work that way, and it doesn’t seem to be required. showMessageDialog() is used to display a message on the screen. This takes 4 args. JOptionPane.showMessageDialog(null, “Nice to meet you” + name, “Meet you box”, JOptionPane.PLAIN_MESSAGE Arg1: Null: required Arg2: Text to display Arg3: Caption in Title bar of Dialog box Arg4: Intrinsic constant: A value that Java understands to have a specific meaning. In this case it refers to the type of dialog box and what icons they will contain See pg 172 for types: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, PLAIN_MESSAGE, YES_NO_OPTION showConfirmDialog() is used allow user to confirm a particular choice Choice = JOptionPane.showConfirmDialog(null,”Please choose yes or no”, “Confirm box”, JOptionPane.YES_NO_OPTION Arg1: Null: required Arg2: Text to Display Arg3: Caption in Title bar of Dialog box Arg4: Type of dialog box to display Returns an integer reflecting which choice is chosen. Probably 0 and 1 but can’t find this in book. Went to API site, but doesn’t give actual integer only string value: YES_OPTION, NO_OPTION etc
36
Swing Dialog Boxes Tell students to create a backup copy of their file. For instance: BodyMassSwing99.java Have students follow the instructions on Page 173, figure 3-31 Tell them to be sure to follow the directions in order. The directions start at the last line of code and work backwards. This is to insure that line numbers are correct. If students work in the other direction their line numbers will be off.
37
Closing Programs that use Swing
System.exit() terminates an application that displays a GUI The command prompt window closes when this method is called System.exit accepts an integer argument that serves as a status code 0 indicates successful termination 1 indicates abnormal termination All programs have the option of setting a Return code, or an Exit code, or a Condition Code. These codes can be queried by calling programs to see if subroutines ended successfully. If you don’t code an exit statement when using Java Swing classes your command prompt window will not close. Have students follow the directions on Page 174, Figure 3-32
38
Saving, Compiling, and Running the Swing Version
Verify that the file name matches the class name at the beginning of the code Compile the source code Test with the same sample data for all versions to compare output results If incorrect or unrealistic data is entered by the user, errors will occur Errors and exception handling will be discussed in a later chapter Double check that students have previously saved this program to a name of BodyMassSwing. If they haven’t tell them to follow directions in gray box on page 175. Have students compile program then follow the directions on Pages 176 and 177, figures 3-33 thru This will have them compile, execute and debug their program.
39
Moving to the Web The applet version of the Body Mass Index Calculator has four kinds of objects Image, Labels, TextFields, and Buttons Import three packages Java.applet Java.awt Java.awt.event Implement an ActionListener interface in the class header Informs the program to respond to user-driven events The Applet version of this program will run in a different environment, typically by a browser reading a Web page. As such, the program must be modified so that the Browser understands what’s going on. The browser needs to be able to recognize events such as selecting a menu item, pressing the enter key, clicks a button, double-clicks an item etc. etc. In order to do this out Applet must tell the browser to listen for certain events. In order to do this, we need to import a new class: java.awt.event. There are several different kinds of events that the browser can be told to listen for. Although the logic for this version of the program will be the same as the other versions, there will be significant changes to the way the logic is implemented. So, much so that the book will have you actually start a new program from scratch, rather than have you copy and modified one of the existing programs.
40
Moving to the Web Every event class has one or more associated listener interfaces This is a list of several classes in the java.awt.event package, with an example of an event that represents the class, and an associated listener interface The keyword, implemnts, is used in the class header to specify which listener interface a programmer wants to use.
41
Have students follow the directions in the gray box on Page 180
Remind them that they will be creating the Java application from scratch, rather than modifying one of the old programs.
42
Adding Interface Components
Label Displays text in the applet window TextField Displays a text box for users to enter text Buttons Displays a command button for users to click The java.awt package contains components or object data types that you can use to build a user interface for applets. A Label is an object that displays text in a window in the same way that showMessageDialog displayed text when using the Swing components. A TextField is an object that displays a text box in which users enter text, in the same way that showInputDialog prompted for input when using the Swing components. A Button is an object that displays a command button for users to click. A button is a generic object whose color and shape are inherited from the operating system. However, programmers write the underlying code that determines what action takes place when a particular button is pressed. We need to Construct each object that we will be using. Label companyLabel = new Label (“Sun Fitness Center”); Label is the datatype, companyLabel is the new variable name = is the assignment operator New indicates we are constructing a new instance of the Label type Label is the constructor. Sun Fitness Center is the argument passed to the Label constructor. We frequently combine a Label with a Textfield: Label heightLabel = new Label(“ Enter your height to nearest inch: “); TextField heightField = new TextField(10); where 10 indicates number of bytes in textfield Have students follow the instructions on Page 183, figure 3-40.
43
The init() Method Initializes the window color and graphic
Adds components to the applet window Registers the Button’s ActionListener with the button The constructors defined on the previous slide are just storage locations until the applet actually is displayed on the screen. To display them on the screen, they must be added to the applet interface using the init() method. The init() method loads the initial setup of the applet when execution begins. Line 32 sets the text color to red Lines insert the previously declared objects into the applet window – the browser’s window. Line 39: calcButton.addActionListener(this); Says to add the ActionListener event to the calcButton. “The keyword, this, refers back to the component itself – in this case, the calcButton instance of the Button class. The calcButton thus is the object monitored by the listener interface, ActionListener.” Line 41 retrieves the image from disk and stores it in the variable named logo. The getDocumentBase() method says to retrieve the image from the current folder in which the applet class is stored. Have students complete the instructions on Page 186, figure 3-42
44
The actionPerformed() Method
When a click event occurs, the ActionListener’s actionPerformed() method is triggered Input values are retrieved with getText() Calculations are performed Output is sent to a label with setText() We now have to create the code that lies behind the Calculate button. That is, we have to say what to do when the button is clicked. In this case we need to calculate the Body Mass Index, just as it did in the previous two versions of the program. (remember there are several different kinds of listener interfaces, see 4 slides back) All Listener Interfaces have methods called Event Handlers that specify what will happen when an event is triggered. The button is the Event Source to the routine that performs the calculations. The calcButton is associated with the ActionListener Interface. The ActionListener interface has one event handler, or method, called actionPerformed. It is the underlying code of actionPerformed that gets executed when the click event occurs. The actionPerformed method receives one parameter of the type ActionEvent, the name of the parameter is conventionally e. In this case the action that gets passed as a parameter will be the clicking of the button. The getText() method is used to input text from a user and setText() is used to display output. Remember that text is inputted and outputted in character format, it must be converted to numeric format in order to perform calculations, thus the parseInt method wraps itself around the getText method. Have students follow the directions on Page 188, figure 3-44
45
The paint() Method Draws the initialized image in the applet window
The paint method, which we used in the last chapter, will be used to draw the Sun Fitness Center login at a location of 125 pixels from the left of the applet and 160 pixels from the top. The paint method takes one parameter of type: Graphics, the name of that parameter is conventionally g. The brace on line 58 closes the block of code for the paint() method. The brace on line 59 closes the entire BodyMassApplet class. Have students follow the instructions on Page 189, figure 3-46
46
Creating an HTML Host Document for an Interactive Applet
Compile the applet Write an HTML Host Document to execute the applet Use the <APPLET> tag to specify the bytecode file, and width and height of the window Use the same sample data to test the applet Document the source code We now have to create the HTML driver which will allow us to test the applet. Have students follow the instructions on Pages 191 and 192 figure 3-48 Have students follow the instructions on Pages 192 and 193, figure This will have students run and test the applet. Warn them that the <applet> tag there is a period between BodyMassApplet.class In book it looks like a space. Point out, again, that in a test environment you want to use the same test data to make sure you get the same results as in the previous versions of the program.
47
File management Coding and compiling an application creates several files on your storage device File naming conventions and the operating system’s capability of displaying icons can help the programmer maintain a logical order Three java files named after the program purpose and user interface type Three class files after compilation HTML host document Image file Go to Windows Explorer and point out how many files have been created in the process of creating these 3 versions of the applications.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.