Upload
j-c
View
1.684
Download
0
Tags:
Embed Size (px)
DESCRIPTION
Citation preview
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
1
McGraw-Hill/Irwin
Chapter 2
Using Variables and Constants
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
2
McGraw-Hill/Irwin
Objectives
• Use multiple forms of constructors.
• Add buttons and text fields to an interface.
• Use variables to store information.
• Input data into a text field.
• Display multiple lines of output in a text area.
• Obtain and display the system date.
• Capture user actions with a listener.
• Add event handling for a button and text field.
• Incorporate mouse events.
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
3
McGraw-Hill/Irwin
Applet Panel with Text Field, Text Area, and a Button
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
4
McGraw-Hill/Irwin
Constructor Methods
Constructor method executes automatically
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
5
McGraw-Hill/Irwin
Variables and Constants
• Data can be stored in a variable or constant.
• Variables can change value while the program is executing.
• Constants cannot change at any time while the program is executing.
• You have already used constants, e.g. “Hello World.”
• Anything in quotes is a constant.
• You used color constants such red, cyan.
• You have alignment options in the labels such as Label.RIGHT, where RIGHT is a constant.
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
6
McGraw-Hill/Irwin
Format of Constructor
Label( String text, int alignment)
parameter list
Code
Label lblMessage = new Label("Hello World", RIGHT);
arguments
Format of Constructor
Label(String text, int Alignment)
parameter list
Java Code
Label lblMessage = new Label("Hello World", Label.RIGHT);
arguments
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
7
McGraw-Hill/Irwin
Java Data Types
• The data type determines the way that a program handles and stores data.
• Java has eight primitive data types, which are built-into the language.
• Java supplies some classes that define additional data types to give more flexibility.
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
8
McGraw-Hill/Irwin
Java Primitive Data Types
Data Type Naming Prefix
Contents Default Initial Value
Possible Values
boolean bln true or false false true or false
byte byt small integers 0 -128 to 127
char chr single character
char code 0 Unicode character—a code designed for internationalization of applications
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
9
McGraw-Hill/Irwin
Java PrimitiveData Types Continued
double dbl double precision floating point number
0.0 15 digit precision
float flt single precision floating point number
0.0 7 digit precision
int int integer data 0 -2,147,483,648 to 2,147,483,647
long lng long integer 0 -9,223,372.036,854,775,808L to 9,223,372,036,854,775,807L
short int short integer 0 -32,768 to 32,767
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
10
McGraw-Hill/Irwin
Valid and Invalid Variable Names
Identifier Valid or Invalid Reason
int Person Count invalid No spaces allowed in a name.
int_Person_Count valid
chrLetter valid
blnIsFinished valid
2Times invalid Must begin with a letter or underscore.
fltBig# invalid Only letters, letters, and underscore characters allowed. No special characters.
dblBig.Number invalid No periods allowed.
X valid Accepted by Java but is a terrible identifier, since the name is not meaningful.
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
11
McGraw-Hill/Irwin
Declaring Variables • When you declare variable, you reserve a location in memory.
• The data type determines the amount of memory reserved and how the data is handled.
• To name a variable, you must have the data type prefix and the name you want to give in accordance with naming rules.
• General Format - datatype variablename;
• Examples – float fltTotalSales;
int intStudentCount;
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
12
McGraw-Hill/Irwin
Forming Numeric Literals
• Numeric literals can consist of the digits 0-9, a decimal point, a sign at the left, and an exponent.
• For the floating point variable you must use a f or F after the variable. You can use a D or d for double. Floating point variables default to double.
• If you type a whole number it assumes an integer unless the value is greater than the integer allowed.
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
13
McGraw-Hill/Irwin
Declaring Numeric Constants • Use the keyword final to specify that the data remains a
constant.
• You must use final before the data type.
• Follow standard naming conventions.
• Begin with 3 character lowercase prefix for the data type.
• Use uppercase for the rest of the name.
• Separate the words with an underscore.
• Example – final float fltTAX_RATE = 0.07f;
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
14
McGraw-Hill/Irwin
Selected Java DataType Wrapper Classes
DataType Naming Prefix Contents
String str character data
Boolean Bln True or False
Float Flt floating point numeric
Integer Int Integer
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
15
McGraw-Hill/Irwin
Scope and Lifetime of Variables
Type Location of Declaration
Scope (Visibility)
Lifetime Memory allocated
Class Inside a class but not within a method. Keyword static.
Visible in all methods of the class.
As long as any instance of the class exists.
One copy for the class.
Instance Inside a class but not within a method.
Visible in all methods of the class.
As long as this specific instance of the class exists.
One copy for each object instantiated from the class.
Local Inside a method. Visible only inside the method where it is declared.
Until the method ends.
New copy each time the method is called.
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
16
McGraw-Hill/Irwin
The TextField Component—Constructor Formats
TextField()TextField(int maximumNumberCharacters)TextField(String initialValue)TextField(String initialValue, int maximumNumberCharacters)
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
17
McGraw-Hill/Irwin
The TextField Component—Examples
TextField txtName = new TextField(20);TextField txtQuantity = new TextField(5);TextField txtZipCode = new TextField("91789");TextField txtZipCode = new TextField("91789",9);
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
18
McGraw-Hill/Irwin
The TextArea Component—Constructor Formats
TextArea()TextArea(int numberRows, int maximumNumberCharacters)TextArea(String initialValue)TextArea(String initialValue, int numberRows, int maxNumberCharacters)TextArea(String initialValue, int numberRows, int maxNumberCharacters, int Scroll)
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
19
McGraw-Hill/Irwin
The TextArea Component—Examples
TextArea txaInvoice = new TextArea(20,40);TextArea txaGrades = new TextArea(15,20);TextArea txaGrade = new TextArea("Name Average",15, 20);TextArea txaGrade = new TextArea("Name Average", 15, 20,
TextArea.SCROLLBARS_BOTH)
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
20
McGraw-Hill/Irwin
Selected Methods of the TextField and TextArea Components
Method Purpose
getText() Returns the contents of the text component.
setText(String value)
Assigns the value to the text component.
append() Adds text to the end of the contents, only available with TextArea.
selectAll() Selects (highlights) the contents of the text component.
getSelectedText() Returns only the text that is selected in the text component.
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
21
McGraw-Hill/Irwin
The getText Method—General Format
componentName.getText()
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
22
McGraw-Hill/Irwin
The getText Method —Example
strName = txtName.getText();
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
23
McGraw-Hill/Irwin
The setText Method—General Format
componentName.setText(string to be displayed)
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
24
McGraw-Hill/Irwin
The setText Method—Examples
lblMessage.setText("Hello World");txtGreeting.setText(strName);txtAnswer.setText("Hello " + txtName.getText());txtName.setText(""); //Clear the text field
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
25
McGraw-Hill/Irwin
Concatenation
“+” means concatenation of two items
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
26
McGraw-Hill/Irwin
Including Control Characters
• ‘\n’ – new line (line feed)
• ‘\t’ – horizontal tab (advance to the next tab stop)
• ‘\f’ – form feed (eject a page when sending it to the printer)
• ‘\”’ – double quote(include a double quote within the string)
• ‘\’’ – single quote(include a single quote within the string)
• ‘\\’ - backslash
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
27
McGraw-Hill/Irwin
The append Method—General Format
componentName.append(string);
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
28
McGraw-Hill/Irwin
The Append Method—Examples
txaInvoice.append("Sold To: " + strName +"\n");txaInvoice.append("Address: " + strStreet + "\n");txaInvoice.append(" City: " + strCity);
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
29
McGraw-Hill/Irwin
Use Unnamed Labels for Prompts
Prompts
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
30
McGraw-Hill/Irwin
Prompts for Text Components
• The prompt is never going to be referred to in the program.
• We can create an unnamed label and eliminate a step.
• For example: add a prompt named Department – add(new Label(“Department”));
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
31
McGraw-Hill/Irwin
Positioning the Cursor
• You would want the cursor to appear in the first textfield when the user runs the program.
• The can be achieved by using the requestfocus method for that component.
• txtDept.requestfocus();
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
32
McGraw-Hill/Irwin
System Dates
• You can easily access systems dates and time using the Calendar class found in the Java util package.
• The getInstance method creates an instance of the Calendar class which contains the current date and time for the default locale and time zone.
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
33
McGraw-Hill/Irwin
Partial List of Calendar Integer Constants
Constant Returns
YEAR 4 digit year
MONTH Month starting with 0
DAY_OF_MONTH Day starting with 1
DAY_OF_YEAR Julian date
DAY_OF_WEEK Starts with 0 for Sunday
ERA BC or AD
HOUR Hour (12 hour time)
MINUTE Minute of hour
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
34
McGraw-Hill/Irwin
The Button Component—Constructor Formats
Button()Button(String label);
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
35
McGraw-Hill/Irwin
The Button Component—Examples
Button btnBlank = new Button()Button btnClear = new Button ("OK");Button btnDisplay = new Button("Display");
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
36
McGraw-Hill/Irwin
The ActionListener Interface
• The ActionListener detects (listens) to the click of a button.
• To add a listener to your code you must:
• Add another import java.awt.event.*; statement.
• Include an “implements ActionListener” clause in the class header.
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
37
McGraw-Hill/Irwin
Adding a Listener to the Component
• To add the ActionListener to the component uses the addActionListener method.
• In the argument, you must include this, which means current class.
• The current class is notified of the event occurring for that component.
• btnCalculate.addActionListener(this);
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
38
McGraw-Hill/Irwin
Coding for the Event
• After having added the ActionListener, you must code the actionPerformed method of the interface ActionListener.
• This method executes each time the user clicks on the button(the event fires).
• The method header is as follows: public void actionPerformed(ActionEvent pl).
• The argument pl is that system supplies a value for the action event.
• The argument indicates which component has triggered the event.
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
39
McGraw-Hill/Irwin
Mouse Events
• Java allows you to listen mouse events such as mouse clicked, mouse moved over an object or mouse moved away from an object, using the MouseListener interface.
• The MouseListener interface requires you to include five methods, even if you have to leave them empty.
• The five mouse methods are mouseClicked, mousePressed, mouseReleased, mouseEntered, and mouseExited.
• You will code in the mouseEntered method. When the mouse enters in the button.
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
40
McGraw-Hill/Irwin
Mouse Events Continued
• You will code in the mouseExited method. When the mouse exits the button.
• If you are not coding in the other methods, they must be included and empty.
• They override the methods defined in the MouseListener.
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
41
McGraw-Hill/Irwin
Other Listeners
• Many other listeners are available in Java.
• For example: MouseMotionListiner, TextListener, WindowListener, and KeyListener.
• Each of the listeners have a set of methods.
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
42
McGraw-Hill/Irwin
The showStatus Method—General Format
showStatus(String);
Programming with Java
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
43
McGraw-Hill/Irwin
The showStatus Method—Examples
showStatus("Click here to Calculate");showStatus("Invalid entry");