Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Chapter 3
More Java Fundamentals
Go
Sect 1 - More About Data Types and Variables
Go
Sect 2 - Order of Operations and Expression Evaluation
Go
Sect 3 - Method Signatures and User-Defined Methods
Go
Sect 4 - Problematic Order of Input Statements
Go
Sect 5 - Program Comments
Go
Sect 6 - More about Java Errors
Go
Sect 7 - Drawing and Painting in Java
Chapter 3 Section 1
More About Data Types
Primitive & Object Data Types
Declaring Variables and other User-Defined
Symbols
Java Keywords
Constants
Constructing String and Other Objects
The String length() method
2
3.1 Primitive & Object Data Types
There are two categories of data types:
•
•
1. Primitive data types, specifically:
•
int (integers)
•
double (floating-point)
•
char (characters)
•
boolean (true or false)
2. Objects, for instance:
•
String - characters, words, or sentences
•
Scanner - can read from the keyboard or files
•
Color - a color with red, green, & blue components
•
JPanel - a canvas that can display painted or other items
•
JApplet - a window that contains panels or other GUI items
3
3.1 Primitive & Object Data Types
•
The Java syntax (rules) for manipulating primitive data types
differs for objects:
–
Primitive data types are combined in expressions with
operators. Primitives are NOT constructed! You never
construct a primitive!!!
–
Objects are constructed and sent messages or objects
call methods.
4
3.1 Declaring and Initializing Variables
Several variables can be declared in a single declaration as in
int x, y, z; but we don’t usually do this unless because it
may not be evident that all three are int variables.
As you have found out, variables can be declared and
initialized in one line of code:
int limit = 1000;
double q = 1.41;
String name = “Bill Jones”;
Note: Here we are initializing them but not constructing them.
5
3.1 Int & Double Primitive Data Types
When you use primitive data types, you simply declare
variables of those types and either initialize them with a
literal value or give them a value from a method …
int x = 15;
int y = reader.nextInt();
int area = calculateArea(x, y);
double num1 = 32.47;
double num2 = reader.nextDouble();
double percent = getPercentage(num1, num2);
6
3.1 Six Numeric Data Types
•
There are actually six numeric data types in Java but we will
use only two. The six types and there storage amounts are:
– byte
(an 8 bit integer)
– short (a 16 bit integer)
– int
(a 32 bit integer)
– long
(a 64 bit integer)
– float (a 32 bit floating-point)
– double (a 64 bit floating-point)
Each uses a different number of bytes for storage and each has
a different range of values. We will use only int and double in
this class and those are the only two you need to know for
the AP Exam. For more on these data types go to this link:
Java’s Primitive Data Types
7
3.1 Int and Double Storage Requirements
Type
Storage
Requirements
Range
int
4 bytes (or 32 bits)
-2,147,483,648 to 2,147,483,647
double
8 bytes (or 64 bits)
-1.79769313486231570E+308 to
1.79769313486231570E+308
These are the only two storage requirements you need to
be familiar with.
Remember that 1 byte has 8 bits.
int data takes 4 bytes which is equal to 32 bits.
double data takes 8 bytes which is equal to 64 bits.
This confirms the information on the previous slide.
8
3.1 Arithmetic Overflow
Arithmetic overflow can happen if you assign a value to a variable
that is outside of the range of values that the data type can
represent.
For example if you are adding two int data type values, if their sum
exceeds 2,147,483,647 then Java will wrap around to the lower
limit (-2,147,483, 648) and proceed upwards toward zero to
complete the addition, which will give you an incorrect value.
Integer.MIN_VALUE and Integer.MAX_VALUE are constants that can
be used in a program to access the limits of the int data type
directly and provide protection for the program. They are constants
of the Integer class.
Integer.MIN_VALUE
is equal to -2,147,483,648
Integer.MAX_VALUE
is equal to
2,147,483,647
9
3.1 Java’s Scientific Notation of doubles
Floating-point numbers (doubles) in Java will sometimes be
displayed in scientific notation in the console output window. The
number following the E is the exponent of the base 10. Numbers
are displayed this way only when the number is very large or very
small.
7.638E12
equivalent to
7.638 x 1012
4.259613E-8
equivalent to
4.259613 x 10-8
10
3.1 Char & Boolean Primitive Data Types
Again, when you use primitive data types, you simply declare variable
of those types and either initialize them with a literal value or give
them a value from a method. Here are two primitive data types we
haven’t discussed yet … char and boolean. A char is a single
character that can be either an alphabetical letter, numeric digit, or
a symbol from the keyboard. A boolean is either true or false with
no double quotes around those values.
char letter = ‘A’;
char firstLetter = firstLetterOfName(studentName);
boolean done = false;
boolean eligible = checkEligibility(studentName);
11
3.1 Conceptualizing Variables
A variable is a named location in memory.
Changing a variable’s value is equivalent to
replacing or overwriting the value in that memory
location. Here the variable radius has 42.7 stored
in it, but it is overwritten with a new value, 36.4.
These two lines of code do this:
variable
radius
42.7
36.4
double radius = 42.7;
radius = 36.4;
Once a variable has been declared in a program
of a certain type (like int), it cannot be changed to
another data type (like double) later on in the
code. Think about that. The reason is simple.
Java cannot re-allocate a smaller or larger
amount of memory “on the fly” for a variable.
12
3.1 Declaring Variables
Before using a variable for the first time, you must declare its
type. Here are several variable declaration statements
that you are now familiar with:
int age;
double celsius;
boolean done;
String name;
Scanner reader;
The type appears on the left and the variable’s name on the
right.
<data type> <variable name> ;
13
3.1 Choosing Names in Java
Variable, method and program names are what we call userdefined symbols.
These names must begin with an alphabetical letter, the
underscore character or the dollar symbol … followed by a
sequence of letters and/or integer digits. No other symbols can
be included, except for the underscore and dollar sign symbols.
So names can only include:
alphabetical letters: A .. Z
alphabetical letters: a .. z
numeric digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
the symbols: _ and $
14
3.1 Java Keywords
One additional rule about creating variable names is you cannot
use Java keywords (also called reserved words) for variable
names.
These have special meaning in Java. These are words like print,
println, class, public, and static, true, and false. You cannot use
the name of any class that you know exists like Scanner for a
variable name. However, you could use scanner (lower case).
Also, it is important to note that keywords are case sensitive and
are usually all lower case so don’t try to capitalize any letters.
For instance, always use import not Import or IMPORT.
15
3.1 Java Reserved Words Chart
abstract
boolean
break
char
class
double
else
extends
false
for
if
implements
import
int
new
null
package
private
public
return
static
true
super
this
throws
try
void
while
Some of Java’s most common reserved words.
16
3.1 Valid Variables with Meaningful Names
It is very important to wisely choose meaningful variables names that
increase a program’s readability and maintainability.
Sometimes it requires more typing but consider the following variables for a
program that might be read by someone other than the programmer that
wrote the code:
1.
radius rather than r
2.
taxableIncome rather than ti
Examples of valid and invalid variable names:
Valid Names:
surfaceArea3
Invalid Names: 3rdPayment
can’t start
with number
or
_$_$$$ (valid but not good)
pay.rate
can’t use a
dot
public
cool@#%&stuff
can’t use a
reserved word
can’t use these
symbols
17
3.1 Naming Conventions
By convention, when forming a compound variable name,
programmers capitalize the first letter of each word except the
first letter of the first word.
(For example: incomeTax)
However, when forming a program’s name each word will begin
with a capital letter.
(For example: ComputeEmployeePayroll or BestFriends)
Constant names are formed using all uppercase letters with all
words separated by underscores.
(For example: SALES_TAX_RATE)
18
3.1 Variables Declared as Constants
If variables are declared using the word final, then the value stored
in them cannot be changed or overwritten during the run of a
program. We call these variables constants.
Names of constants are always written in uppercase. It is a
convention that all programmers follow. Here is the declaration
of the constant SALES_TAX_RATE:
public static final double SALES_TAX_RATE = 7.85;
In any class file, if we want a constant to be able to be used
anywhere in that file, then we have to include static and declare
it globally outside all methods. If we want the constant to be
available to any other class then we also include public.
19
3.1 Constant Declaration Examples
Here are some other constant variable declaration examples for int
and String:
public static final int MAXIMUM_GRADE = 100;
public static final String DEFAULT_NAME = “John Doe”;
Compare the above declarations to the declaration from the
previous slide seen below. Note the similar pattern and the
differences between int, double, and String constants.
public static final double SALES_TAX_RATE = 7.85;
20
3.1 Constant Declaration Challenge
Write the constant variable declaration for the constant that will
represent a minimum grade of zero ... ???
21
3.1 Constant Declaration Answer
Write the constant variable declaration for the constant that will
represent a minimum grade of zero ... ???
public static final int MIN_GRADE = 0;
22
3.1 Public Constants of a Class
Sometimes constants are contained within classes other than the
ones programmers are writing. For example, there is an Integer
class in Java that can be used, but there is no reason to import
it because it is in the java.lang package that is automatically
imported into every Java program. If you had to import it, then
the statement needed would be:
import java.lang.Integer;
Earlier when we discussed arithmetic overflow we mentioned these
two constants:
Integer.MIN_VALUE
is equal to -2,147,483,648
Integer.MAX_VALUE
is equal to
2,147,483,647
23
3.1 String Object Data Types
String objects do not need to be constructed. They are automatically
constructed. Here are two examples:
String name = “Java”;
or
String word = reader.nextLine();
Notice there is no need to construct the String object first with a line of
code like:
String name = new String (“Java”); or
String word = new String ( );
word = reader.nextLine();
This is a convenience for programmers who use Strings a lot. So they
built it into Java to work this way.
24
3.1 The String length() Method
Objects of the String class can be sent several different messages.
One message we can send to a String object is “tell me your length”.
We do this by calling the length() method.
The length method will return us the number of characters of the value
stored in a String object. Here is an example:
String sentence= “Programming in Java is Fun!”;
int theLength = sentence.length();
System.out.println(“The number of characters is ” + theLength);
This will print …
The number of characters is 27
25
3.1 The String length() Method
In the lines of code …
String sentence = “Programming in Java is Fun!”;
int theLength = sentence.length();
We want to find the number of characters in the String variable
sentence, so we use sentence to call the method length().
There are four ways we can say this. We can say we are …
1.
sending the message “length” to the String variable sentence
2.
calling the method length() with the String variable sentence
3.
executing the method length() with the String variable sentence
4.
invoking the method length() with the String variable sentence
(All four ways of saying this mean the same thing!)
26
3.1 Constructing Object Types
Objects must be constructed before being used. Instantiate means
to construct. This is true of Scanner objects, Color objects, JFrame
objects and others you will soon find out about. An object is
constructed first, then it can be sent messages or then the object
can call methods.
Scanner reader = new Scanner (System.in); // construct
int x = reader.nextInt(); // send the nextInt() message to reader
reader is the Scanner variable that refers to the Scanner object!
We can also say reader calls the method nextInt().
27
3.1 Constructing Object Types
You can construct a JPanel object to be referred to by the JPanel variable
panel:
JPanel panel = new JPanel();
Then you can send the message setBackground with the parameter
Color.pink to the object referred to by panel using:
panel.setBackground(Color.pink);
You can construct a JPanel object and place a constructed GridLayout
object in the JPanel using the following code:
JPanel panel = new JPanel( new GridLayout ( ) );
Since no variable refers to the GridLayout object being constructed,
we can it an anonymous construction of a GridLayout object.
28
3.1 Important Note About Color Constants
You probably remember initially being introduced to the color
constants:
Color.red
Color.blue
Color.green
and others, where the words red, blue, green, etc. were not
Capitalized. With early versions of Java they were not
capitalized, however, both declarations exist in the Color
class. In other words, you can use Color.RED or Color.red
when writing code.
Our preference will be to use Color.RED so let’s all follow the
standard convention of capitalizing the value.
29
Chapter 3 Section 2
Order of Operations and
Expression Evaluation
Order of Operations
Binary and Unary Operators
Precedence of Operators and Operations
Mixed Mode Arithmetic Expressions
Casting
Rounding Floating-Point Numbers
Escape Sequences
More about Concatenation
30
3.2 Order of Operations
An arithmetic expression consists of operands and operators
combined in a manner just like algebra.
The usual rules apply:
•
Multiplication and division are evaluated before addition
and subtraction.
•
Operators of equal precedence are evaluated from left
to right.
•
Parentheses have the highest precedence and can be
used to change the order of evaluation.
31
3.2 Binary & Unary Operators
Multiplication must be indicated explicitly using * not implicitly.
(In Java, a * b cannot be written as ab like in algebra )
Binary operators are placed between two operands as in a * b.
Other binary operators are +, -, /, and %.
a Unary operator is placed before its single operand as in -a.
Both + and - are unary operators and are the only two that
double as both binary and unary.
32
3.2 Precedence of Operators Chart
Operator
Symbol
Precedence Level
Association
Parentheses
( )
1
Method Selector
.
2
left to right
Unary Minus
-
3
---------
Unary Plus
+
3
---------
Construction
new
3
right to left
Casting
(int)
(double)
3
right to left
Division
/
4
left to right
Multiplication
*
4
left to right
Mod or Remainder %
4
left to right
Subtraction
-
5
left to right
Addition
+
5
left to right
Assignment
=
10
(highest precedence) ---------
(lowest precedence)
right to left
Commonly used operators and their precedence
33
3.2 Mixed Mode Arithmetic Expressions
In Java, you can mix int and double values in expressions. We call
these Mixed Mode Expressions. If you do, as seen below, you
end up with a result that is a double. For example:
double x = 18.2345;
int y = 10;
double sum = x + y; // sum contains 28.2345
double difference = x - y; // difference contains 8.2345
double product = x * y; // product contains 182.345
double quotient = x / y; // quotient contains 1.82345
34
3.2 Dividing Doubles and Ints Using /
In Java, the division operator / calculates the quotient in two different
ways.
First, if a double is divided by a double, then it calculates the quotient
exactly, as in ..
5.0 / 2.0 which yields 2.5
Second, if a double is divided by an int, then it calculates the quotient
exactly, as in ..
5.0 / 2 yields 2.5
(this is mixed-mode arithmetic)
Third, if an int is divided by an int, then it calculates the quotient and
totally drops the remainder even if it is greater than or = to 1/2.
5/2
yields 2
(a quotient in which the remainder 1 of the
division is simply dropped)
35
3.2 Mixed Mode Assignments
Mixed-mode assignments are also allowed in Java, provided
the variable on the left is of the more inclusive type
double than the int value on the right. Otherwise, a syntax
error occurs.
double d;
int i;
i = 45; // OK, because we assign an int to an int
d = 45; // OK, because d is more inclusive than the int
value 45, so 45.0 is stored in d.
i = 45.0;
// Syntax error. Can’t store a double in an int!
36
3.2 Mod Gives the Remainder of Division
In Java, The mod operator % yields the remainder obtained
when an int is divided by another int.
Here are some examples:
9%5
yields 4
5%4
yields 1
5%2
yields 1
8%3
yields 2
13 % 7
yields 6
18 % 6
yields 0
Long hand division
confirms these results.
37
3.2 Precedence of Evaluating Expressions
When evaluating an expression, Java applies operators of higher
precedence before those of lower precedence unless overridden by
parentheses. It then follows left to right order of operations like
algebra.
Here are what some expressions yield:
3+5*3
yields 18
-3 + 5 * 3
yields 12
+3 + 5 * 3
yields 18 (use of unary + is uncommon)
3 + 5 * -3
yields -12
3 + 5 * +3 yields 18 (use of unary – is uncommon)
(3 + 5) * 3
yields 24
3 + 5 % 3 yields 5
(3 + 5) % 3 yields 2
38
3.2 Casting to int or double
•
Casting involves temporarily converting one data type to another for
some purpose involving a calculation.
•
You can cast a single variable or an entire expression.
•
To do this, place the desired data type within parentheses before
the variable or expression that will be cast to another data type.
int i = (int) 3.14;
// 3 is stored in i because (int) truncates the value
double d = (double) 5 / 4;
// stores 5.0 / 4 = 1.25 in d.
1.25 is stored because only the 5 is cast to a double, since 5 is the first
thing after the cast operator (double).
double d = (double) (5 / 4); // stores 1.0 in d … why?
(see next slide)
39
3.2 Casting to int or double
double d = (double) 5 / 4; // stores 5.0 / 4 = 1.25 in d
double d = (double) (5 / 4); // stores 1.0 in d … why?
Java will first evaluate 5 / 4 as int division that gives 1 since it is
in parenthesis. The result of that is the one thing that the cast
(double) is applied to.
So the expression is essentially (double) 1 that gives 1.0
40
3.2 Rounding Positive Values
The cast operator is useful for properly rounding positive floating-point
numbers to the nearest integer. In fact, you need to know the
following formula for the AP Exam.
double p = 45.7;
int answer = (int) (p + 0.5);
Note the approach is to add 0.5 to the value you want to round, which
is stored in x and then cast using (int) which truncates the
calculated 46.2 to 46. So with positive numbers, adding 0.5 and
casting to int rounds the value up or down properly.
45.7 + 0.5 = 46.2
(int) 46.2 ------> 46
41
3.2 Rounding Positive Values
Here is a second example:
double p = 45.2;
int answer = (int) (p + 0.5);
45.2 + 0.5 = 45.7
(int) 45.7 ------> 45
42
3.2 Rounding Negative Values
The cast operator is useful for properly rounding negative floating-point
numbers to the nearest integer. In fact, you need to know the
following formula for the AP Exam.
double n = -22.4;
int answer = (int) (n - 0.5) ;
Note the approach is to subtract 0.5 from the value you want to round,
which is stored in y and then cast using (int) which truncates the
calculated -22.9 to -22. So with negative numbers, subtracting 0.5
and casting to int rounds the value up or down properly.
-22.4 - 0.5 = -22.9
(int) (-22.9) ------> -22
43
3.2 Rounding Negative Values
Here is a second example:
double n = -22.8;
int answer = (int) (n - 0.5);
-22.8 - 0.5 = -23.3
(int) (-23.3) ------> -23
44
3.2 Escape Character & Escape Sequences
•
The Escape character (\) is used in code to represent characters
that cannot be directly typed into a program. They are used when
we want to output something to the screen in a special way.
•
To do this we combine the escape character \ with some other
character to form an escape sequence.
•
Here are 4 different escape sequences:
–
\n is a new line character
–
\” is a double quotes character
–
\\ is a backslash character
–
\t is a tab character
Let’s look at three particular escape sequences of the ones above …
45
3.2 Escape Character & Escape Sequences
String literals are delimited (marked) by quotation marks (“…”),
which presents a dilemma when quotation marks are
supposed to appear inside a string sent to output.
Placing a special character before the quotation mark, indicating
the quotation mark is to be taken literally and not as a
delimiter, solves the problem.
This is where we use the escape character … the backslash \.
Below, the blue “” double quotes surround the overall String
parameter of the System.out.println statement and the red “”
double quotes paired with \ indicate the double quotes to be
shown in output.
System.out.println(“the traffic cop yelled, \”Stop!\””);
46
3.2 Escape Character & Escape Sequences
If we need to actually print a backslash, two consecutive backslashes
\\ are used to accomplish this as seen in the following example:
System.out.println(“C:\\Java\\Ch3.doc”);
This will print to the screen …. C:\Java\Ch3.doc
Additionally, \n can be used to create a new line. The following three
lines of code accomplish exactly the same thing;
System.out.println(“Java Rules!”);
System.out.print(“Java Rules!\n”);
System.out.print(“Java Rules!” + “\n”);
47
3.2 Concatenating Strings and Numbers
As you learned in Chapter 2, Strings can be concatenated to
numbers. What we didn’t tell you was that when we
concatenate everything together the result is a String. What you
may not have realized is that the parameter in a
System.out.println statement has to be a String. Remember this
line where num1 and num2 held integer values:
System.out.println(num1 + " plus " + num2 + " is " + sum);
This is actually a form of implicit (implied) casting where a number is
automatically converted to a string before the concatenation
operator is applied. So num1 is converted to a String and then it
is joined to the word “plus” and so on.
48
3.2 Concatenating Strings and Numbers
You can also concatenate numbers and strings together and store
them in a String variable. We just found out that the result of
concatenation is a String.
String message;
int x = 20, y = 35;
message= “Bill sold ” + x + “ and Sylvia sold ” + y + “subscriptions.”;
The String value “Bill sold 20 and Sylvia sold 35 subscriptions.” is
stored in the String variable message.
49
3.2 Precedence of Concatenation
The concatenation operator has the same precedence as
addition, which can lead to unexpected results:
“number ” + 3 + 4
---> “number 3” + 4
---> “number 34”
“number ” + (3 + 4) ---> “number ” + 7
---> “number 7”
“number ” + 3 * 4
---> “number ” + 12
---> “number 12”
3 + 4 + “ number”
--->
7 + “ number”
---> “7 number”
Intermediate Values
50
Chapter 3 Section 3
Basics about Methods
What is an Algorithm?
Different Uses of Assignment Statements
Writing Methods
More Details about Import Statements
51
3.3 Algorithm Definition
An algorithm is a step-by-step procedure for solving a
problem. In our case, a programming problem.
An algorithm may call a method to perform an operation in each
step of the problem solving process or a method may
implement a particular algorithm to accomplish its work.
52
3.3 Pseudocode Example
When algorithms are being developed, they are often written in part
English and part code. This is called pseudocode. Here is an
example of pseudocode:
calculate area of rectangle (pass in the width and height)
{
area = width x height
}
which becomes in its final form …
public static double calculateArea(double width, double height)
{
double area = width * height;
return area;
}
53
3.3 More About Assignment Statements
An assignment statement has one of three general forms:
< variable > = < initializing value >;
< variable > = < arithmetic expression >;
< variable > = < method call >;
In an assignment statement, the value of the expression on the
right is assigned to the variable on the left. Methods that
return values are almost always part of an assignment
statement!
54
3.3 Methods, Messages, and Signatures
Some classes in Java don’t define a particular kind of object. They
just make a program run. We call these classes “driver files”.
A driver file contains a main method that outputs information to a
console output window. The main method always has the method
signature:
public static void main(String args[])
All of the methods in a driver file must have static in the method
signature or if you try to call them from the main method Java will
show an error. There are other files that have static methods, but
don’t worry about that for now.
55
3.3 Why Do We Have Methods
Sometimes we want to use the same lines of code over and over again
in a program. This could even be hundreds or thousands of
times.
It would be time consuming and tedious to write them out over and
over again, so Java and most other languages allow for the
creation of segments of code called methods, although some
languages call them procedures or functions. It doesn’t matter …
all of them are operations that perform a task.
So once a method is written (and it may have anywhere from 1 to a
large number of lines), we can call it whenever we wish to
execute those lines of code in the method. It is much simpler to
write one line of code over and over again to call a method than to
write all of the lines of code in the method over and over again. 56
3.3 Methods that are Public & Static
By making a method public, we make it available to the methods of
some other class. This means …
•
we can call the method from another method in the class the
method is in, like the main method.
•
we can call the method from a method in another class.
Again, if the method is in a class that has a main method, then we
must include the word static in the method signature. The
examples on the next few slides assume the methods are in a
class file that has a main method.
57
3.3 Void Methods
Void methods do not return a value. They just do some work like
printing. They may calculate something but they do not return
anything.
Here is a void method. The first line is the method signature. Inside
the { } is the body of the method.
public static void printAddress ( String address)
{
System.out.println("The address is :" + address);
}
58
3.3 Void Methods
public static void printAddress ( String address)
{
System.out.println("The address is :" + address);
}
To call this method, we could use this code in the main method:
Scanner reader = new Scanner (System.in);
System.out.print ("Enter the address: ");
String address = reader.nextLine();
// The next line calls the method printAddress passing it address
printAddress (address);
Just the name of the method followed by
the parameters that need to be passed.
59
3.3 Methods that Return a Value
Some methods get or calculate a value and return it. The method
below gets a value from the keyboard and returns it.
public static int getAge ( )
{
Scanner reader = new Scanner (System.in);
System.out.println("Enter the age: ");
int age = reader.nextInt();
return age;
}
Notice that a method that returns a value always has a return
statement that includes the Java keyword return. In this case,
the value store in the variable age is returned.
60
3.3 Methods that Return a Value
public static int getAge ( )
{
Scanner reader = new Scanner (System.in);
System.out.println("Enter the age: ");
int age = reader.nextInt();
return age;
}
To call this method, we could use this code in the main method:
int age = getAge( );
Note that by placing the call to the method on the
right side of an assignment statement, the value
that is returned is stored in the variable age on
the left side of the assignment statement.
61
3.3 Method Signatures
In summary, some methods return a value and others do not.
To use a method successfully we must know:
1.
It’s name
2.
What type of value it returns
3.
The number and type of the parameters it expects
This information is called the method’s signature.
Review the following web page (Write User-Defined Methods) that
we have already covered to remind yourself about how to write
void methods and methods that return a value.
62
3.3 Packages and the import Statement
Java often utilizes code written by many other programmers.
A package makes it easy for programmers to share code. The Scanner
class is in the util sub-package of the java package. We know this by
the import statement:
import java.util.Scanner;
A programmer can collect the classes together in a package, and then
import classes from the package.
The Java programming environment typically includes a large number of
standard packages.
When using a package, a programmer imports the desired class or
classes. Importing all the classes in a package is unnecessary
and bloats the code somewhat. We may do this occasionally
when we do not want to take the time to include specific imports.
63
3.3 General Form of Import Statements
The general form of an import statement is:
import x.y.z;
where
x is the overall name of the package.
y is the name of a sub-package inside the package.
z is the particular class in the subpackage.
It is possible to import all the classes within a subpackage at
once.
The statement to import all the classes within a subpackage looks
like this:
import x.y.*;
A star (*) is used to make available all of the classes in a
package.
64
Chapter 3 Section 4
Consuming New Line Characters
Problematic Order of Input Statements
Consuming the New Line Character
65
3.4 Order of input with nextLine first
The following lines of code create no problem with input when they
are used in this order:
System.out.print(“Enter your name (a string): ”);
String name = reader.nextLine();
System.out.print(“Enter your age (an integer): ”);
int age = reader.nextInt();
System.out.print(“Enter your weight (a double): ”);
double weight = reader.nextDouble();
System.out.print(“Greetings ” + name + “.\n”
“You are ” + age + “.\n”
“You weigh ” + weight + “.\n”);
66
3.4 Bad Order of Input for nextLine
Here there is a problem. The prompt to enter the name is printed and
then without giving the user the chance to enter the name, Java will
print nothing for the name and then print the age and weight.
System.out.print(“Enter your age (an integer): ”);
int age = reader. nextInt();
System.out.print(“Enter your weight (a double): ”);
double weight = reader. nextDouble(); <-- new line not consumed!
System.out.print(“Enter your name (a string): ”);
String name = reader. nextLine();
System.out.print(“Greetings ” + name + “.\n”
“You are ” + age + “.\n”
“You weigh ” + weight + “.\n”);
67
3.4 reader.nextLine() Solution
This problem can be cured by adding a nextLine statement.
System.out.print(“Enter your age (an integer): ”);
int age = reader. nextInt();
System.out.print(“Enter your weight (a double): ”);
double weight = reader. nextDouble(); <-- new line not consumed!
reader.nextLine(); <---- add this to consume the new line character
System.out.print(“Enter your name (a string): ”);
String name = reader. nextLine(); <-- now this works correctly
System.out.print(“Greetings ” + name + “.\n”
“You are ” + age + “.\n”
“You weigh ” + weight + “.\n”);
(The reason this works is on the next slide)
68
3.4 Bad Order of Input for nextLine
Here is the original bad code again. See the note in red below.
System.out.print(“Enter your age (an integer): ”);
int age = reader. nextInt();
System.out.print(“Enter your weight (a double): ”);
double weight = reader. nextDouble(); <-- new line not consumed!
System.out.print(“Enter your name (a string): ”);
String name = reader. nextLine();
This line ended up consuming the new
line character but didn’t allow input.
System.out.print(“Greetings ” + name + “.\n”
“You are ” + age + “.\n”
“You weigh ” + weight + “.\n”);
69
3.4 Be Careful of Order When Using nextLine
double weight = reader.nextDouble();
String name = reader.nextLine();
In the above code, the problem is caused because when the double is
read from the keyboard, the new line character is not consumed by
the nextDouble() method. So it is still sitting there waiting to be read.
When the nextLine() method is called, it consumes the new line
character from the nextDouble line and Java doesn’t know that it is
suppose to take something from the keyboard.
Therefore, an “empty string” value has been placed into the variable
name and we don’t see anything in output when we print out the
contents of name.
70
3.4 Be Aware of Your Input Order
When asking for string and numeric input from the keyboard, there is
always a potential problem if you ask for numeric input first followed
by string input. So the two remedies are:
1) Change the order of your input statements as in:
double weight = reader.nextDouble();
String name = reader.nextLine();
to
String name = reader.nextLine();
double weight = reader.nextDouble();
2) Add a reader.nextLine(); statement after a reader.nextInt() or
reader.nextDouble() statement to consume the “hanging” new line
character in the input stream.
71
3.4 Be Aware of Your Input Order
Or
2) Add a reader.nextLine(); statement after a reader.nextInt() or
reader.nextDouble() statement to consume the “hanging” new
line character in the input stream as in …
double weight = reader.nextDouble();
reader.nextLine(); // consumes the nextDouble() new line character
String name = reader.nextLine();
72
3.4 How nextInt, nextDouble, & nextLine Work
Here is what is really happening when using these methods:
1) The Scanner class method nextInt() returns the first integer in the
input line but ignores leading and trailing spaces or characters.
2) The Scanner class method nextDouble() returns the first double in
the input line but ignores leading and trailing spaces or
characters.
3) The Scanner class method nextLine() returns the input line
including leading and trailing spaces. However, a leading new
line is returned as an empty string when nothing is typed and the
enter/return key is pressed.
73
Chapter 3 Section 5
Program Comments
Single Line Comments
Multi-line Comments
Java Doc Comments
74
3.5 The Purpose of Comments
Program comments are inserted in a program in such a
manner that they….
•
explain the purpose of the program
•
are ignored by the compiler
•
are used to make a program more readable
75
3.5 Comments are Used To …
Comments are used to:
•
begin a program with a statement of its purpose
•
explain the purpose of a variable that needs it
•
explain the purpose of a major segment of code, like a
method
•
explain the workings of complex or tricky sections of
code
•
provide official documentation about a class in an API
76
3.5 Too Many Comments are …
Too many comments are as harmful as too few!
The reasons for this are:
•
they clutter the source code and make it less readable
•
meaningful variable and method names helps document the
program anyway.
•
the program can become more difficult to maintain, because
not only code needs to be changed but the comments need
to be changed when the program is updated.
77
3.5 The Three Types of Program Comments
Program comments come in three varieties:
–
End of line or Single comments: All text following a double
forward slash (//) on a single line may explain a line of code
and are ignored by the compiler.
–
Multi-line comments: All text occurring between a /* and a */
is ignored by the compiler. Multi-line comments are used where
lengthy explanations are needed or you want to deactivate a
large segment of code temporarily.
–
Javadoc comments: All text occurring between a /** and a */ is
ignored by the compiler. These higher level multi-line
comments follow the rules for formatting this information into
what is called an API. An API is web page documentation of a
class or library of classes.
78
3.5 Javadoc Comments
All Javadoc comments occur between a
/** and a */
You can run an operation in Eclipse to generate an API for a class where
you have Javadoc comments. The operation looks for the comments
surrounded by the /** and */ delimiters and this instructs the software to
create a web page for the class that obeys certain rules.
Here is an example from an API. Notice an * appears at the first of each
line inside the overall comments.
/**
* Constructor:
* Creates a grid with dimensions <code>rows</code>,
* <code>cols</code>,
* and fills it with spaces
*/
By using javadoc comments, a programmer can generate browse-able
java documentation.
79
3.5 Check Out These Online APIs
So what really is an API? API stands for Application Program
Interface.
An API is documentation that is like a software manual for
programmers so they can know how to use the classes contained
in a library of files. Programmers can use a software utility to
generate browse-able API documentation for the code they write,
if they have included javadoc comments in their code.
So let’s check out a few:
1)
Go to the String class API and see if you can find the information
about the length() method.
2)
Go to the Scanner class API and see if you can find the
information about the nextInt(), nextDouble(), and nextLine()
methods.
(Click on the links above to go to each one)
80
Chapter 3 Section 6
More about Java Errors
Syntax Errors
Run-Time Errors
Logic Errors
81
3.6 Three Kinds of Programming Errors
•
There are three types of programming errors:
1.
Syntax errors and Compile-time errors keep a program from
running when you try to compile it.
2.
Run-time errors occur after a program is running and the
error is encountered.
3.
Logic errors don’t stop a program from running but cause
incorrect results because something like a formula is coded
incorrectly. It won’t cause the program to stop it will just cause
incorrect results.
When syntax or run-time errors occur in a program, we say the
program “throws an exception”. Throwing an exception is just
Java’s way of saying an error has occurred that won’t let the
program continue.
82
3.6 Syntax and Compile-Time Errors
•
Syntax errors and Compile-time errors keep a program from
running when you try to compile it. Some of them are:
•
a programmer misspells a method name like println
•
a programmer forgets to put a semicolon at the end of a line
where it is needed
•
trying to store a data value of one type in a variable of another
type
•
leaving out the opening or ending curly brace for a method
These errors are detected when the programmer tries to compile and
run a program. In this case, the program will never start, and you
will see error messages in the console window. These messages
identify the line or lines of code that have syntax errors and may
describe the syntax error.
83
3.6 Run-Time Errors
Run-time errors occur after a program is running and the error is
encountered.
Examples are:
1.
If a program is running an it asks the user to enter a double value but
a string value is entered, then the program will “crash” or halt and
show you a InputMismatchException error in the console window.
Note: the program will compile and run OK until the string is entered.
(see next slide)
2.
If the code of a program is written so that division by 0 occurs, then
the program will halt (stop) and “throw” what is called an
ArithmeticException error. (see 2 slides ahead)
3.
If a program compiles and runs but you have declared an object
variable but not constructed an object for it to refer to, then you will
get a NullPointerException if you try to send a message to that
object. (see 3 slides ahead)
84
3.6 InputMismatch Exception
If the program is expecting an int and a string is entered,
an InputMismatch Exception is thrown:
public static void main (String [] args)
{
Scanner reader = new Scanner (System.in);
System.out.print("Enter an integer: ");
int i = reader.nextInt(); // line 11
System.out.println ("The value of i is " + i);
}
In the console window, you would see:
Enter an integer: java
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at ch03.RunTimeWrongData.main(RunTimeWrongData.java:11)
85
3.6 ArithmeticException
If the code of a program is written so that division by 0 occurs, because 0
is entered from the keyboard, then the program will halt (stop) and
“throw” what is called an Arithmetic Exception exception:
Scanner reader = new Scanner (System.in);
System.out.print("Enter an integer for the variable j: ");
int divisor = reader.nextInt();
int quotient = 3 / divisor;
System.out.print("The quotient of 3 divided by ");
System.out.println(divisor + " is " + quotient);
In the console window, you might see:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ch03.DivideByIntegerZero.main(DivideByIntegerZero.java:8)
86
3.6 Default Values of Variables
If you declare variables of any time but do not initialize them, Java will
give them certain values by default. For example:
int x;
// 0 will be stored in x
double y;
// 0.0 will be stored in y
boolean done;
// false will be stored in done
Scanner reader;
// null will be stored in reader
String name;
// null will be stored in name
Color myColor;
// null will be stored in myColor
Any object of any class is set to null .
This is important to know because it can affect the code in your
program if you do not initialize them and then you never give the
variable a value through any code. Errors can occur.
87
3.6 NullPointerException
If the code of a program is written so that an object is not instantiated
and that object tries to call a method, then the program will hold
and throw a NullPointException exception. Example:
public static void main (String [] args)
{
Scanner reader; // should have = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = reader.nextLine(); // line 13
System.out.println ("The name is " + name);
}
In the console window, you would see:
Enter your name: Exception in thread "main" java.lang.NullPointerException
at ch03.RunTimeNullPointer.main(RunTimeNullPointer.java:13)
88
3.6 Logic Errors
Logic errors don’t stop a program from running but cause incorrect
results.
For example:
A programmer intends to code the line …
celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
but instead writes the following valid line of code …
celsius = (fahrenheit - 212.0) * 5.0 / 9.0;
then this is a logic error. Java just checks syntax. It doesn’t
check your logic.
The program will compile and run but it gives incorrect results,
because 212.0 should be 32.0 above. There is not anything
syntactically wrong with the code. Java calculates what you tell it
to calculate. You have to test your code to see if it produces the
correct results. So always Run and Test!
89
3.6 Desk Checking to Preventing Errors
The best way to prevent errors is to do what is called desk
checking.
Desk checking is where a programmer proofreads the code of
a program immediately after it is written before he runs it.
Many times we are in a hurry or we are coding late and night
and we are tired.
If you will proofread your code before you run it, then you will
catch most of your errors and save time.
90
3.6 Debugging with Output Lines
Sometimes the nature of a bug suggests its general location in
a program.
One debugging method is to add extra System.out.println
statements to print values of selected variables at strategic
points in the program. If you find an incorrect value stored in a
variable, move backward through the code to find the possible
problem line.
logic error
extra debug line
91
Chapter 3 Section 7
Intro to Java Graphics
The Graphics Context g (the paint brush)
The Graphics Drawing and Painting Commands
92
3.7 Multi-File Graphic Programs
Dividing the responsibility of a program between different classes
or files can be a way of simplifying its organization and
allowing for easy troubleshooting.
Our first graphics program will have two files with different
responsibilities:
1.
A driver file named BasicPaintingApplet whose responsibility
is to run the program.
2.
A graphics file named BasicPaintingPanel class whose
responsibility is to draw and paint everything on a panel.
Here we will write the code for all of the Java graphics
commands to draw or paint what we wish.
93
3.7 Code for BasicPaintingApplet File
public class BasicPaintingApplet extends JApplet
{
BasicPaintingPanel panel;
public void init ()
{
resize(900, 800);
Container c = getContentPane();
panel = new BasicPaintingPanel(Color.gray);
c.add(panel);
In this code, we are calling the
}
BasicPaintingPanel constructor
located in the BasicPaintingPanel
class in the second file.
public void paint(Graphics g)
{
super.paint(g);// must have to paint background gray
panel.paintComponent(g);
}
}
94
3.7 The Responsibility of the Two Files
BasicPaintingApplet.java has the responsibility for:
•
Constructing a new window
•
Constructing a BasicPaintingPanel object
•
Adding the panel object to the window’s content pane.
This class does NO drawing!!!
The BasicPaintingPanel class will have the responsibility of
executing Java drawing and painting commands.
95
3.7 The BasicPaintingPanel Class
Here is some of the code of this panel class:
public class BasicPaintingPanel extends JPanel
{
public BasicPaintingPanel (Color color)
{
setBackground(color);
}
public void paintComponent (Graphics g)
{
super.paintComponent(g);
…. (other code)
This is the
BasicPaintingPanel
constructor. We know this
because any constructor
method has a name that is
exactly the same as the
name of its class and it
doesn’t have a return type.
Constructors are the only
methods that don’t have
return types.
96
3.7 Graphics: Drawing Shapes and Text
•
The reason for the BasicPaintingPanel class is to create a
specialized graphics panel to draw on. This new class must extend
the JPanel class.
•
By extending the JPanel class, it inherits all of the properties
and methods of a JPanel, but the new class BasicPaintingPanel can
add other methods if necessary.
•
The most important methods that the BasicPaintingPanel class has is
its constructor and it will need to override the paintComponent()
method of the JPanel class by providing its own paintComponent()
method.
97
3.7 The Java Graphics Coordinate System
•
Every Java graphics program uses a coordinate system similar
to the one used in geometry. Positions of items in a Java graphics
window are specified in terms of two-dimensional points (x, y).
•
The main difference is that the origin (0, 0) for a Java graphics
window is located at the upper-left corner of a panel or frame.
•
Because you can have several panels in a Java window, each
panel has its own coordinate system with its origin in the upper-left
corner.
98
3.7 The Java Graphics Origin
Java’s origin
(0, 0) is the
upper-left hand
corner of the
applet window.
x values increase to the right and y values increase downward.
99
3.7 The Java Graphics Class and Paint Brush g
Java has a Graphics class that allows programmers to draw
or paint on a panel using a pencil or brush object named g.
Every panel that is created maintains this object named g that is
formally called the graphics context. You can think of g as a
pencil for drawing and at the same time a paint brush for
painting. So g has the ability to draw or paint!
100
3.7 The Java Graphics Class and Paint Brush g
Shapes drawn on a panel by the Graphics class have a
foreground color for g. That way the background color can
stay the same while you draw or paint with another color.
You can change the foreground color by using g to call the
setColor() method as in …
g.setColor(Color.yellow);
Every time we want to draw or paint,
we will use g to call a method.
101
3.7 Java’s Default Color Constants
Color Constant
RGB Value Construction
Color.red
new Color (255, 0, 0)
Color.green
new Color (0, 255, 0)
Color.blue
new Color (0, 0, 255)
Color.yellow
new Color (255, 255, 0)
Color.cyan
new Color (0, 255, 255)
Color.magenta
new Color (255, 0, 255)
Color.orange
new Color (255, 200, 0)
Color.pink
new Color (255, 175, 175)
Color.black
new Color (0, 0, 0)
Color.white
new Color (255, 255, 255)
Color.gray
new Color (128, 128, 128)
Color.lightGray
new Color (192, 192, 192)
Color.darkGray
new Color (64, 64, 64)
If you were going to construct these colors by yourself, you would
use the 3 integer values in the parenthesis.
102
3.7 The drawLine Command
To draw a line in Java, you use g with the method named
drawLine.
The general form of the drawLine command is:
g.drawLine(x1, y1, x2, y2);
where you are drawing between two points, namely (x1, y1)
and (x2, y2).
So the line of code:
g.drawLine(0, 0, 25, 75);
draws a line between the two points (0, 0) and (25, 75), where g
is the object, drawLine() is the method, and 0, 0, 25, and 75
are the parameters.
103
3.7 Customized Colors
You can construct a customized color if the color you need is not
one of the Color constants seen on the previous slide.
You can construct a new Color object by using three int values
between 0 and 255 with:
Color myColor = new Color(redValue, greenValue, blueValue);
In this code, redValue, greenValue, blueValue must be integer values.
You would then use the code:
g.setColor(myColor);
( don’t use Color.myColor in () )
Here is an actual example:
Color brown = new Color(164, 84, 30);
g.setColor(brown );
(don’t use Color.brown in () )
104
3.7 The drawRect & fillRect Commands
To draw the outline of a rectangle, follow the general form of the
drawRect command:
g.drawRect(x, y, width, height);
To do this you must know the point (x, y) which represent the upperleft corner of the rectangle and you must know the width and height
of the rectangle. This will draw the rectangle so that its sides are
oriented in either vertical or horizontal directions. You can never
draw a rectangle at an angle.
(x, y)
width
height
105
3.7 The drawRect & fillRect Commands
To draw the outline of a rectangle with upper left corner represented
by the point (50, 200) that has a width of 300 and a height of 150
use:
g.drawRect(50, 200, 300, 150);
To paint a rectangle with upper left corner represented by the point
(50, 200) that has a width of 300 and a height of 150 use:
g.fillRect(50, 200, 300, 150);
To draw an outline of a figure, the method name will always start with
the word “draw”.
To paint a figure, the method name will always begin with the word
“fill”.
106
3.7 drawRoundRect & fillRoundRect
To draw the outline of a rounded-rectangle, follow the general form of
the drawRoundRect command:
g.drawRoundRect(x, y, width, height, arcWidth, arcHeight);
Draws the outline of a rounded rectangle whose upper-left corner is (x,
y) and whose dimensions are the specified width and height. The
corners are rounded according to the last two parameters. To make
them perfectly symmetrical, make the last two values equal.
(x, y)
height
width
arcHeight
arcWidth
107
3.7 drawRoundRect & fillRoundRect
To draw the outline of a rounded-rectangle with the upper-left corner
represented by the point (300, 400) with a width of 100 and a
height of 50 that has an arcWidth of 10 and an arcHeight of 10 use:
g.drawRoundRect(300, 400, 100, 50, 10, 10);
To paint the same rounded-rectangle use:
g.fillRoundRect(300, 400, 100, 50, 10, 10);
108
3.7 The drawOval & fillOval Commands
To draw the outline of an oval with upper left corner represented by
the point (50, 200) where the oval is circumscribed by a rectangle
with a width of 300 and a height of 150 use the general form:
g.drawOval(x, y, width, height); giving …
g.drawOval(50, 200, 300, 150);
To paint the same oval use
g.fillOval(50, 200, 300, 150);
(50, 200)
width
height
The height and width values determine the curvature characteristics of the oval
109
3.7 The drawArc & fillArc Commands
To draw or paint an arc, use one of the following:
g.drawArc(x, y, width, height, startAngle, arcAngle); or
g.fillArc(x, y, width, height, startAngle, arcAngle);
This command draws the outline of an arc that is a portion of an oval.
It fits within a rectangle whose upper-left corner is (x, y) and whose
dimensions specify the width and height of an oval that the arc is
part of. The arc is drawn from startAngle to startAngle + arcAngle.
The angles are expressed in degrees. A startAngle of 0 indicates
the 3 o'clock position. The arcAngle indicates how much and what
direction is swept to draw the arc. It can be positive or negative. A
positive arc indicates a counterclockwise rotation, and a negative
arc indicates a clockwise rotation from 3 o'clock.
110
3.7 The drawArc & fillArc Commands
Example: draw or paint the arc whose upper-left corner of its
imaginary oval is the point (100, 100) where the oval has a width of
50 and a height of 50 and whose startAngle is 90 and whose
arcAngle is 270.
Code: g.drawArc(100, 100, 50, 50, 90, 270);
start angle of 90
(100, 100)
height of 50
imaginary rectangle
that surrounds
imaginary oval that
the arc is part of.
0 degrees = 3 o’clock
270° draw or paint
width of 50
111
3.7 drawPolygon & fillPolygon
To draw or paint a polygon, use one of the following:
g.drawPolygon(xvalues, yvalues, n); or
g.fillPolygon(xvalues, yvalues, n);
Draws or paints a polygon where the abscissas (Xs) and ordinates
(Ys) of a set of points have been defined in two simple arrays prior
to making a call to either of the methods. The parameter n
represents the number of sides of the polygon. We usually just
place the correct number in place of n. For example, if we are
making a triangle with 3 sets of points, then we put 3 in place of n.
112
3.7 drawPolygon & fillPolygon
Example: draw or paint the triangle that has the three points:
(x1, y1) = (100, 25) (x2, y2) = (150, 75) (x3, y3) = (200, 50)
Here is the code you would need:
int [ ] xvalues = {100, 150, 200};
Note how they are placed: int [ ] xvalues = {x1, x2, x3};
int [ ] yvalues = {25, 75, 50};
Note how they are placed: int [ ] yvalues = {y1, y2, y3};
then you can use:
g.drawPolygon(xvalues, yvalues, 3);
or
g.fillPolygon(xvalues, yvalues, 3);
113
3.7 The drawString Command
To draw a String to a panel use the general formula:
g.drawString(str, x, y);
where str is a String variable or a literal String value in double quotes,
and the point (x, y) indicates the position of where the base line
starts for what is to be printed.
Example: draw the words "Java Rules" at the point (10, 50).
g.drawString("Java Rules", 10, 50); or
String str= “Java Rules”; g.drawString(str, 10, 50);
(10, 50)
Java Rules
baseline
start of baseline
114
3.7 Changing Fonts for drawString()
When you run a JFrame or JApplet program, Eclipse or other
IDEs will always use your default system font when you call
drawString().
To change the drawing font, you need to define a font then
set the drawing font to that font. The code is on the next
slide:
115
3.7 Changing Fonts for drawString()
Here are the steps to change the drawing font:
Step 1. Define a font.
Step 2. Set the font.
Step 3. Draw the string.
Example:
Step 1.
Font font1 = new Font ("Arial", Font.BOLD, 18);
Step 2.
g.setFont(font1);
Step 3.
g.drawString("Java Rules", 100, 100);
The general form of the Font constructor line is:
Font font = new Font (<Font Name>, <Font Style>, <Font Size>);
The Font Name must be in double quotes.
The Font Style is usually a constant from the Font class. It can be:
PLAIN, BOLD, ITALIC, or BOLD + ITALIC.
116
3.7 The getWidth() and getHeight() Methods
The width and height of a panel can be found using the getWidth()
and getHeight() methods, respectively.
They return int values that give the number of pixels wide or the
number of pixels high of the panel.
This can be helpful for things like centering something in the center of
a panel no matter what its size is.
When calling these methods, do not use g.getWidth() or g.getHeight()!
One good way to use them is as parameters when using the
drawString method:
g.drawString(“Go Bearcats”, getWidth() / 2, getHeight() / 2);
117
3.7 Drawing and Painting Web Page
The drawing and painting commands web page discusses these
preceding commands and also tells you how to change the font
if you don’t like the default font when using drawString.
http://ww2.kcd.org/apcsa/special/DrawingCommands.html
118
3.7 The JPanel paintComponent() Method
When we create a class like ColorPanel that extends JPanel, we will
always have a paintComponent() method, and the first line of
code in it must always be ….
super.paintComponent (g);
This line of code produces a fresh blank panel for the
BasicPaintingAndDrawing class to use and prepares it for drawing
or painting. Your code will follow that line of code.
Your method paintComponent() in BasicPaintingAndDrawing will
automatically be called by the JVM when the panel needs to be
drawn.
If someone is viewing your panel and decides to resize the window,
then the JVM will automatically call your paintComponent() method
which will then call super.paintComponent(g); (which erases the
panel) then your drawing code will be executed and the panel will
be redisplayed.
119
3.7 Over-Riding the paintComponent() Method
This year you are going to be over-riding methods! You are doing it
for the first time in the ColorPanel class!
If you could go look at the code of the JPanel class, you would find a
method with the method signature of …..
public void
paintComponent (Graphics g)
But you have a method with that exact method signature in your
ColorPanel class and the class definition of your ColorPanel class
is ….
public class ColorPanel extends JPanel
By including “extends JPanel” in your class definition line and the
method paintComponent with that exact method signature, then
you are “over-riding” the paintComponent method. (More on next
slide)
120
3.7 Over-Riding the paintComponent() Method
By over-riding the method paintComponent, you are telling
Java to NOT execute the paintComponent method of the
JPanel class but instead to execute your paintComponent
method that has your drawing code.
However, to make sure the panel is repainted properly with the
background color when resized we need to call
super.paintComponent and it has to be the first line of code
in your paintComponent method.
121