Programming with Java

Download Report

Transcript Programming with Java

Programming with Java
1
Chapter 2
Using Variables and Constants
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
2
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
3
Applet Panel with Text Field, Text
Area, and a Button
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
4
Constructor Methods
Constructor method executes automatically
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
5
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
6
Format of Constructor
Format of Constructor
Label(String
text, int Alignment)
parameter list
Label( String text, int alignment)
Java Code
parameter list
Label lblMessage = new Label("Hello World", Label.RIGHT);
Code
arguments
Label lblMessage = new Label("Hello World", RIGHT);
arguments
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
7
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
8
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
internationaliz
ation of
applications
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
9
Java Primitive
Data 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
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
10
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
11
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;
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
12
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
13
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;
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
14
Selected Java Data
Type Wrapper Classes
DataType
Naming Prefix
Contents
String
str
character data
Boolean
Bln
True or False
Float
Flt
floating point
numeric
Integer
Int
Integer
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
15
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
Visible only
inside the
method where it
is declared.
Until the
method ends.
New copy each
time the method
is called.
Inside a method.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
16
The TextField Component—
Constructor Formats
TextField()
TextField(int maximumNumberCharacters)
TextField(String initialValue)
TextField(String initialValue, int maximumNumberCharacters)
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
17
The TextField Component—
Examples
TextField
TextField
TextField
TextField
txtName = new TextField(20);
txtQuantity = new TextField(5);
txtZipCode = new TextField("91789");
txtZipCode = new TextField("91789",9);
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
18
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)
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
19
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)
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
20
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
21
The getText Method—General
Format
componentName.getText()
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
22
The getText Method —Example
strName = txtName.getText();
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
23
The setText Method—General
Format
componentName.setText(string to be displayed)
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
24
The setText Method—Examples
lblMessage.setText("Hello World");
txtGreeting.setText(strName);
txtAnswer.setText("Hello " + txtName.getText());
txtName.setText(""); //Clear the text field
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
25
Concatenation
“+” means concatenation of two items
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
26
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
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
27
The append Method—General
Format
componentName.append(string);
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
28
The Append Method—Examples
txaInvoice.append("Sold To: " + strName +"\n");
txaInvoice.append("Address: " + strStreet + "\n");
txaInvoice.append(" City:
" + strCity);
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
29
Use Unnamed Labels for Prompts
Prompts
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
30
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”));
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
31
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();
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
32
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
33
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
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
34
The Button Component—
Constructor Formats
Button()
Button(String label);
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
35
The Button Component—
Examples
Button btnBlank = new Button()
Button btnClear = new Button ("OK");
Button btnDisplay = new Button("Display");
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
36
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
37
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);
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
38
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
39
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
40
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
41
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.
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
42
The showStatus Method—
General Format
showStatus(String);
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.
Programming with Java
43
The showStatus Method—
Examples
showStatus("Click here to Calculate");
showStatus("Invalid entry");
© 2002 The McGraw-Hill Companies, Inc. All rights reserved.