Gill&ChrisJava Booklet
Gill&ChrisJava Booklet
BYTECODES........................................................................................................................................................................1
Java Page - 1
Table of Contents Last printed 2/3/2004 10:24:00 AM
PRACTICAL EXERCISES 9............................................................................................................................................25
TYPE IN, AND GET THE ABOVE CLASS GOING.INTRODUCTORY EXERCISE 10 - REAL NUMBERS
(AND MORE!) 25
Java Page - 2
Table of Contents Last printed 2/3/2004 10:24:00 AM
A summary of the theory of methods in Java................................................................................................................48
The method call............................................................................................................................................................48
Formal and Actual parameters....................................................................................................................................50
Call-By-Value and Call-By-Reference.........................................................................................................................50
Method Overloading.....................................................................................................................................................51
Modularising Graphics................................................................................................................................................52
More advanced topics, including notes on using the JWS API help:...........................................................................53
Public private and protected methods..........................................................................................................................53
Instance and Static methods.........................................................................................................................................53
Instance and Static variables.......................................................................................................................................53
Wrapping......................................................................................................................................................................54
Methods and Constructors...........................................................................................................................................54
Classes and Interfaces:................................................................................................................................................54
Programming exercises 16...........................................................................................................................................55
Introductory exercises in Methods...............................................................................................................................57
EXERCISE 17 MOUSE EVENTS AND EVENTS DUE TO OTHER COMPONENTS EVENTS...........................60
The ActionListener interface........................................................................................................................................60
How do you decide which component generated an event?.........................................................................................60
Other interfaces............................................................................................................................................................60
Some other components that generate Events..............................................................................................................61
Checkboxes (use ItemListener interface).....................................................................................................................62
Scroll bars (uses AdjustmentListener interface)..........................................................................................................64
Keyboard events (including the KeyListener interface)...............................................................................................65
Mouse events: MouseListener interface.......................................................................................................................66
Mouse events: MouseMotionListener interface...........................................................................................................67
Using the mouse to draw on the screen........................................................................................................................68
Practical exercises.......................................................................................................................................................70
EXERCISE 18 JAVA NOTES: CONTROL STRUCTURES.................................................................................71
Conditional statements.................................................................................................................................................71
If statement:..................................................................................................................................................................71
Compound if statement.................................................................................................................................................71
Nested if statements......................................................................................................................................................71
if .. else statements........................................................................................................................................................71
The “dangling” else.....................................................................................................................................................72
Switch statements.........................................................................................................................................................72
Programming exercises 18...........................................................................................................................................73
Theoretical exercises 18...............................................................................................................................................74
Break and continue.......................................................................................................................................................78
While and do loops.......................................................................................................................................................78
“break” and “continue” in while and do loops...........................................................................................................79
Theoretical exercises....................................................................................................................................................79
More Programming exercises......................................................................................................................................80
EXERCISE 19 CLASSES AND OBJECTS..............................................................................................................83
What are objects and classes?......................................................................................................................................83
Instantiating an object..................................................................................................................................................83
What are principles of object-oriented programming (OOP)?....................................................................................83
Inheritance....................................................................................................................................................................87
Exercises 19..................................................................................................................................................................89
Objects & Classes- exercises.......................................................................................................................................91
Initialization and construction.....................................................................................................................................91
Summary: GUI objects.................................................................................................................................................93
Sample questions from mid year papers.......................................................................................................................97
EXERCISE 20 ARRAYS..........................................................................................................................................101
Array Processing Techniques.....................................................................................................................................102
Making A Copy Of An Array......................................................................................................................................103
Sorting An Array........................................................................................................................................................103
Two-Dimensional Arrays...........................................................................................................................................105
Arrays programming exercises 20.............................................................................................................................107
Java Page - 3
Table of Contents Last printed 2/3/2004 10:24:00 AM
Problems in Arrays 20................................................................................................................................................108
EXERCISE 21 CHARACTERS AND STRINGS..................................................................................................111
Strings.........................................................................................................................................................................111
Exercises 21................................................................................................................................................................114
EXERCISE 22 THREADS IN GAMES WITH ANIMATION.............................................................................115
Single Thread.............................................................................................................................................................115
Two Threads...............................................................................................................................................................115
Three Threads.............................................................................................................................................................115
Four Threads..............................................................................................................................................................115
Many Threads.............................................................................................................................................................115
A summary of the techniques used to control various numbers of Threads...............................................................116
Single Thread.............................................................................................................................................................116
Multiple Threads........................................................................................................................................................116
Runnable.....................................................................................................................................................................117
Declaring separate Classes to create the multiple Thread objects............................................................................117
Stopping a Thread......................................................................................................................................................118
EXERCISE 23 GRAPHICS IN GAMES WITH ANIMATION...........................................................................120
How do you draw to the screen?................................................................................................................................120
Double Buffering........................................................................................................................................................120
Update........................................................................................................................................................................120
Using file images........................................................................................................................................................121
Problems with starting the program..........................................................................................................................121
Flicker1......................................................................................................................................................................122
Flicker2......................................................................................................................................................................122
Flicker3......................................................................................................................................................................122
Exercise 24 Notes on games which make use of Thread techniques.................................................................123
Java Page - 4
A Word about the Java Platform
The Java platform consists of the Java application programming interfaces (APIs) and the Java
virtual machine (JVM).
Java APIs are libraries of compiled code that you can use in your programs.
They let you add ready-made and customizable functionality to save you
programming time.
javac
The "Java interpreter" in the picture is an executable program that is running on the computer
system. Each type of computer system has its own Java interpreter that can run on that system. The
"Actual processor" is the actual, hardware, processor chip of that computer system.
(Another) Important Idea: The Java interpreter running on any computer system "looks like" the
hardware Java processor chip. It is a Java Virtual Machine.
Any computer system can execute all Java bytecode programs if it has a Java interpreter. The Java
interpreter has to be specifically written for the specific processor type of the computer system, but
once that is done, the computer system can become a Java virtual machine. That is, it looks like a
computer with a Java processor chip and can run Java bytecodes.
Remember that when a Java program is translated into bytecodes, the bytecodes are exactly the
same no matter what computer system is used. This means the bytecodes on a Sun computer can
be sent to an Intel based computer and they will run without a problem.
An applet is a Java bytecode program that runs on a Web browser. Most up-to-date Web browsers
include a Java interpreter. A Web page on a host computer on the Internet can contain instructions
that send Java bytecodes to a client computer (like yours) that has asked to view the page. The
Web browser on the client runs the Java applet with its built-in interpreter.
A Java tutorial which takes you through the basics of programming in Java.
http://www.javasoft.com/docs/books/tutorial/java/index.html
The Java API help, which provides a reference to the Java language. The opening page describes how to use
the API help. For the time being much of this will be difficult for you. We will briefly cover how to interpret
some features of this help later on.
http://java.sun.com/j2se/1.4/docs/api/index-files/index-1.html
//An introductory class to illustrate the use of Graphics objects,Fonts and Colors.
//Paint (Graphics g) is one of the standard methods which is always used in a java applet.
//In this case we have added a few graphics to it.
Packages
The Java Applications Programming Interface (API) contains a large number of programming
features grouped into “packages” of related features. When you write a class in Java you must
import those packages which are used in the class.
Class
We will have a lot more to say about classes in this course. For the time being, you can regard a class
as a program, and every class that you write will begin with the line:
One of the standard methods used in java applets is the paint( ) method. This is responsible for
painting graphics and text into the applet window.
If you want to use the paint method you always begin with the line:
Fonts
The font names available are “Serif”, “SansSerif”, “Monospaced”.
The font styles available are Font.PLAIN, Font.BOLD and Font.ITALIC.
The font size is a whole number.
You can set a font in the paint() method with a line such as:
To find out more about fonts you can look up the the Java API following the links
Java API | Package Java awt | Classe Index Fonts.
You will notice that the awt package includes many more of the classes you would expect to use
such as Color.
Colors
Colors are most easily specified by their Red, Green and Blue RGB components, which are each
integers from 0 to 255.
You can set a colour in the paint( ) method with a line such as:
(This is a colour containing the maximum amount of red, about half green and no blue.)
g.setColor(Color.green);
Window Coordinates
When you draw a graphics object on the applet window, you must specify its coordinates.
Strings
A string is a piece of text enclosed in inverted commas, such as “Hello”. To write a string onto the
applet window in paint() you use a programming line such as:
If you want to use a font other than the standard font you must set it before you use g.drawString.
Graphics Objects
The java.awt package provides a number of graphics objects. To find out all that are available, look
up the Java WorkShop Help under:
***Help | Java API Documentation | Package Java awt | Class Index | Graphics
4. Select the Applet Project radio button (in this course we will be dealing with Applets only)
5. Delete unwanted code from the default class that appears on the screen and type in the above
PaintDemo class. Remember that Java is CASE SENSITIVE so be careful to retain the case (ie
upper or lower case) as written above.
8. If you have errors – check you uppercase / lower case / spelling etc. Most problems will occur
from small spelling mistakes.
9. If no errors press the RUN APPLET button and you should see the following:
10. Now modify the class to suit your own tastes: you should try
11. Try to produce the following with a font size of 80, red text “ELLO”, white text “H” and a blue
rectangle behind the “H”:
Introduces
int (integer) variables
the init() method
basic integer operations
g.drawString used to print out integer values
import java.applet.Applet;
import java.awt.*;
// Globally declare two integers and variable names for their sum, difference,
// product, quotient and remainder.
Notes
Variables
Variables are spaces in computer memory which store things such as numbers and characters.
When you declare a variable you tell the class what type of variable it is (eg integer or real number)
and give it a name. The class then sets aside the appropriate memory space for the variable, so that
you can use this throughout the class.
A global declaration (immediately after the main class definition) means that all the “methods” of
the class can use these variables and their values.
Basic integer operations
Assignment:
n = 4; //assigns the value 4 to variable n
Sum:
sum = 4 + 7; //the variable sum is assigned the value 4 + 7
sum = n + 4; //variable sum becomes n + 4 where n is another integer variable.
Product:
prod = n * 4; //variable prod is assigned the value n*4
Integer division:
quot = n / 4; //eg 7/4 = 1; 13/4 = 3 etc
Integer remainder or “modulus”:
rem = n%4; //eg 7%4 = 3; 13%4 = 1 etc
Breaking up the class into different methods in this way makes the class much easier to manage and
more versatile.
to write out the value of the variable. Note that to use drawString in this manner you must precede
the integer by a string.
Practical Exercise 2
You might wish to declare new variable names for each of these quantities.
Theoretical Exercise 2
There are about 12 mistakes in the following class. How many can you identify?
(Lines are numbered for convenience in answering.)
1. import java.applet.Applet;
2. import java.awt.*;
5. int n, m, sum;
Introduces
Declaring and instantiating global color and font objects.
import java.applet.Applet;
import java.awt;
// This class is similar to the PaintDemo class except that the init method (another standard
// method used in java applets) is used to initialise the colors and fonts used in paint.
// To transfer the information from init to paint we must first declare the color and font as
// "objects" that can be accessed in both paint and init.
//The init method is used in this case to set some global colours and fonts.
//The paint method can now make use of the colours and fonts defined in init().
Objects
Objects are the basic “modules” of an object oriented program. In the above class, color1, color2,
color3 and font1 are objects. Objects are stored in memory like variables, but have many more
features than variables.
Objects include
data (such as the RGB values of the color objects in the above class)
“methods” or operations on that data (such as the setColor method).
When objects are used in a class they must be set up in memory. This is called “instantiating” the
object.
Setting up objects in a class
In the first class we used a class line such as
When we do this we set the new colour as an object in memory. However, this new colour is only
used until the next new colour is set. If we have a colour that we want to use on different occasions,
we must declare the colour by giving it a name before we instantiate it.
We declare the colours we a going to use with a program line such as:
When we want to give the colour a value in memory (“instantiate” the color) we use the new
command:
color1 = new Color(255, 50, 50);
We can now set out new colour in the paint() method with a program line such as:
g.setColor(color1);
When the objects are made available to the whole class in this way we say that they are declared
globally.
Practical Exercise 3
1. Copy and run the above class as before. Be sure to give your project the same name as the class
(in this case ObjectDemo).
2. Declare some new colour and font objects. Make up your own names for the objects (a
combination of letters and numbers).
3. Instantiate the objects in the init() method using new.
4. Set the objects in the paint() method and use them in your own applet.
5. Check with your teacher when finished.
Introductory Exercise 4 -Strings
Introduces
The String class
Various methods of constructing string
String methods length(), toUpperCase(), toLowerCase(), trim(), replace().
The String class is contained in the java.lang package which is automatically called for all classes (so
that it does not need to be imported).
import java.applet.Applet;
import java.awt.*;
Since Strings are objects, the normal way to set up a string in a class is to declare it and instantiate it
using new.
String methods
A number of the string methods are illustrated in the above class. These are:
Practical Exercise 4
1. Copy and run the above class as before. Be sure to give your project the same name as the
class (in this case StringtDemo).
Introductory Exercise 5 - Components
Introduces
Components (including Label, TextField and Button)
The add operation
import java.applet.Applet;
import java.awt.*;
//The init method sets up the GUI components that have been declared globally.
//To do this we must:
// - "instantiate" the components using the "new" command. This provides space in
memory for the components.
// - "add" the components to the applet window, in the left to right, up to down order in
// which they are added in init.
//place components in the applet window in the order written left to right, then
//downwards.
add (myPrompt1);
add (myPrompt2);
add (value1);
add (value2);
add (addButton);
}
}
Notes
Components
Components are Graphical User Interface (GUI) objects which are used to provide an interface for
the user, enabling the user to enter data into the class. There are many such components, including
TextFields, Buttons, Menu, ScrollBar and so on. They are described under the Help | API | java.awt.
Setting up components in an applet window
To set up a component in an applet window you must:
1. Declare the component giving it a name which by convention starts with a lower case letter. A
typical declaration is:
Button myButton; //declares a Button object of name myButton
The components are placed in the applet window in the order in which they are added, left to right
and top to bottom.
Practical Exercise 5
Copy out the class into a new project and adjust the size of the components and the window to give
you a good layout.
At this stage you can type into the text fields, but it won’t do anything.
Introductory Exercise 6 - Events
Introduces
java.awt.event.*
ActionListener and actionPerformed (ActionEvent e)
Converting text to integer using Integer.parseInt and Integer.valueOf
Converting integer to text using Integer.toString
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*; //Handles events initiated by the user
// This class extends the previous class ComponentDemo to actually provide a means of adding
// up the numbers. It does this by including an Action Event method.
// Additions to ComponentDemo are in bold type.
//The class definition includes "implements ActionListener which tells the class to "listen"
for //"events" set of by the user.
// In this case, the event being listened to is the press of a "button in the applet window.
//The method "actionPerformed (ActionEvent e)" is used to "listen" to events and respond
public void actionPerformed(ActionEvent e)
{
//The user must type the integers into the text fields. When the button is pressed,
// - the text field strings are converted to integers (two different methods are
// provided – they do the same job.
// - the integers are added together
// - the sum is displayed in the status bar.
2. Tell the class which events to listen to (there might be a number of possible events):
addButton.addActionListener(this);
In this case, we are telling the class to listen to the GUI component that we have named
“addButton”. The word this tells the class that “this” class is doing the listening (it is possible to
listen to events in other classes).
Here parseInt is one of the methods of the Integer class, which converts a string to an integer.
valueOf is another method of the Integer class. We won’t worry about the details of this
approach for the time being and you will probably prefer to use parseInt in your classs.
getText is one of the methods of the TextField class which retrieves the text from the Text Field.
An integer must be converted back to a string to print it out on the window. One way to do this is to
concatenate the number to a string as we did in the second exercise.
However, to print out the number without a preceeding string you need to use the toString method
first in a line such as:
If there is only one answer to print out, we can avoid using paint() by printing the answer in the
status bar at the bottom of the applet window, using the line:
showStatus(Integer.toString(answer));
Practical Exercise 6
1. Copy and paste the ComponentDemo class into a new EventDemo project and modify it as
above.
2. Modify the class to:
Print out the answer within the window (using paint()).
Print out the product of the numbers instead of the sum.
3. Allow the class to listen to a press of the <return> key when the cursor is in one of the Text
Fields by adding the following programming lines to init():
value1.addActionListener(this);
value2.addActionListener(this);
Theoretical Exercise 6
1 import java.applet.Applet;
2 import java.awt.*;
5 Label myPrompt;
6 TextField value1, value2;
7 int num1, num2, answer;
21 num1 = Integer.parseInt(value1.getText);
22 num2 = Integer.valueOf(value2.getText).intValue();
23 answer = num1 * num2;
24 showStatus(answer);
25 }
26 }
Introductory Exercise 7 -Images
Introduces
Image objects
getImage, getDocumentBase, drawImage methods.
import java.applet.Applet;
import java.awt.*;
//Next line gets an image stored in the same directory as the HTML.
//These images can be imported or created in Paint Shop Pro.
butterfly = getImage(getDocumentBase(),"butterfly.gif");
picture = getImage(getDocumentBase(), "picture.gif");
}
Getting an image
You can draw any gif image onto your applet window. To obtain a gif image, have a look in Paint
Shop Pro (on your computers) and either import an image or create one.
where the two numbers are the x and y coordinates of the top left of the image, and “this” again tells
the class to draw the image in this applet.
Another draw image method allows you to specify the width and height of the image drawn in the
window :
Here the 4th and 5th parameters tell the class the width and height of the image on the window. In the
class above we used the getWidth and getHeight methods to find the width and height of the
original image and then multiply these by two so that the final drawn image was twice the size of the
original.
Practical Exercise 7
Have a bit of fun, and remember that you will eventually be incorporating java applets in web pages.
Use Paint Shop Pro to draw or import some images which you can then put into the applet.
Introductory Exercise 8 -Sound
Introduces
The play method
AudioClip class and method getAudioClip
//This very simple class will play an audio file of type .au stored in the same folder as the //
SoundDemo project. It will play the sound once only.
import java.applet.Applet;
Notes
The sound file formats supported by Java 2 include files ending with .au, .wav, .midi, and .aiff. You
can find suitable files if you do a search for *.au or *.wav.
Au files can be found at C:\Java-WorkShop20\JWS\examples\ClockBeans.
There are plenty of wav files at c:\winnt\media\Microsoft office 2000.
Java applets can play sound files using the play method.
Practical Exercise 8a
Set up a project SoundDemo and move one of the au files into the project directory. Run the class
on a computer with a sound card.
Modify the class so that the sound plays when the user clicks an appropriate button.
More Sound
Here is an extended version of the above program which enables you to have a lot more control of
the sound. It does this by declaring the sound file as a named object. The loop() and stop() methods
can then be applied to this sound.
The code also introduces “if” statements (which enable you to make a choice) and the getSource()
method (which enables you to determine which button has been pressed). More on these later.
Although the class does not use it, you could also have the code play(glass) to play the sound once as
in the previous class.
import java.awt.*;
import java.applet.*; //import all (*) imports AudioClip class
import java.awt.event.*;
//To run this you will need to put in some sound files (.au or .wav) into the
//same directory as your project.
//In this case a .wav file is used
Practical Exercise 8b
import java.applet.Applet;
import java.awt.*;
import java.text.DecimalFormat;
//This class demonstrates methods for converting text to numerical values and converting the
// numerical values back to text for printing in paint.
// It also shows different ways of instantiating strings.
Revision
In Introductory Exercise 2 (IntegerDemo) we looked at one technique for painting integer values in
the applet window. This involved concatenating the integer with a string. For example:
We also used the reverse process, converting a string to an integer, in the EventDemo class.
num1 = Integer.parseInt(value1.getText());
num2 = Integer.valueOf(value2.getText()).intValue();
This technique works for any integer type string. For example:
num1 = Integer.parseInt(“12345”);
real1 = Double.valueOf(s3).doubleValue();
To paint a double as a string with full precision (all decimal places) we use, for example:
To paint a double with the required number of decimal places uses the DecimalFormat class. To use
this we must declare a particular decimal format as an object (for example precision2 in the above
class), instantiate it giving it its value and then use it in the paint() method. In the above class the
relevant class lines were:
Practical Exercises 9
Type in, and get the above class going.
Introductory Exercise 10 - Real numbers (and more!)
Introduces
The float and double types together with methods round, sqrt, max and random.
Promoting a number in a binary operation.
Casting using (int) and (double).
import java.applet.Applet;
import java.awt.*;
import java.text.DecimalFormat;
// The basic number information is in the package java.lang which does not have to be imported
// (although decimal formatting is in the text.DecimalFormat class and must be imported.)
// This class illustrates some of the methods and techniques in the Math, Float, Double and
// Integer classes within the java.lang class.
//We can declare and initialise numbers at the same time. Note that a float (which occupies less
//memory space than a double) must be followed by f when initialised.
float f = 2.345f;
double d = 5.678;
double prod, quot;
double e = 1.456E+45;
int i;
DecimalFormat precision2;
Mathematics Methods
To obtain a full listing of standard mathematical methods that are available in all classes look at the
API help under java.lang.Math. Note that methods of the same name may be defined for different
types (int, long, float, double). Some of those used in the above class:
Promoting
Java can only perform binary operations (such as + * - /) on two numbers of the same type. For
example, if you want to multiply an integer by a double, it will first promote the integer to a double
to give a double answer.
For example 4 * 3.1 is converted to 4.0 * 3.1 to give a final answer of 12.4.
The order of promotion for numbers is: int long float double.
Casting
There are some situations in which you want to convert one number type to another. You can do this
by using a cast such as (int), (double) etc.
1. What are the values (as calculated by Java) of the following expressions. Be careful to indicate
the difference between an integer (int or long) and a real (float or double) answer.
(You will have to look up the API help under java.lang.Math for some of these.)
2. What are the final values of m after the following java statements are executed, if m has an initial
value of 20.
Answers
1 a)10 b)18 c)2 d)10.0 e)2.5 f)2.0 g)25 h)26 i)16 j)16.0 k)7 l)5
m)10 n)3 0)33 p)4 q)7 r)14.4 s)8 t)-4.5 u)8 v)1
2 a)25 b)21 c)19 d)30 e)8 f)2 g)60.0 h)3 i)3.333..
Practical Exercises 10
Sample solutions are provided in Outlook
1. Write a class that lets the user enter two real numbers and prints out their sum, product,
quotient and the maximum value. (Ex10_1_Reals)
2. Write a class that has a counter button: the class counts each time the user presses the button
and prints this out. (Ex10_2_Count)
Introductory Exercise 11 - The if statement
Introduces
The if statement
Brackets around multiple statements.
Equality and relational operators
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
//This class is a modification of the previous addition class, but instead of adding the two
//numbers it compares them with using an if conditional statement.
public class IfDemo extends Applet implements ActionListener
{
Label myPrompt1, myPrompt2; //declare prompts (Labels)
TextField value1, value2; //declare user input (text)
int num1, num2; //integers displayed in text fields
//ActionPerformed is here used simply to get the values of the two integers
public void actionPerformed(ActionEvent e)
{
num1 = Integer.parseInt(value1.getText());
num2 = Integer.parseInt(value2.getText());
repaint();
}
//paint is used to print out the comparison between the two numbers. An alternate
//approach would be to use showStatus in the actionPerformed method.
public void paint (Graphics g)
{
if (num1 > num2)
{
g.drawString("First number is larger.", 25, 150);
g.drawString(“Maximum value is “ + num1, 25, 200);
}
if (num1 == num2) g.drawString("Numbers are equal.", 25, 150);
if (num1 < num2)
{
g.drawString("First number is smaller.", 25, 150);
g.drawString(“Maximum value is “ + num2, 25, 200);
}
}
}
Equality and Relational Operators
Equality operators
== x == y x is equal to y
!= x != y x is not equal to y
Relational operators
> x>y x is greater than y
< x<y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
The if statement
An if statement has one of the general forms:
The boolean expression is any statement that has values true or false. The simplest boolean
expressions use one of the equality or relational operators.
Note that when an if statement is to implement more than one statements, these multiple statements
must be enclosed in { } parentheses. If this is not done only the first of the multiple statements is
controlled by the if statement.
While the position of the parentheses does not matter so far as the class is concerned, you will
frequently line up the final } parenthesis with the preceding if (as is done in the class above).
Practical Exercises 11
From now on the practical exercises get more interesting – and harder! Specimen solutions are
posted in Outlook: you should check these only when you are having trouble.
Your class should have a Text Field for the user to enter the total number of hours worked.
To begin with, you could just initialise the three integers in your class. However, once you have done this you
should provide three text boxes for the user to input the numbers.
This is a classic “ordering” problem and there are many ways of tackling it. Once suggested way is to proceed
as follows:
How to use temp:
Suppose the three values are initially called a, b and c. if (a > b)
If a > b reverse them using a temporary variable called temp {
temp = a;
If b > c reverse them using temp again.
a = b;
If a > b again reverse them using temp. b = temp;
Now a, b and c stand for the values in order and they can be }
printed out.
Proceed as follows:
Use the method above to place the sides of the triangles in order.
If the smallest number is less than or equal to zero, or if the sum of the two smallest is less than the
largest, the numbers do not form a valid triangle.
If all three sides are the same the triangle is equilateral. If two only are the same, the triangle is isoceles.
Once again, your final version of the class should include text fields for the users to type in data.
Introductory Exercise 12 - if else statements
Introduces
if ..else statements
the getSource() method of the event class (in Programming Exercise 3)
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
//User enters values from 0 ..49 and class counts values in ranges 0..9, 10..19 etc.
value.addActionListener(this);
}
//Class tests if values are between 0..9, then 10..19 etc to 40..49 and maintains
//a tally of each the total number of entries within each range.
public void actionPerformed (ActionEvent e)
{
number = Integer.parseInt(value.getText());
if (number < 10) zeros = zeros + 1;
else
if (number < 20) tens = tens + 1;
else
if (number < 30) twenties = twenties + 1;
else
if (number < 40) thirties = thirties + 1;
else forties = forties + 1;
value.setText(""); //Clear the text box
repaint();
}
1. If there is only one desired true condition, using an if .. else statement makes the class more efficient
because those conditions after the first true condition are not tested.
2. Because the class exits from an if .. else statement as soon as there is a true condition, you can use what
would otherwise be overlapping conditions. For example in the above class, if number was 25 the if .. else
statement would exit on the third condition (number < 30) even though the remaining conditions (number
< 40 and number < 50) were true.
Programming exercises 12
(As before, sample solutions for these exercises are available on Outlook.)
Draw a histogram of the data: this will be a series of rectangles of height proportional to the value of
zeros, ones …forties. To get a decent scale, you will need to multiply the zeros, ones etc values by a
constant scale factor which might be something like 20 (so that the height of each rectangle is 20 * <the
value of zeros, ones etc> pixels.
Finally, once you have counted up the total number of votes for each person you will have to work out
which of these is the largest. You should use the techniques of the previous Introductory Exercise 10 to do
this. Print out the names of all the people who have the largest vote (you may get more than one with the
top vote).
Once again, you will need to use the getSource to determine which button was pressed.
Introductory Exercise 13 The for loop
Introduces
The for loop in its simplest form
import java.applet.Applet;
import java.awt.*;
As we will see later, the for loop can contain quite complex control expressions that do a lot more
than simply count.
Programming exercises 13
13.4 Ask the user to input a whole number between 1 and say 50. The class prints out a line of this
number of stars.
Exercise 14 Variables in Java
Variables are spaces in computer memory which store things such as numbers and characters.
Variable types
The variable types available in JAVA include (among others):
Variable names
Variable names can contain letters and digits, and (by convention) start with a lower case letter.
Some valid names are:
When you declare a variable you tell the class what type it is and give it a name. This sets aside
memory space in which to store the variable.
Here are some examples of declaring one or more variables of different types. Note that you can
assign values to variables when you declare them. If you do not assign a value the variable is given a
default value.
int n, m, p = 15;
boolean isTooBig, isTooSmall, prime = true;
char character1, character2 = ‘k’;
double p, q = 3.5E25;
float x, y = 45.78 f; Note that the symbol “f” must follow a float initialisation.
A global declaration (immediately after the main class definition) means that all the “methods” of
the class can use these variables and their values. If it is not initialised (or “assigned” a value) a
global variable a default value. The default values are 0 for int and long, 0.0 for float and double and
false for boolean.
If you only intend to use a particular variable within one method or one for loop, it is best to declare
it locally within that method or loop. This avoids cluttering up the main program. However, note
that:
Locally declared variables must be initialised before using.
If the same variable name is used both globally and locally, the local meaning takes
precedence within that block. We will look at this more when we discuss “methods”.
For example:
<import statements>
public class ScopeDemo extends Applet
{
int n, m; //global declaration of n and m
Number types
public void paint (Graphics g)
{ //g is a local parameter to paint()
int m, p; //local declaration of m, p
for (q = 1; q < 10; q++) //local declaration of q
p = m + 5; //the local version of m is used
The order of promotion for numbers is: int long float double.
Casting
There are some situations in which you want to convert one number type to another. You can do this
by using a cast such as (int), (double), (long) etc. For example
(int) 45.6 is equal to 45
(double) 33/7 converts 33 to a double, so that the result is 4.71…
(double) (33/7) performs the integer division 33/7 which has result 4, and then converts this to
the double 4.0.
(float) (2.2*3.3) converts the result of the operation 2.2*3.3 (which is double) to float.
Mathematics Methods
To obtain a full listing of standard mathematical methods that are available in all classes look at the
API help under java.lang.Math. The java.lang library is always loaded into an Applet so you do not
have to import the classes in this library in your programs.
Note that methods of the same name may be defined for different types (int, long, float, double).
Some of those used in the above class:
Math.round(float / double) rounds to the nearest integer
Math.sqrt(double) square root
Math.max(int, int) etc the maximum value of the two (for all types)
Math.random() a random double from 0 to 1.0
Writing the integer values to the applet window
The paint() method can use a line such as:
to write out the value of the variable. Note that to use drawString in this manner you must precede
the integer by a string.
If you do not wish to precede the number by text, you can either precede the number with a null
string “” in the drawString statement or use one of the methods which convert numbers to strings.
You will find these methods in the java API help under java.lang.Double, java.lang.Integer and so
on. Examples are:
g.drawString(“” + num, 25,60);
g.drawString(Double.toString(34.6), 25, 50);
g.drawString(Integer.toString(57), 25, 60);
g.drawstring(Long.toString(longNumber), 25, 60);
You might be wondering why these last few methods refer to, for example, “Integer” instead of int.
The reason is that there is a difference between objects of type Integer and variables of type int.
While the details of this are beyond this course, we will discuss this later on.
intNumber = Integer.valueOf(input.getText()).intValue();
floatNumber = Float.valueOf(input.getText()).floatValue();
doubleNumber = Double.valueOf(input.getText()).doubleValue();
IntNumber = Integer.parseInt(input.getText());
bool1 = false;
bool2 = 4 < 5; //the boolean expression (4 < 5) is true, so bool1 is true
bool3 = 4 < 5 && x < 23;
The standard comparison operators operate on numbers and some other simple variables to give a
boolean expression:
== equals
!= does not equal
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
The boolean operators operate on boolean expressions to give a result which is boolean.
Logical AND is &&
Logical OR is ||.
NOT is !
Exclusive OR is ^. (we won’t use this one in tests!)
Expressions are evaluated from left to right and stop evaluating as soon as the result is known. Eg if
((x == 45) && (y < 56)), when x is not equal to 45 the first expression is false so that the whole
expression will be false. Because of this, the second expression (y < 56) is not evaluated.
Note that Java also provides versions of AND & and OR | which allow the program to evaluate the
whole of a long expression. Programs using these will run more slowly and may have some
unexpected results in some cases.
Order of precedence including comparison operators
() brackets
++ -- (<type>) ! unary increment and decrement, cast: also includes unary + and -
*/% product, quotient and modulus
+- binary addition and subtraction
< <= > >= comparison operators
== != test of equality or inequality
&& logical AND
|| logical OR
= += -= *= /= %= assignment operators
In each case, operations of a similar precedence are evaluated from left to right.
Declaring a character:
Operations on characters
The basic comparison operators apply to characters, and compare their numeric values in Unicode.
For example in the ASCII and Unicode character sets, ‘a’ has numeric value 97 and ‘A’ has value 65,
so that
‘a’ > ‘A’.
To print a character to screen you can use methods similar to those used with numbers. For example:
When you type into a TextField, you generate an object of type String. If you want to actually read in
variables of type char you can convert the (first letter of) the String to a character using the String
method charAt(<position of character in string>). The first position in a string of characters is
numbered zero (0).
For example, to get a character char1 from a TextField charInput you would write:
char1 = charInput.getText().charAt(0);
Character methods
As with Double, Integer and so on, Character objects are part of the java.lang package and have a
number of useful methods. While you should look these up in the Java API help, some of the useful
Character methods (applied to a variable char1 of type char) include:
Methods with a Boolean output:
Character.isDigit (char1)
Character.isLetter (char1)
Character.isLowerCase (char1)
Character.isUpperCase (char1)
Character.isLetterOrDigit(char1)
Character.isSpace (char1)
Character.isWhiteSpace (char1) //”white spaces” include space, tab, new line
3. If p = 4, q = 6 and r = 8, what is the value of the following expressions. Indicate any syntax
errors.
4. Write out Java type statements which are true under the following conditions:
x lies between 10 and 20
x does not lie between 10 and 20.
5. If ch1 = ‘a’, ch2 = ‘A’ and ch3 ‘ ‘ (space) what is the value of the following expressions:
Once the user finishes with the Applet two more key methods are called. These methods can be
modified by the programmer for more advanced purposes, but we will never do this in this course.
The methods are
stop() which basically stops the Applet running and
destroy() which removes all features of the Applet from memory.
Other standard methods that you have used are the various event handling methods. How to use these
is described in the notes on events. They include:
public void actionPerformed(ActionEvent e) {}
public void mousePressed (MouseEvent e) {}
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
public void mouseDragged (MouseEvent e) {}
public void mouseMoved (MouseEvent e) {}.
More on paint()
The paint() method is executed
Once, immediately after init/start.
Whenever the applet window is redrawn, for example when you change windows.
When called from actionPerformed (which doesn’t have access to graphics) using repaint().
repaint()
clears applet windows of graphics (but not the GUI components which sit on top of the output
window).
calls paint.
What do you code in paint() and in the various event methods?
Some rules of thumb are:
If it uses the Graphics object g it can only be executed in paint.
However, note that g can be used in other methods which are called in paint() – see later.
If it uses the Event object e it can only be executed in actionPerformed.
However, note that e can be used in other methods which are called in actionPerformed and the
other event handling methods – see later.
Other statements might be in either method. Try to carry out calculations etc in actionPerformed
unless this requires a lot of information being passed to paint.
If there is a lot of work to do in either paint() or actionPerformed(), you would normally split it
up into smaller methods. This is described in the next section.
Exercise 16 Writing your own methods
Methods with no input or output
In the following example, “Hello()” is a method which has no input and which does not change any
object or variable in the class so that it can be regarded as having no output. Note that the parameter
brackets () are necessary to indicate that it is a method.
The word void will make more sense later: it means that the method does not generate a new value.
Whenever you want to use a method you call or invoke it from another method such as paint().
import java.applet.Applet;
import java.awt.*;
import java.applet.Applet;
import java.awt.*;
import java.applet.Applet;
import java.awt.*;
Method with input parameter and output which changes the input value
In this example, the method alters both the properties of an object within the class and also modifies
the data within supplied to it in the parameter.
import java.applet.Applet;
import java.awt.*;
TextField t;
import java.applet.Applet;
import java.awt.*;
The word return specifies the value that the method generates.
import java.applet.Applet;
import java.awt.*;
import java.applet.Applet;
import java.awt.*;
import java.applet.Applet;
import java.awt.*;
The general form of a method definition is as follows. The first line is called the heading.
Nearly all methods that The type or class that the Use normal Java If no formal parameters
you will use start with method returns (int, identifier rules. use ().
the word “public”. Other TextField etc). If the Begin with lower More than one formal
words are “private” and method does not return a case letter. parameter separated by
“protected”. value use the word void. comma.
If the method was defined in the same class in which it is called, you simply call it using the
name of the method. init(), paint(), start(), destroy() and stop() are automatically defined in each
new class and so can be called directly by name in this way. Any method that you write in a class
(such as in the simple examples above) is also called in this way.
If the method is defined in another class (such as most of the standard Java methods that you will
use), you must identify the class which defines the method. There are three different ways of
doing this, and which one is appropriate depends on how the method was originally defined. (See
discussion of “instance” and “static” methods in the next section.)
If the method is other than void, it returns a new value which is used in an expression just like any
other value. For example:
g.drawString("The square of " + 9 + " = " +(square(9)), 25, 50); //from above
examples
y = Math.max(23, 45);
Return Return has two uses:
1. To cause the current method to end. In the following example if b == -1 the method exits without
printing out the value of b.
There are two ways in which you can use the value returned by a method:
You might use the new object or datatype (for example to print it) and then discard it from
memory. As an example, to print out the value of an integer you might use:
g.drawString(Integer.toString(456), 25, 50);
If you want to keep the new object or primitive type in memory you must have declared it. As
an example, you can keep the string value of an integer if you write:
string1 = Integer.toString(456);
Examples of methods that do not have a return include many of the graphics methods such as
SetColor, drawRect, drawString.
Scope Rules
A block is any section of a class enclosed in { } brackets. Blocks can include:
A class (application or applet)
A method.
A section of a for loop or a conditional statement etc.
2. After a method heading: These are variables that have a scope that is local to the method: they
are not defined outside the method. Any variables that are used only in the method should be
made local. As an example:
public int rand(int max)
{ //max is a formal parameter
int x = (int)(1 + Math.random()*max); //x is a local variable
return x;
}
3. In the method heading (parameters): These formal parameters are only defined within the
method – that is they are local variables in the method. However, they provide a link to the
actual parameters used in the class. In the above example max is a formal parameter local to the
rand method.
4. Variables defined in blocks (such as for loops): These are only defined within that block. An
examples is:
for (int i; i < 10; i++)
Parameters
Formal and Actual parameters
The formal parameters are the identifiers used in the definition of the method.
The actual parameters are the values used in the method call. These might be literal values or
instance variables that have been given a value.
In a method call the actual parameters must exactly match the formal parameters in number and in
type. The only exception to this is if the type of one of the actual parameters can be promoted to the
type of the formal parameter. We say that the actual parameters are passed to the formal parameters.
The following example shows a method definition heading, and how this method might be called
from another method:
//Method definition
public double methodExample(int a, int b, double x, boolean t)
{
statements;
}
//Method call (in another method such as paint() or a method made up by the programmer etc)
//In the following examples, val1 and val2 are both int variables, doub1 is a double and b is a //boolean. All of
these variables must have a value before the method is called.
Class variables (TextField, Button, Label …) are passed “Call-By-Reference”: the original object
is referred to and its values may be changed by the method. We say that the formal parameter is
an alias for the actual parameter (another name for the same object).
The following class is a simple example of this. The method tryToChange has an int and a TextField
parameter. It sets new values for each of these parameters. When it is called, the int value is not
changed outside the method, while the TextField value is changed.
import java.applet.Applet;
import java.awt.*;
Method Overloading
Sometimes we want to be able to do similar things to different types or objects. In this case, Java
enables methods that are different (because their parameters are different) to have the same name.
There are many examples of this, and a very small selection is:
toString(<type>): the type can be int, double, and many more (including both types and objects).
Math.max(<type, type>): the types can be (both) int, double etc
The following example shows how a new method max can be defined to give the maximum value of
3 integers or 4 integers or three doubles. Which version of max is called depends on the number and
the type of parameters in the call.
Modularising Graphics
Often it is convenient to break up a graphics method into smaller methods, particularly if there are
repetitive tasks to undertake.
The following class shows how this can be done. A menu is located in a menu method, while the
method thickline enables repeated drawing of a thick line. Note that the Graphics objects in the
various methods can be given a formal parameter which is any valid identifier.
import java.applet.Applet;
import java.awt.*;
public void thickLine(Graphics graph, int x1, int y1, int x2, int y2, int thickness)
{
for (int i = 0; i <= thickness; i++)
graph.drawLine(x1+i, y1, x2+i, y2);
}
Static methods: Methods preceded by the class name (when called outside the class in which they
are defined) are called Static Methods (GREEN dot in the JWS API help). They operate on the
class as a whole. For example:
Sometimes the same name can be given to two different methods one of which is static and the other
an instance method. The toString methods provide an example.
Static variables: (BLUE in JWS help) Examples are Math.PI and Math.E, or Color.red and
Color.blue. These are essentially constants that apply to every object in the class. A variable is made
“static” by including the word static at the beginning of it’s declaration. For example:
int2 = Integer.valueOf(s2).intValue();
Why are there two apparent attempts at getting the integer value of the string s2?
If you look up valueOf in the Integer class you will see that it returns an Integer Object. This integer
object contains the integer as its data, but it also contains other information: it is not the same as the
primitive data type int. To get the actual value we have to add on the method intValue() which
applies to an Integer Object and returns a primitive type int which corresponds to the data of the
Integer object.
In this case we say that the Object Integer “wraps” the data type int.
Constructors: (YELLOW dot in JWS help). A constructor is a special kind of method which is
called when an object is created. It is used to give an initial value to the data stored in the object. For
example, if you use the code:
s1 = new String(“Hello”);
you are actually calling one of the String constructors. You will not be required to write constructors,
but you should understand their use in the Java help.
Interfaces are similar in many ways to classes. The differences are beyond the scope of this course.
Programming exercises 16
1. Areas
Here are the formulae for the areas of a number of different shapes in terms of their basic dimension
(radius, side length etc).
Square: area = (side length)2
Circle: area = PI* radius2
Hexagon: area = 1.5*3 * r2
Equilateral triangle: area = 0.25 *3 * r2
Your program should call the above procedures as appropriate from the actionPerformed() method,
and as always print out the area from the paint() method.
horizontal and vertical dashed lines. These two methods should include parameters for
the graphics object g
the starting coordinates of the line
the length of the line in pixels
the length of the dashes in pixels.
horizontal and vertical thick lines. These two methods should include parameters for
the graphics object g
the starting coordinates of the line
the length of the line in pixels
the width of the line in pixels.
rectangles and ovals with thick sides. These two methods should include parameters for
the graphics object g
the top left coordinates
the width
the the height
the thickness of the sides in pixels
Using these methods and if necessary other methods (such as thick or dashed lines inclined at 45)
draw up a nice picture on the screen. Add colors to your picture. The picture could be:
This is an assignment due before the end of May. The completed code should be emailed to
your teacher with the subject “RPS”.
In the game rock, paper, scissors the two players each choose one of the three. The winner is then
decided by the rules:
Paper covers rock, paper wins.
Scissors cut paper, scissor wins.
Rock breaks scissors, rock wins.
All matching combinations are ties.
Write a program to simulate the game, with the user playing the computer. As well as paint() and
actionEvent, your program should include procedures for:
Allowing the computer to make a choice of rock, paper or scissors. This will involve a
procedure which has no parameters, but which returns a value (perhaps int or char) which
corresponds to rock, paper or scissors.
Allowing the user to make a choice of rock, paper or scissors. The use of buttons or a list
would be most appropriate. The method returns a value which corresponds to rock, paper or
scissors similar to that produced by the previous method.
Deciding the winner in each round of the game and tallying up the total score (wins, ties and
losses).
An interesting version of the game will have appropriate images and sounds, including a suitable
reward if the user wins.
Introductory exercises in Methods
3. Answer the questions for the class given, which is a variation of the previous class:
6. Here are some programs which look similar. What is the output of each? Explain.
import java.applet.Applet; import java.applet.Applet;
import java.awt.*; import java.awt.*;
public class int1 extends Applet { public class int2 extends Applet {
int a, b, c; int a, b, c;
public void intMethod (int p, int q, public void intMethod () {
int r) { a = 2;
p = 2; b = 3;
q = 3; c = 4;}
r = 4;} public void paint (Graphics g) {
public void paint (Graphics g) { intMethod();
intMethod(a,b,c); g.drawString("" + a, 20, 40);
g.drawString("" + a, 20, 40); g.drawString("" + b, 20, 60);
g.drawString("" + b, 20, 60); g.drawString("" + c, 20, 80);
g.drawString("" + c, 20, 80); }
} }
}
(Answers: int1: 0, 0, 0; int2: 2, 3, 4;)
An event is an action performed by the user which gives information to the class. GUI components
are often used to generate events. Events can include things such as
Clicking a Button or one of the other components such as a List, CheckBox etc.
Pressing <return> with the mouse cursor in a Text Field.
Clicking or moving a mouse.
2. Tell the class which events to listen to (there might be a number of possible events):
addButton.addActionListener(this);
In this case, we are telling the class to listen to the GUI component that we have named
“addButton”. The word this tells the class that “this” class is doing the listening (it is possible to
listen to events in other classes).
1. To tell which specific component generated the event, you name components in code such as
the following:
An example of the use of this were the voting and calculator programs of Introductory Exercise 12.
2. To tell what type of component (TextField, Button etc) generated an event, you can use the
instanceOf comparison operator as in the following example:
Other interfaces
As well as ActionEvent there are many other “interfaces” which control the response of the applet to
the events generated by various types of components or by the mouse or keyboard. Some of these are
considered (in a very introductory way) in the remainder of these notes.
Some other components that generate Events
So far you have used Button and Text Field objects to generate action events. There are many other
components which will also generate events and while you will not be examined on all of these, you
should become familiar with how to use them in your own programs.
The following pages give examples of programming some of these components, without further
explanation. You can copy these into Java Workshop in order to try them out. You should be able to
write similar programs yourself.
Lists (use ActionEvent interface)
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* A simple demonstration of the List component. The user clicks on a list of colours, which sets
the background color. */
public class ListDemo extends Applet implements ActionListener
{
List colorList; //declare a list
Label prompt;
switch (colorList.getSelectedIndex())
{
case 0: setBackground(Color.red); break;
case 1: setBackground(Color.blue); break;
case 2: setBackground(Color.green);break;
case 3: setBackground(Color.yellow); break;
case 4: setBackground(Color.cyan);
}
repaint()
}
}
Checkboxes (use ItemListener interface)
A checkbox allows the user to choose between two options one of which is “true” and the other
“false”. In the following example the choices are milk / no milk, sugar / no sugar, strong / not strong.
Code that you have not used before is in bold.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* A class to demonstrate Checkboxes. The user uses the Checkbox to determine how he likes
his coffee. Checkboxes use the ItemListener interface. */
//In each case the getState method is TRUE if the Checkbox has been
//ticked and FALSE otherwise.
if (strong.getState())
order = order + "strong coffee ";
else order = order + "weak coffee ";
if (milk.getState())
order = order + " with milk";
else order = order + " no milk";
if (sugar.getState())
order = order + " and with sugar";
else order = order + " and no sugar";
repaint();
}
Radio Buttons (use ItemListener interface)
Radio buttons are a variation of the Checkbox: however, only one radio button can be ticked as true
at any time.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
CheckboxGroup votes;
Checkbox jim, joe, sue, sal;
String winner;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
It uses the method keyTyped to get the value of a “normal” letter or digit key.
It also uses the method keyPressed to identify which key has been pressed, and includes the “action
keys” such as the function and arrow keys, Home, Page Up etc. In the window are printed the value
of the letter or digit key if one of these has been pressed, and the name of the key that has been
pressed.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/*Each of the following three methods must be declared whether or not they are used.*/
/*keyPressed responds to pressing anY key on the keyboard, including the "action keys", which
include arrow and function keys, Home, End, Page Up, Page Down, Num Lock etc */
public void keyPressed (KeyEvent e) {
sr = e.getKeyText (e.getKeyCode()); //return a string describing the key
ch = ' '; //a convenient value if a character key is not pressed.
repaint();
}
}
Mouse events: MouseListener interface
A very important class of events are those events generated by the computer mouse. These actually
use the MouseListener interface.
The following program is about the shortest program you can write using a MouseListener. It simply
tells you the coordinates of the cursor in the Applet window, and is available under the Outlook
public folders.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
//The other interface methods used by MouseListener must be defined, even if they are not
used.
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
You can add the following lines to the previous program to make use of these other methods:
String event; //Declare a string which is used to indicate the type of event
{
x = e.getX();
y = e.getY();
event = "Pressed";
repaint();
}
x = e.getX();
y = e.getY();
event = "clicked";
repaint();
}
//Indicate position of mouse and whether mouse has been pressed, clicked or released
public void paint (Graphics g) {
g.drawString("Mouse "+event+" at (" + x + ", " + y + ")",x,y);
}
}
Here is the code that you can add to the previous program to listen to mouse movements:
mouseMoved and mouseDragged enable you to draw in the Applet window using the mouse. To do
this you need to use the “update” method using the code:
Normally, when repaint() is called it completely clears the screen of all previous graphics and paints
the new information onto the resulting clean screen. If you use the update method, repaint() leaves
previous graphics on the screen. Hence, if you are drawing a line using the mouse the Applet window
will remember the previous lines drawn on the screen.
The following code (added to the previous code) allows you to draw a series of circles in the window
which follow the motion of the mouse. The distance between successive circles depends on how fast
the mouse is moving, and on how frequently the particular computer can call the repaint() method.
To draw a continuous line, you can use the following paint method (along with the previous code):
public void paint (Graphics g)
{
g.drawLine(oldX, oldY, newX, newY);
}
Here:
newX and newY give the current x and y coordinates of the mouse (as obtained using the
method getX(), getY() in mousePressed.
oldX and oldY give the previous x and y coordinates: the program draws short lines from the
old to the new coordinates.
Practical exercises
1. Complete all of the programs suggested above. To remind you these are:
1. Print out the position of the mouse (Mouse1) as in the first complete example.
2. Print out the mouse events in mouseListener
3. Print out the mouse events in mouseListener and mouseMotionListener
4. Draw a series of circles which follow the movement of the mouse
5. Draw a continuous line which follows the movement of the mouse.
These are all available for your checking in outlook under the Mouse folder, with names Mouse1,
Mouse2, Mouse3, Mouse4 and Mouse5.
2. Write a program which will let the user draw a series of connected straight lines in the Applet
window. You will need to use mouseListener, and you will need to store the previous x and y values.
The sample solution is the program “Lines” in Outlook.
3. Write a program which draws a line from the current position of the dragged mouse to a suitable
fixed origin near the bottom left of the screen. This line represents a vector of the type you may have
found in maths and science. At the head of the vector, print out the angle it makes with the
horizontal. You will need to use mouseMotionListener and you will also need to use Math.PI and
Math.atan(angle in radians).
The maths is as follows, where origX and origY are the coordinates of the origin – but try to work it
out yourself before you use the answer. In this maths the angle is in degrees and the length is in
pixels.
angle = Math.atan((double)(origY - y)/(x - origX))*180/Math.PI;
length = Math.sqrt((origY - y)*(origY - y) + (x - origX)*(x - origX));
This is what a small section of the Applet window might look like
You will be using this technique later on when you write some games programs in which you wish to
launch a ball / missile / billiard ball etc at a target.
Exercise 18 Java Notes: Control Structures
Conditional statements
If statement:
If (<boolean expression>) <statement>
Simple examples:
if (x < 5) g.drawString(“hello”, 20, 40);
if ((x < 5) && (y > 23)) g.drawString(“hello”, 20, 40);
if (x == 4) num = 45 + x;
if (doAgain) repaint(); //doAgain must be a boolean variable
if (e.getSource() == input) count++;
Compound if statement
If you want more than one statement to be executed when the “if” condition is true, you must bracket
them in braces {}, otherwise only the first statement will be executed.
Syntax
if (<Boolean expression>) {
Statement1;
Statement2;
<More statements>;
}
Nested if statements
Conditional statements can be nested. For example:
if (<Boolean 1>)
if (<Boolean 2>)
if (<Boolean 3>)
<statement>;
is equivalent to:
if (<Boolean 1> && <Boolean 2> && <Boolean 3>)
<statement>;
if .. else statements
Syntax:
if (<Boolean 1>) <statement1>;
else if (<Boolean 2>) <statement2>;
else if (<Boolean 3>) <statement3>;
…..
else <final statement>; //optional last line
There is a big difference between the two sections of code in the following example:
The first section of code has three separate if statements which are all tested separately. For
example, if marks was equal to 45 the code would print out “Pass”, “Credit” and “Great” – not the
intention. The second section of code contains one if statement and the program leaves the statement
after the first true condition. For example, if “marks” was equal to 45 it would print out “Pass” and
then exit the statement.
The “dangling” else
General rule:
Here is an attempt at a program which is supposed to write out “Pass” if the marks are between 50
and 60 and “Fail” if they are below 50:
In this case, the else goes with the preceding “if (marks < 60)” so in spite of the way that the program
is written, the computer actually interprets it like this:
In this case, there is no print out for the case when marks are less than 50, and “Fail” is printed out
for those students who get more than 60 marks. The problem is referred to as a ”dangling else”
problem.
Switch statements
Switch statements provide a convenient shorthand for a series of if statements in which each
statement tests if a variable has one particular value.
Basic syntax:
Switch (<expression>)
{
case <expression value> : <statements>;Can be more than one, without braces
case <different value> : <statements>;
..
..
case <different value> : <statements>;
}
Some things to know about switch statements:
1. Because each case tests for an equality, you cannot use real numbers in the case expression. In
the same way, you can't put comparisons in the case label.
2. You cannot duplicate the case condition.
3. Unlike a series of if..else conditions, a switch statement executes every case condition after the
first true case condition unless you tell it to jump out of the loop using the break command.
4. You can include more than one value in each case label, using the following syntax:
case <value1>: case <value2>: case <value3>: <statement>;
5. You can insert a default at the end of the list of case labels which is executed if it is reached,
using the syntax:
default: <statement>;
An example:
Switch (dayOfWeek)
{
case 1: case 7:
g.drawString("Weekend", 20, 40);
rate = 2; break;
case 2: g.drawString("Monday", 20, 60); break;
case 3: g.drawString("Tuesday", 20, 60); break;
case 4: g.drawString("Wednesday", 20, 60); break;
case 5: g.drawString("Thursday", 20, 60); //break omitted
case 6: g.drawString("Friday", 20, 60); //break omitted
default: g.drawString("Number out of range", 20, 60);
}
In this case, the if the day falls on a weekend, the program sets the rate (of pay presumably) to 2 and
breaks out of the switch statement. If it is a then continues on to the correct day. It will only reach the
default if the number entered is out of the weekday range, and in this case it will print out an error
message. Because there is no “break” with cases 5 and 6 (as their should be) if it gets to case 5 and
case 5 is true, it will continue to execute case 6 and the default regardless of whether case 6 is true or
not.
Programming exercises 18
(See also the simple programming exercises you have already done in Introductory Exercises 11 and
12.)
1. Set up a TextField in an Applet window into which the user types single characters. Maintain
a tally of the letters, digits and spaces which you print out in the window.
2. Extend the previous exercise to include a tally of upper case letters and lower case letters.
This will probably involve some nested if statements.
Write a class which has inputs for the employee category and the hours worked. The program
evaluates the salary of each employee for the week and also tallies up the total salary bill for
the week.
Your program should:
Accept ‘a’, ‘A’, ‘b’, ’B’, ‘c’, ‘C’ as valid inputs to the character category.
Print out a warning message for any other input.
Theoretical exercises 18
In the following examples you may assume that all variables have been correctly declared as having
the appropriate type, including boolean type.
1. What are the output of the following code? How would you fix it?
if (gender == 1)
showStatus(“Woman”);
else;
showStatus(“man”);
2. What is the output of the following code if age = 70 and if age = 50? How would you fix the code
to print out pension if and only if the age is greater than or equal to 65?
if (age >= 65);
showStatus (“Pension”);
4. What is a more efficient (ie uses less logic operators) way of stating the boolean conditions in the
following statements. Your studies of logic might help you here!
(a) if (!(x < 19) && !(y > 3)) < statements>;
(b) if (!(x < 19) || !(y > 3)) < statements);
(c) if ((x > 20 && y > 3) || (x > 20 && y < 0)) <statements>
(d) if (!(x >=20) && (!(x <= 10)) <statements>
5. Find the mistakes in the following code, assuming that months 5 to 10 are cold, the other
months (1 to 4 and 11 to 12) are warm and months 9, 10 and 11 are spring. You don’t have to
worry about situations that are not covered by the code.
6. Walter J. Nerd needs a computer to tell him what to do. His plans are that:
a. If the temperature is below 15 and it is raining he will stay at home and play computer
games. However, this will damage some of his neurons.
b. If the temperature is above 30 he will go to a nice air conditioned computer shop and buy
some more computer games. However, this will reduce his bank balance.
c. Otherwise he will go to the house of his friend Wallace W. Squareyes and play computer
games, as well as drinking all of Wallace’s cola.
Here is his attempt at programming the computer to tell him what to do:
if (temp < 15)
if (raining)
{
g.drawString(“Stay at home”, 20, 20);
neurons--;
}
else if (temp > 30)
{
g.drawString(“Go to shop”, 20, 40);
balance --;
}
else
g.drawString(“Go to Wallace”, 20, 40);
g.drawString(“Drink Wallies’ cola”, 20, 60);
How would you fix up the program to do what Walter wants? Try it (the program, not the
lifestyle)!
7. Find the mistakes in the following code. There are lots of them!
switch 4*m + 2
{
case 14: num = 1;
case m>3: num = 2;
case 3: case 14: num = 3;
default: num = 5;
case 18; num = 6;
10. Repeat the previous question for the following alternate code:
switch (selectValue)
{
case 0: setBackground(Color.red); break;
case 1: setBackground(Color.blue); break;
case 2: setBackground(Color.green);
case 3: setBackground(Color.yellow);
case 4: setBackground(Color.cyan);break;
default: setBackground(Color.magenta);
}
switch (selectValue)
{
case 0: setBackground(Color.red); break;
case 1: setBackground(Color.blue);
case 2: setBackground(Color.green);break;
case 3: setBackground(Color.yellow);
case 4: setBackground(Color.cyan);break;
default: setBackground(Color.magenta);
}
The for loop
A for loop allows you to repeat a programming sequence until some condition is met. The for loop
can be expressed as:
for (variable declaration ; boolean expression ; control statement)
<statement>;
The simplest type of for loop uses a simple counting variable. Examples are:
If you run this, you will get a final quotient of 17 rather than the expected 16 indicating that the loop
has run 17 times rather than 16. The reason for this is that after 16 runs the value of n is 100 – 16*6 =
4 so that the Boolean is still true and the loop runs once more. The final value of n before the loop
exits will in fact be –2.
Incidentally, the above simple example illustrates a few more points about for loops:
1. The Boolean condition did not involve the counter.
2. The loop used multiple statements which had to be enclosed in braces.
3. We could not print out the value of the loop variable outside the loop. To retain this variable
we had to declare another variable quot which will retain its value outside the loop.
int joe = 0;
for (int n = 1; n <= 10; n++)
{
joe++;
g.drawString(""+joe, 20, 40+10*n);
if (n == 5) break;
}
Continue is used if you want to start the next loop sequence without finishing off the current one.
For example, in the following loop only the values of n which are not divisible by 3 are printed out.
for (int n = 1; n <= 10; n++)
{
if (n%3 == 0) continue;
g.drawString(""+n, 20, 40+10*n);
}
do <statements>
while (<Boolean expression>);
“While” statements are similar to for statements, and in fact a “for” statement can almost always be
written as a “while”.
As an example, the following two sections of code are equivalent:
for (int n = 1; n <= 10; n++) int n = 1;
g.drawString(“”+n, 20,40); while (n <= 10) {
g.drawString(“”+n, 20, 40);
n++;}
A “while” statement checks the Boolean expression first, and if it is false the subsequent statements
do not run. On the other hand, a “do” statement always executes the loop statements once before it
checks the Boolean condition. Program errors or crashes can result if the Boolean was actually false.
As an example, what happens in the following two sections of code?
int num = 100, n = 10; int num = 100, n = 10;
while (n > 0) { do {
quot = num/n; quot = num / n;
n--; n--;
g.drawString(“”+ quot, 20, 40);} g.drawString(“”+ quot, 20, 40);
}while (n > 0);
Because of the greater scope for errors in using do/while loops, it is generally best to avoid them:
stick to using for or while loops whenever you can.
As a point of programming style, you will often use braces with a do statement to emphasise the fact
that the “while” belongs to the previous “do” – even though this is not strictly necessary. For
example, the following two sections of code are equivalent though the second uses a better
programming style:
Note the following difference between the way in which “continue” operates in different types of
loop. (This is a subtle point and will probably not be examined.)
Theoretical exercises
1. How many times do the following loops run:
(a) for (int n = 1; n < 10; n++) <statement>;
(a) How many times does the code run before exiting?
(b) What is the largest value of prod?
(c) What does the drawString method do in this code? Try it!
More Programming exercises
4. Primes
Print out all of the prime numbers less than 6000.
To do this, note that:
A prime number is one that has no divisors except for itself and 1. In other words, when
you divide any number into it there will be a remainder.
To check if a number is prime, you need only check the remainder for integer division by
divisors less than or equal to the square root of the number you are testing.
Some programming considerations
Your program will have to have nested for loops. For each number less than 6000 you
will need to test division by all suitable divisors.
Once you find a divisor for a number there is no point in continuing in that for loop, and
you should break out of the for loop.
You will probably want to declare a boolean which indicates whether or not a number is
prime.
You will need to pay careful attention to your program layout – especially the coordinates
in your g.drawString statements – and you will need to use the Project Manager Edit to
set the size of the Applet window.
5 A graph plot
Write an Applet which plots out any quadratic.
This is a tricky program, but it does illustrate some important programming concepts, particularly
in relation to setting up scales in your Applet windows. You can use these concepts in later
programs to do things like plotting out house plans or projectile trajectories.
Because you are working in pixels, you will need to enter coordinates such as a = 0.002, b = 0.5 and
c = -200 to get a decent plot.
You should also tell the program not to plot any points that lie outside the graph borders. Do this
when you have got everything else going.
Suppose that we want the graph to plot between x = -10 and x = +10, y = -10 and y = +10. Since in
both the x and y directions a range of values of 20 must be scaled up to 600 pixels, we will need to
multiply all of the pixel units by the scale factor of 600/20 = 30.You will also have to adjust the
range of x values in the for statement.
Your program will be much more versatile if you declare variables for all of these numbers,
including variables for the x and y scale factors, and initialise the values of these numbers in init() or
in the declaration section. You could even add TextFields so that the user can alter some of these
values.
Text fields are initially blank, and blank text fields will crash the program. Add a “reset” button
which sets all of the text field values to “0”.
You might also consider adding grid lines or labelling the axes. And why not extend your program to
cover other types of graphs as well?
Exercise 19 Classes and Objects
Summary of terms used in this unit:
Class
A general computer program which carries a “design” or “blueprint” for an object, and so enables a
programmer to create or “instantiate” any number of objects of this class.
Instantiating an object
When you want to use an object in a class you must
Declare the object by giving it’s class and identifier name:
eg Button myButton;
By convention the class name begins with a capital while the object name begins lower case.
Instantiate the object by calling one of the constructor methods for the object with the new
method: classes will often have a number of different constructors which take different
parameters, and you can look up the constructors for different objects in the Java API help.
The constructor method always has the same name as the class, but there may be any number
of parameters.Examples are:
myButton = new Button(“Hello”);
2. Inheritance
A “parent” class can be extended to “child” classes which include more data and methods. In
this way the programmer can set up a hierarchy of classes, without necessarily needing to know
the internal details of parent classes. For example, when you create an applet class you are
extending the Java class Applet, and you do not need to know any details of how the Applet
class was originally set up.
3. Polymorphism
If similar classes have the same method name, whenever that method is called for a particular
object Java “knows” to get the version of the method defined in the appropriate class.
First example – a very simple class
On the opposite page is an example of the use of a user defined class and its objects within a larger
program. The class Olympian allows the main program to use objects which store the name, sex and
country of different Olympian athletes.
This is a very simple program, and you might wonder what the fuss is all about. But be patient – you
will see some more involved programs later.
The Olympian class (This is the user defined class included in the main class Olympic)
Lines 19 onwards:
These lines form the class definition. Notice that by convention the name of a class begins with a
capital letter, while objects belonging to the class begin with a lower case letter.
Line 20
This defines a public variable (or property) of the Olympian class. We can access this directly using
notation such as jim.name.
Lines 21 and 22
These define private variables within the Olympian class. These variables cannot be accessed (by
name) outside the class, though the data contained within them can be accessed by the getSex() and
getCountry() methods of the class.
Lines 24 to 26
Here we define a constructor for the class. This is a public method which is used by the external
program to instantiate a new object of that class. The constructor always has the same name as the
class, though the number of parameters can vary. In this case, the constructor has two parameters
which are used to set sex and country of the object when it is instantiated.
Lines 28 to 32
These specify two public methods which return the data stored in the object. In this particular
example, it seems (and probably is) rather pointless going to all this trouble when we could access
the data by making the variables age and country public rather than private. However, this concept of
data hiding is central to object oriented design, because it protects the raw data from mistakes made
by the outside programmer. In this case the programmer has decided that the variable (property)
name can be made public, whereas sex and country should be hidden.
Lines 28 to 41
These specify public methods for setting the data stored within an object.
Line 4
This declares two objects, jim and joe, of the Olympian class
Lines 6 and 7
This instantiates the objects jim and joe using the new operator and the constructor defined in the
Olympian class. Notice that the constructor method must be called with appropriate parameters
which set the initial values of sex and country.
Lines 8 to 11
These use the setSex(), setCountry() and set Name() methods to change the data stored in the objects.
Lines 12 and 13
These obtain the data from each of the objects using the name property for the public variable and
the getSex() and getCountry() methods for the private variables.
1. import java.applet.Applet;
2. import java.awt.*;
Notice that
all constructors have the same name as the class;
the constructor methods are overloaded by having different sets of parameters.
These constructors are called from the main Olympic class in lines 9, 13 and 16. An example of each
different constructor is provided.
In line 20 note that joe does not have a country when the getCountry() method is called. When Java
is asked to provide non-existent object data it returns the default value which is “null” in the case of
a String and “0” in the case of a number.
1. import java.applet.Applet;
2. import java.awt.*;
3.
4. public class Olympic2 extends Applet {
5.
6. Olympian jim, joe, jill;
7.
8. public void init(){
9. jim = new Olympian();
10. jim.setName("Jim Spriggs");
11. jim.setSex('M');
12. joe = new Olympian('M', "NZ");
13. joe.setName("Joe Bloggs");
14. joe.setCountry("Germ");
15. jill = new Olympian("Jill Hill", 'F', "France");
16. }
17.
18. public void paint(Graphics g) {
19. g.drawString(jim.name + " " + jim.getCountry() + " " + jim.getSex(), 20, 40);
20. g.drawString(joe.name + " " + joe.getCountry() + " " + joe.getSex(), 20, 60);
21. g.drawString(jill.name + " " + jill.getCountry() + " " + jill.getSex(), 20, 80);
22.
23. }
24. }
25.
26. class Olympian {
27. public String name;
28. private char sex;
29. private String country;
30.
31. public Olympian (){}
32.
33. public Olympian (char s, String c) {
34. sex = s;
35. country = c;}
36.
37. public Olympian (String n, char s, String c){
38. name = n;
39. sex = s;
40. country = c;}
41.
42. public char getSex() {
43. return sex;}
44.
45. public String getCountry() {
46. return country;}
47.
48. public void setSex(char s) {
49. sex = s;}
50.
51. public void setCountry(String c) {
52. country = c;}
53.
54. public void setName(String n){
55. name = n;}
56. }
Super
You may remember that the Java word this refers to the current object. Similarly the word super
means the superclass of the current object.
A class often needs to invoke a method from its immediate superclass or one of the classes further up
the inheritance tree. The methods in all classes up the inheritance tree are freely available (provided
that they are labelled as public or protected). The only problem that can arise is when the desired
method in the superclass has the same name as a method in the current class. The solution is for the
subclass to prefix the method name required with the word super.
In the following example the current class has a method called calculate, and within that class is a
call to another method called calculate from its super class.
Inheritance
One of the very important features of object oriented design is inheritance, the ability of one class to
inherit important features of another class without the need to repeat the code of the “parent” class.
Inheritance is accomplished using “extends”.
The code opposite shows three classes which inherit from the Olympian class. In each case note that:
Since the name of the constructor must be the same as the name of the class, the constructors
are not inherited from the parent class and must be defined in each child class. It also follows
that if the constructors use private variables, these must be redefined.
Public methods defined in a parent class are passed on to the child class.
Class Track is a child of the class Olympian and stores the additional data distance and time, and
defines the methods for setting and getting this data. Since the constructors variously take time,
distance and country as parameters, these must all be redefined in the class. However, sex is inherited
from Olympian as are all of the other methods of Olympian.
Class Water is a child of the class Track, and stores the addition data stroke, as well as the
appropriate methods for setting and getting this data. Since sex and country are used in the
constructors, they must be redefined in this class.
Class Team is a child of the class Olympian and stores the additional data game, as well as
appropriate methods for this data. Since game is the only parameter in the constructors, the inherited
data sex and country do not have to be defined in this class.
Note that if we never intend to use the parent class Olympian in the program, using instead its child
classes, it is not necessary to define constructors for the Olympian class.
The relationships between the classes can be represented in a class hierarchy as shown:
Olympian
Track Team
Water
Exercises 19
Devise a class for gymnasts which holds the usual information about name, sex and country
and also adds sport information.
Devise a Soccer class which stores information on positions played as well as whether the
player is a captain or vice captain.
Where would you put a class to include members of water relay teams? You might end up
with a bit of polymorphism in your methods!
Suppose that you want to store information on all of the members of a soccer team. How
would you set up an array of Soccer objects (corresponding to each of the members of the
team)? Write a method for getting a list of all of their names and their positions, with the
captain and vice captain at the head of the list.
class Track extends Olympian
{
public Team () {}
Suppose we are designing a computer game of “golf” then one of the program objects would be a
golf ball, another could be the holes. Every golf ball created will be an instance of the golf ball
object.
The program will have to display a ball to the screen, move it and let the user know when the ball has
been sunk. Suppose the ball is identified as “sunk” by changing colour.
1. What data variables would you need to associate with the golf ball object to determine its size
and position? Write the code to declare these variables.
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
2. Write the method that will display the golf ball to the screen. Call it drawBall
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
3. Complete the following constructor method for the golf game project
public GolfBall (int initialDiameter, int initialX, int initially) { Note – the
diameter = _______________________ constructor
method must
________________________________
have the same
________________________________ name as the class
________________________________
Classes
As many golf balls are going to be created we need a basic description / plan / blueprint of how to
create a ball. The declaration of the structure of all balls is called a class. A class is a generalization
of an object. Each time a new ball is created we say it is an instance of the class. Below is the code
for the class GolfBall as we have defined is so far.
4. Include the code for an applet called GolfGame that creates one instance of GolfBall.
(Remember to treat it like all other objects so far). Where would this code be written?
class GolfBall
{
int diameter;
int xcoord, ycoord;
4. Write a line of code that will make the golf ball red and note where this code will go in the
above Applet.
5. Write the code that will move the golf depending on where the mouse is clicked as shown
below
Mouse click
position
Golf ball
8. Write the algorithm that will draw the golf course – background colour and holes
9. Write the code to draw the golf course
10. Write an algorithm that will determine when a ball has been sunk and that it will change
colour when sunk
11. Write the Java code to determine when a ball has been sunk. Include a Boolean variable that
will be true when sunk and false otherwise
12. Write the code that make the golf ball red if sunk and yellow otherwise
Summary: GUI objects
To create (instantiate) an object use the constructor with new.
For example, myButton = new Button(“Hello”).
To add an object to the Applet window use add.
For example add (myButton).
To listen to an object (if available) you must
o implement the appropriate interface in the class definition
o tell the class to listen to that object in init()
o use the appropriate method to respond to events.
To control the layout of a GUI object you must include the following code:
setLayout( null); //removes automatic layout
objectName.setBounds(int topleftX, int topleftY, int width, int height);
In the following summaries “name” refers to the name of the appropriate object.
Label
Constructor Label (String s) Values for “alignment” are:
Label (String s, int alignment) Label.LEFT Label.CENTER Lavbel.RIGHT
Implements Not applicable
Other Methods name.getText()
name.setText( String s)
Button
Constructor Button (String s)
Implements ActionListener
Other Methods
TextField
Constructor TextField( int columns)
TextField( String s)
TextField(String s, int columns)
Implements ActionListener
Other Methods name.getText() To onvert text to number types use, eg
name.setText( String s) int m = Integer.valueOf(fieldname.getText()0.intValue();
TextArea
Constructor TextArea (int rows, int columns) scrollbars can have values:
TextArea (String s) SCROLLBARS_BOTH,
TextArea (String s, int rows, int columns) SCROLLBARS_HORIZONTAL_ONLY
TextArea( String s, int rows, int columns, SCROLLBARS_NONE
SCROLLBARS_VERTICAL_ONLY
int scrollbars)
Implements ActionListener Also TextListener
Other Methods name.setText(String s) Many other methods available
name.setEditable(Boolean canEdit)
Choice Buttons (“Drop Down List”)
Constructor Choice()
Implements ItemListener
Other Methods name.add(String item) add is repeated for each item in the drop down list.
name.getSelectedIndex() Returns the index (int) of the selected item.
CheckBoxGroup (“Radio Buttons”) – only ONE button can be selected at any one time
Constructor CheckboxGroup() Constructor for the whole group
Checkbox( String s, s is the String displayed for each button
CheckboxGroup c, c is the name of the group of buttons
boolean state); state is the initial state of each button: if more than
one is set true initially, only the last one remains true.
Note that you must add the group and each Checkbox within
the group
Implements ItemListener
Other Methods
List
Constructor List (int rows, boolean many) rows is the number of rows visible. If there are more rows
these will be accessed by a scroll bar.
many is true if more than one item can be selected at any one
time.
Implements ActionListener
Other Methods name.add(String s) Adds new item to the list
name.getSelectedItem() Returns a String, the name of a single selected item
name.getSelectedItems() Returns a String array of selected items.
Scrollbar
Constructor Scrollbar (int orientation, ScrollBar.VERTICAL or ScrollBar.VERTICAL
int value, Initial value of Scrollbar
int visible, Amount value changes if clicked
int minimum, Minimum value of Scrollbar
int maximum) Maximum value of Scrollbar
Implements AdjustmentListener
Other Methods name.getValue(); Returns value of Scrollbar
Examples of setting up various GUI objects
//Set up myButton
myButton = new Button(" This is a Button "); //create
add(myButton); //add to window
myButton.addActionListener(this); //listen
//Set up myArea
myArea = new TextArea(4,15); //create
add(myArea); //add to window
myArea.insert("This is a TextArea", 12); //add some text to the area
//Set up myText
myText = new TextField(" This is a TextField ");//create
add(myText); //add to window
myText.addActionListener(this); //listen
//Set up List (in this case three items, multiple choices not allowed
myList = new List(3, false); //create
myList.add("First list item"); //add items to the list
myList.add("Second list item");
myList.add("Third list item");
add(myList); //add to window
myList.addActionListener(this); //listen
}
Question 10
Consider the code for an Applet given below. Draw a rough sketch of what you would expect the
output from the Applet to look like on the screen. Be sure that you clearly distinguish between
buttons, labels and textfields.
import java.applet.*;
import java.awt.*;
public class ExamQuestion10 extends Applet
{
Label prompt;
Button buttonA, buttonB, buttonC;
TextField nameText;
public void init()
{
prompt = new Label("Enter your name");
buttonA = new Button("Do something");
buttonB = new Button("Do something else");
buttonC = new Button("Exit");
nameText = new TextField ("Enter your name here");
add(prompt);
add(nameText);
add(buttonC);
add(buttonA);
add(buttonB);
}
public void paint(Graphics g)
{
}
}
Question 11
class Person
{
(a) A student wishes to create Person objects in an Applet. The required objects are:
(b) The student would also like to see if the objects have been correctly created so they decided to
print the first name, surname and gender of each person onto the screen. How could this be
accomplished
from the Applet?
Question 12
The student decided to create some further objects as defined in the hierarchy below.
Person
For the following two questions, a and b, you will need to decide what additional member variables
and member methods would be appropriate to describe the new sub classes.
(a) Write the definition for the sub class Athlete, and then show how Peter Smith, a state champion
high jumper would be created (instantiated).
(b) Write the definition for the sub class Academic, and then show how Peter Jones PhD, a physics
professor could be created (instantiated).
(c) Explain using examples from the above classes, what the role of super and this are in the
construction of classes and sub-classes.
Launceston College 2004 Section D Criterion 7
Question 10
In Java we use constructors to create objects in the Applet window.
Below is more detail on a number of commonly used object constructors.
The diagram opposite contains a number of these objects:
Constructors
1. Button Constructors:
2. Button() creates and empty button
3. Button(String) creates a button with a specific label.
4. myButton.setBounds(int, int, int , int) sets the position of the
Button in the window.
5. myButton.setEnabled(Boolean) sets the Button to enabled or disabled.
6. Choice Box Constructors:
7. Choice() creates an empty multi-choice box.
8. myChoice.add(String) adds the given string as a selection to the myChoice choice list.
9. TextField Constructors
10. TextField() creates a new textfield.
11. TextField(int) creates a new textfield able to hold a specified number of characters.
12. TextField(String) creates a new textfield initialized with a specific text.
13. TextField(String, int) creates a new textfield initialized with a specific text and able to hold a
specified number of characters.
14. All the above Constructors have these methods
15. thisObject.setBounds(int, int, int, int) sets the position of the object in the window.
16. thisObject.setEnabled(boolean) sets the object to enabled or disabled.
17. thisObject.setBackground(int, int,int) sets the red, green, blue colours for the object.
18.
(a) You want to use the setBounds(int, int, int, int) method to set out your components in the applet
window. How must you set the layout?
(b) Write statements to declare and instantiate a button called goButton with the following properties:
i. The button has the label “Go”.
ii. The button of width 50 and height 30 is positioned at the coordinates 100, 300.
iii. The button is disabled.
iv. The button is added to the applet window.
v. The button is activated to listen for user actions.
(c) Write the Java code you would use to create a Choice box with a list of colours (red, green, blue),
activate it and add it to the applet window.
(d) Sketch the textfield that would appear in your applet window from the statements:
myField = new TextField(“Enter name”, 15);
add(myField);
(e) A method belonging to the TextField class is the setText(String) method. What is its purpose?
Question 11
The questions below refer to the following lines of code.
class Flight
{
protected int flightNumber;
protected double departureTime;
protected String destination;
public void setCoords(int initialFNumber, double initialDTime,
String initialDestination)
{
flightNumber = initialFNumber;
departureTime = initialDTime;
destination = initialDestination;
}
a) You have an applet that uses Flight objects. Write a statement that would declare and instantiate a
new Flight object called myFlight that has a flight number 111, destination Paris and departure
time 11.20 am.
b) You add the following statement to your applet:
myDestination = myFlight.getDestination();
What would the value of the variable myDestination be?
c) Write a method for the Flight class that would allow you to get the flight time of myFlight.
Question 12
Consider the following class.
T h e a r r a y o b je c t c o n t a in s 5 in t e g e r s
lis t : (5 ) lis t .le n g t h
c a lle d lis t [ 0 ] e t c .
0 lis t [ 0 ] It a ls o h a s lis t .le n g t h w h ic h g iv e s t h e
n u m b e r o f it e m s in t h e a r r a y .
0 lis t [ 1 ] N o t e : lis t .le n g t h c a n n o t b e c h a n g e d .
0 lis t [ 2 ]
0 lis t [ 3 ]
0 lis t [ 4 ]
The number of items in an array is called the length of the array. The length of the array list can be
referred to as list.length and in this case would be 5.
The position number of the item in the array is called the index (or subscript) of that item. The
index of the first item in an array is always 0. If the length of the array is N then the index of the last
element is N-1. Once an array has been created its length cannot be changed.
The syntax for referring to an item in an array is:
array-variable [integer-expression]
so list[0] would refer to the first element in the array list, and list[4] the last if an array list had a
length of 5.
In Java, once an array is created it is always filled with a known or default value:
For integers this is zero
booleans is false
char is the character with Unicode number zero and
objects is null
Each one of the items in an array can be used just like a variable :
values can be assigned to it eg list[1] = 46.4
it can be used in expressions eg total = total + list[i]
eg total = total + list[i*3]
it can be passed as a parameter in subroutines
To print out the items in an array, list, using the paint method:
for (int i = 0; i < list.length: i++)
{
g.drawString(“” + list[i], xpos, ypos);
xpos = xpos + 10;
}
This loop will end after painting list[4], because once i = 5 it will no longer be less than list.length
(of 5 in this case).
There are 2 possible errors which can occur when accessing an array:
A null pointer error will occur if the value of the list is null, so list does not even refer to an
array. Trying to access say list[i] will produce this error.
Array index out of bounds error will occur if list does refer to an array but the value of the
index is outside the legal range of values (in our example
if i < 0 or if i > = list.length).
You can declare and initialise an array variable in one step:
eg int[ ] list = new int[5];
and the array items will have the default values of eg zero for integers.
You can also initialise an array with a specific list of values:
eg int[ ] list = { 1, 5, 7, 8, 12, 45 };
where the new list has the 6 values above, list points to this new array and list.length is known to be
6. Items in list do not have to be constants, they can be variables or expressions as long as their
values are of the same base type.
eg int[ ] list = { 1, 5*2, xx, 8, 12, 45 }; where xx is an int which has been initialised.
You can assign a new value to an array variable, list, that has been declared earlier using:
eg list = new int[ ] { 12, 24, 36, 48, 60, 66};
Note: You may see int[ ] list; correct Java syntax <type-name> < variable- name>
is sometimes written as int list[ ]; (a hangover from C, C++ and Pascal syntax)
Array Processing Techniques
Processing an array means applying the same operation to each new item in the array – usually with
a for loop
Applet code to add 5 numbers stored in an array called a.
int a [ ] = {6, 7, 9, 12, 4}; // give initial values to an array called a
public void init( );
{
total = 0; // total starts at 0
for ( int i = 0; i < a.length; i = i + 1 ) // only use < a.length here because if
// i = a.length you will get an “array
// out of bounds error”
total = total + a[i] ;
}
To count the number of items in an array that meet a certain condition (eg that the items are
even numbers)
int a [ ] = {6, 7, 9, 12, 4}; // give initial values to an array called a
public void init( );
{
count = 0; // count starts at 0
for ( int i = 0; i < a.length; i = i + 1 )
{
if ((a[i] % 2) == 0)
count = count + 1;
}
}
To count the number of times an item is the same as the next item in the array a
use the code above replacing if ((a[i] % 2) == 0) with if (a[i] == a[i+1)
Remember that the loop can only be repeated up to a.length –1 times because otherwise there would
be an “array out of bounds error”.
Binary Search
works on a sorted array. Check if item being searched for is greater than or less than a middle value.
You can then eliminate half of the array from being searched. Progressively halve the part of the
array to be searched, until the item is found, or you find the item is not there.
Making A Copy Of An Array
In some computer languages it is possible to make a copy of one array using:
double[ ] b = a; This is not correct in Java since all it does is declare a new array
variable and make it refer to the same object to which a refers.
ie a change to a[i] will make the same change to b[i] as well !!!
To make a new array b that is a copy of a, you must make a new array object and copy each of the
individual items from a into the new array b.
double[ ] b = new double[a.length]; // make a new array object the same size as a.
for ( int i = 0; i < a.length; i = i + 1 )
b[i] = a[i]; // move a copy of a[i] into b[i]
It is possible to only partially fill an array with useful data but you must keep a count of the number
of items in the array.
Sorting An Array
There are a number of different sorting strategies. We will look at the bubble sort. When sorting
items such as integers in an array a, you need to compare a[i] and a[i + 1]. To swap 2 values around
in the array you need to have another variable called hold to temporarily hold one of these values.
See below:
if (a[ i ] > a[i + 1])
hold = a[ i ];
a[ i ] = a[i + 1];
a[i + 1] = hold;
A bubble sort requires you to progressively compare elements next to each other in an array, and (if
you are sorting into ascending order) to place the lower number in the position with the lower index.
// Sorting an array into order using the bubble sort method.
public class sort extends Applet
{
int a[ ] = {6, 5, 4, 3, 2, 1};
boolean finished;
int i, j, xpos, hold;
public void paint(Graphics g)
{
//sort array into order
while (finished == false)
{ finished = true;
for(i = 0; i < a.length - 1; i++)
{ if (a[i] > a[i+1])
{ hold = a[i];
a[i] = a[i+1];
a[i+1] = hold;
finished = false;
}
}
}
//output sorted array
xpos=100;
g.drawString("Sorted Array is",20,80);
for(j=0;j<=a.length-1;j++)
{ g.drawString(a[j]+"",xpos,80);
xpos = xpos+30;
}
}
}
To bubble sort an array of strings rather than integers.
Use as your array a:
String a[ ] = {“Greg”, “Geoff”, “Anthony”, “Murray”, “Dorothy”, Wags, “Henry”};
In the bubble sort algorithm, when comparing 2 items which are strings, you cannot use if (a[ i ] > a[i
+ 1]) which is what you used for integers, use a[i].compareTo(a[i+1])
a[i].compareTo(a[i+1]) will result in a number < 0 if a[i] is < a[i+1] as for example if item a[i]
contained “Ant” and item a[i+1] contained “Dog”.
The reason for this is that the comparison is made using the ASCII numeric code for the characters
eg ‘A’ is 65 and ‘C’ is 67 and on comparison, 65 – 67 gives an answer of –2 which is less than 0.
Don’t worry about this but I’m just explaining why.
Other sort or ordering strategies for arrays:
Insertion Sort works on a sorted array. The item to be added to the list is inserted into the
appropriate place in the sorted list and all the items higher than the new item
will move up one place in the array.
Selection Sort works on an unsorted array. If the array is to be sorted into ascending order,
then the largest item is found and moved to the last position in the array. The
next largest item is found and moved to the second last place etc.
Shuffle There are times when you may need to make a sorted array in random order ie
to shuffle as in card games
// Shuffles an array into random order. From David Eck
public class shuffle extends Applet
{
int a[ ]={1, 5, 8, 56, 89, 99, 100}; //sorted array
int j, xpos, temp, randLoc;
public void paint(Graphics g)
{
//shuffle the array
for(int lastPlace = a.length-1; lastPlace > 0; lastPlace--)
{ // choose a random location (0 .. lastPlace)
randLoc = (int)(Math.random()*(lastPlace + 1));
temp = a[randLoc];
// swap items in locations randLoc and lastPlace
a[randLoc] = a[lastPlace];
a[lastPlace] = temp;
}
Two-Dimensional Arrays
A two-dimensional array is an array of arrays of a particular type.
An array of ints has the type int[ ] and an array of arrays of ints has the type int[ ] [ ]. It is possible to
have 3 or more dimensional arrays but we will stick to 2-dimensional ones.
To declare a variable aa of type int[ ] [ ] and to initialise it to refer to a newly created object use:
int [ ] [ ] aa = new int[3] [4];
where int[3] [4] can be thought of
as a grid of ints with 3 rows and 4 columns
aa:
(4 )
If you create an array 1 0 12 -1
aa = new int[3] [4], aa: 1
7 -3 2 5
you should think of it as a -5 -2 2 9
(3 )
0
"matrix' with 3 rows and
12
4 columns
-1
Really, aa holds a reference to an array
of 3 items, where each item is a reference
to an array of 4 ints.
Remember that arrays start with an index of 0, (4 )
so to refer to the fourth item in the third row use: (4 ) 7
aa[2] [3] which has the value 9. -3
-5
Note: aa.length gives the number of rows of aa;
-2 2
aa[0].length gives the number of columns.
2 5
9
A 2-dimensional array can be created as a list of array initialisers, one for each row in the array.
The array aa shown on previous page can be created using:
int [ ] [ ] aa = { { 1, 0, 12, -1 },
{ 7, -3, 2, 5 },
{ -5, -2, 2, 9 }
};
Two-dimensional arrays can be used wherever data naturally falls into rows and columns:
eg grid on a chess board
students and test scores
monthly sales from a number of branches of a store.
To process all the items in an array you need a for statement nested inside another.
Using the array aa with the following definition:
int[ ] [ ] aa = new int[3] [4]
you could store a 1 in each location of aa with the following code:
for (int row = 0; row < 3; row++)
{
for(int column = 0; column < 3; column++)
{
aa[row] [column] = 1;
}
}
The first time the outer loop executes with row = 0, the inner for loop then fills in the four values in
the first row of aa. The outer loop executes with row = 1 and fills in the four values in the second
row of aa etc.
54, 37, 89, 23, 65, 58, 23, 59, 92, 64, 43, 39, 60
2. The individual players in a sports team obtained the following points in matches with five other
teams. The results are plotted in the following table, with the names of the players in the top row and
names of the opposing teams in the left hand column:
4. How would you declare and initialize a String array which stores the names of the days of the
week?
5. A teacher wishes to store both the names of his 18 students and the marks they obtained in a
test. Declare and create arrays (you will need two of them) which will store all this information.
6. What is the final value of the int variable mystery in the following program:
7. What does the following program excerpt do (assuming everything else is correctly set up).
9. Consider the following code which has lines numbered for convenience:
10. Consider an array which has been declared and initialized as follows:
int[][] table = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}};
int count = 0;
for(int n = 0; n < 3; n++)
for(int m = 0; m < 2; m++)
if( table[n][m] > 2 ) count++;
What values are stored in table after each of the following sections of code.
(a) for (int n = 0; n <4; n++)
for (int m = 0; m < 4; m++)
table[n][m] = n;
13. The following table represents the scores obtained by 6 different football teams over 4 weeks of
matches.
14. Write code that will set up a 6 6 array in which the values stored are 0 if the sum of the
indices is odd and 1 otherwise.
Exercise 21 Characters and Strings
Summary of char variables
Comparing variables of type char with strings
char String
Variable type Primitive type Object
Speed of processing Fast Slower than char
Notating ‘A’ “A”
Assigning char charVal = ‘A’ String s = “Hello”;
String s = new (“Hello”);
Testing equality if (charVal == ‘A’)… if (s.equals(“Hello”))…
Special characters
‘\n’ newline (“enter”) character (does not work in drawString())
‘\t’ tab character (does not work in drawString())
‘\u’ unicode character
\” used to indicate that “ is part of a string and not the beginning or end of a string.
Casting between types char and int
charVal = (char) 65; charVal = ‘A’ (65 is the ASCII and Unicode value of
‘A’)
numVal = (int) ‘A’ numVal = 65.
Methods in class Character
If ch is the name of a character variable then the following methods can be used:
Character.isLetter(ch) returns the Boolean true if ch is a letter, false otherwise.
Character.isDigit(ch) returns the Boolean true is ch is a digit, false otherwise.
Character isLetterOrDigit(ch) returns the boolean true if ch is a letter or digit.
Character.isLowerCase(ch) returns true if ch is a lower case letter.
Character.isUpperCase(ch) returns true if ch is an upper case letter.
Character.toUpperCase(ch) returns a char having the upper case value of ch.
Character.toLowerCase(ch) returns a char having the lower case value of ch.
Strings
Declaring and initialising strings
All of the following are valid declarations:
String S1, S2;
String S1 = “Hello”;
String S1 = new (“Hello”);
After declaration, a string can be assigned a value in the following ways:
S2 = “Goodbye”;
S2 = new (“Goodbye”);
Assigning values to Strings
A string can be given a new value of different length. For example:
String S1 = “Hello”;
S1 = “Goodbye;
S1 = S2;
Strings can be concatenated using +:
S1 = “Hello” + “ “ + “to you.”;
S1 = S1 + “Jim”;
Comparing Strings
Since Strings are objects, they cannot be compared using == and other such symbols. They require
methods of the String class.
Comparing int n = “ant”.compareTo(“ant”) the two strings are the same, value of n is 0
int n = “ant”.compareTo(“bee”) “ant” precedes “bee” so value of n is
negative
int n = “bee”.compareTo(“ant”) “ant” precedes “bee” so value of n is positive
int n = “Bee”.compareTo(“ant”) “Bee” precedes “ant” (capitals have smaller
Unicode values) so n is negative.
Changing Strings
Suppose we have defined a string
String string1= “ Hello “:
Then:
string1.toUpperCase() has value “ HELLO “.
string1.toLowerCase() has value “ hello “.
string1.replace(‘e’, ‘u’) has value “ Hullo “.
string1.trim() has value “Hello”.
In each case we can replace the string variable with an actual string, such as:
“Hello”.toUpperCase() has value “HELLO”.
Concatenating Strings
To concatenate Strings, the easiest method is to use +:
newString = string1 + string2 + “Hello” + string3;
Other primitive types are concatenated as Strings provided they are preceded by a String:
newString = “” + 1234 + numVar + floatVar;
newString = “The answer is “ + (5 * 20); //In this case the product is
evaluated first //and then converted to a String, so newString has the
value “The answer is 100”
Extracting substrings
substring “Hello”.substring (n) returns the substring from position n onwards .
If n = 1 in this example it returns “ello”.
“Hello”.substring (n,m) returns the substring from position n to position (m – 1).
If n = 1 and m = 3 in the above example it returns “el”.
Properties of Strings
Strings may be regarded as arrays of characters with special properties and methods specified in the
String class. Hence, some of the notation for Strings corresponds with that of arrays, with the
characters being numbered from 0 to (string.length-1).
2. What is printed out, assuming s1, s2 and s3 have been correctly declared?
s1 = "bat";
s2 = "bee";
if (s1.compareTo(s2) == 0) then s3 = s1;
else
if (s1.compareTo(s2) < 0) then s3 = s2 + s1;
else
s3 = s1 + s2;
g.drawString (s3, 20, 120);
if (s2.compareTo(s3) > 0) {
s = s2;
s2 = s3;
s3 = s;}
if (s1.compareTo(s2) == 1) {
s = s1;
s1 = s2;
s2 = s;}
}
Here are some examples of common animated games with different numbers of threads.
Single Thread
The user sets some object moving across the screen. The user input and the moving object are
controlled by the same thread: once the object is moving, the user can’t do anything to change what it
does.
Snakes and Ladders: The user throws a die which cause a token to jump from square to square and
possibly to slide up a ladder or down a snake.
Golf: The user hits a golf ball which then moves across the screen bouncing off walls and other
obstacles and possibly landing in a hole.
Scientific simulations: some object (such as a golf ball, a rocket, a bullet or anything else) is
launched and follows a pathway mathematically determined by the laws of Physics.
Two Threads
The user is able to control the object while it is moving. The user input is in the “main” program
while the movement of the object is controlled by a separate independent thread.
Snake: The user controls a snake which moves horizontally or vertically in a box. When the snake
collects randomly placed food items it grows in length, but it the snake crashes into the wall it dies.
Tetris: A single “stone” falls down a grid. The user can control its position and orientation and must
try to place it in the best position when it lands at the bottom of the grid.
Three Threads
The “main” program controls the user input and as well as this there is an object which moves in
response to the users input and another object which moves independently around the screen,
Simple “Shoot-em-ups”: The user fires a gun which sends a bullet towards a moving target. The
threads are the interface, the user and the target.
“Pac Man”: the user controls the movement of a pacman which is being chased by monsters. The
threads are the interface, the pacman and the monsters.
Arkanoid: The user controls the movement of a “paddle” which moves left and right firing bullets at
a wall of bricks. The threads are the interface, the paddle and the bullets.
Single player tennis: the user controls a racquet which hits a ball against a wall. The threads are the
interface, the racquet and the balls.
Four Threads
Once again the “main” program controls the user input. However now there are three types of
objects moving independently around the screen.
Shoot-em-ups in which there is the main program, the user object moving around the screen, the
targets which “feed” the user and “baddies” who try to kill the user.
Two player tennis: The threads are the interface, the racquet, the ball and the opposing racquet
(which may be controlled by the computer).
Many Threads
Shoot-em-ups with the user able to fire a large number of bullets, each controlled by a separate
thread.
A summary of the techniques used to control various numbers of Threads
Single Thread
Here the only problem is to introduce delays which will slow down the animation to human speeds.
Two delaying techniques are:
Add a counting loop. This is simple, but the delay will depend on the speed of the computer.
for(int m = 0; m < 2000000; m++)
Put the thread to sleep for a time by inserting a sleep into each loop of the
animation. This will probably occur within a “for” loop (or similar) in paint(). In
the following example, the thread will “sleep” for tChange milliseconds
try{(Thread.sleep(tChange);}
catch (InterruptedException e){return;}
Note that in this case Thread (capital ‘T’) is used, calling to the static Thread method. If a separate
thread has been declared and created the name of this Thread object can be used instead. See below.
In the following example a separate Thread object has been declared, the class implements runnable
(see next section) and sleep is called in run():
thread is the name of the Thread object which has previous been declared
tChange is the sleep time in millseconds
the alternative catch procedure is return from the current loop – other alternatives may be used.
try{(thread.sleep(tChange);}
catch (InterruptedException e){return;}
If a Thread object has not been declared, the alternative code which calls the default Thread and is
often placed in paint() is:
try{(Thread.sleep(tChange);}
catch (InterruptedException e){return;}
Multiple Threads
Here the basic techniques are the same regardless of how many threads are running. But things can
get complicated.
Here is an outline of the code that you might use to run one extra Thread.
If you are running two or more threads, the code might look something like this.
The methods processThread1() and processThread2() will both contain a sleep method for that particular Thread. Once
again, they will often contain a reference to the Applet window Graphics context which avoids the use of paint().
Here is the basic code for setting up a new Thread class. In this example the Graphics context and
background colour will be passed from the main class to the Thread class in the constructor
parameters. Your programs might well have different constructor parameters.
In the main class you must declare, create and start the MyThread object which we will name
myThread (watch the capitals in the first letter). In the example above you might include the
following code in init():
MyThread myThread; //declaration
Graphics gr = getGraphics(); //get the Graphics context
Color col = getBackground(); //get the background colour
myThread = new MyThread (gr,col); //creating object myThread
myThread.start(); //start object myThread
In the main class you can set and get the public Thread variables using code such as:
myThread.variable1 = <value>;
<value> = myThread.variable2;
Stopping a Thread
Note: Some text books use an infinite loop such as for(;;) in run(), and use threadName.stop() to stop the Thread. This
practice has been declared to be dangerous by the developers of Java and if you use stop you will get a deprecated API
message when you build the class. You should avoid stop and instead use a more direct method to stop a Thread.
An animation thread will generally be controlled by some form of loop. When the loop is ended, the
thread will stop releasing the computer resources it was using while alive. You should make sure that
you write code to jump out of the loop.
Run a while loop while some boolean variable is true. The boolean can be set false in many different
ways. For example, the user could type in a character on the keyboard. The user might die on
collision with a wall or monster object in the game.
while(isAlive) {…}
Then use break to break out of the loop or return to go back to the method which called the method
containing the loop.
if (exitCondition) return; OR
if (exitCondition) break;
1. Scrolling Text
Write a class in which a text string (with a large font) moves across the screen from right to left.
When the text completely passes from the left of the window, it starts moving again from the right.
2. Simple animation
Obtain a series of animated gif images from http://www.animationfactory.com/
and incorporate them into a simple program which displays each of the images one after the other
(with a sleep time of perhaps 40 mS). It is simplest to create an array of images in your program.
Exercise 23 Graphics in Games with Animation
How do you draw to the screen?
The Graphics context is the computer equivalent of the paper, pencils and rules needed for drawing a
picture. An image is drawn into the Graphics context by calling the various graphics methods such as
gContext.drawString(String, int, int);
gContext.drawImage(Image, int, int, this);
and so on.
When you call paint(Graphics g), g is the context for the screen image. Therefore, a call to a method
such as g.drawLine(int,int,int,int) in paint() draws directly onto the screen in the Applet window.
To draw onto the screen (Applet window) without using paint() you must:
Name and create a Graphics object with the current Graphics context (ie the Applet window). In
this case we have named the object “gCurrent” though any other name is possible.
Graphics gCurrent = getGraphics();
Draw into the current context from another method. For example:
gCurrent.drawRect(int,int,int,int);
It is also possible to have an off screen image with its own Graphics context and to draw on this
image. This is the technique used in double buffering.
Double Buffering
If you build up an image component by component on the screen, the image will flicker as each
component is added.
In Double Buffering you create a background (buffer) Graphics context and its image, add all your
components to this buffer and finally draw your complete image to the screen when it is ready.
Steps in double buffering are:
Declare the Graphics context and buffer image:
Image buffer; //buffer image
Graphics gContext; //The buffer Graphics context
Draw the buffered image into the buffered Graphics context one component at a time. For example:
gContext.drawLine(20, 40, 60, 80);
gContext.drawImage(myImage, 0, 0, this);
Swap (or copy) the final buffered image onto the Applet window in paint().
g.drawImage(buffer,0,0,this);
Update
The update() method controls the painting of an image onto the screen. The default erases the current
image with a blank screen before painting the new image. This causes flicker.
To prevent this erasing, and so to enable the new image to build up over the old image without
flicker, you must override the automatic update function by including the following method in your
program:
If the precise coordinates of the background are important (for example if the image contains walls
for a moving ball to bounce off) you can proceed as follows:
In Java draw the essential outlines of the image. For example, draw important boundaries using
drawLine and the positions of important components using fillOval and other Graphics methods.
In Paintshop Pro capture this image from the Applet window and save it as a GIF file without
changing the size. (You will have to save with only 256 colours.) You would preferably save it in the
same directory as your Java project.
In Paintshop Pro or other graphics software, add whatever nice effects you want without changing
the size of the image or the position of the crucial coordinates.
In Java draw this image first into the buffered Graphics context and then onto your Applet.
Just to remind you, the important steps in adding a file image to a class are:
Declare the image:
Image background;
Create the image in init(). If the image file is in the same directory as the project use:
background = getImage(getDocumentBase(), "myImage.gif");
Create the MediaTracker object and use it to force the class to wait until the image is successfully
loaded. The following code is inserted into init() after the creation of the image object.
Flicker2
In this class, the class repeatedly creates the background image but all available techniques are used
for reducing the flicker.
Flicker3
In this class the background image has been created as a separate image “Flicker.gif” in a file which
is also provided in Outlook. You should download this image into your project directory if you want
to run the program. The effect is much the same as for Thread2. In this case there appears to be little
difference between creating the image in the program and downloading it from a file.
Exercise 24 Notes on games which make use of Thread techniques
Most text books seem to favour a technique which puts the various threads in multi-threaded
programs into separate classes which inherit from the Thread class. However this can lead to difficult
programming, particularly if you are not familiar with the techniques needed to create and use
separate classes in your program.
The three games illustrate the various features of each style of programming.
Projectile simulation: Since this simulation only requires one thread, the only thread
technique needed is in setting the sleep time for this thread.
Ball inside a box: The final game (Thread6) uses Runnable to control two independent
threads. In this case, Runnable is perfectly effective and provides the easiest programming.
Shoot-em-up: The final game (Shoot2) places both the target and bullet objects in separate
classes. This was necessary (in the case of the Bullets at least) in order to enable the user to
fire any number of bullets at any one time. The programming is more complex, but so is the
game.
You can find these programs in Outlook public folders as well as various different versions which
illustrate different approaches to writing the programs.
The position of the ball and target are global variables which can be used by any of the threads.
Run uses an if..else statement to select which of the ball and target threads to process. Each thread
has its own sleep time.
The threads are stopped by setting a loop control variable (isAliveBall or isAliveTarget) to false and
returning from the relevant loop in run().
Screen components are drawn in the current Graphics context so that paint is not used except for
the printout of the number of times the target has been captured.
Thread1 has only a single thread (controlled by the main class) with no user interaction. The
only use of Thread techniques is to use sleep to control timing.
Thread2 implements Runnable which enables the ball to be controlled by the user in a named
second Thread. There is no target.
Thread3 provides an alternative technique which has the same overall effect as Thread2. The
ball is made an object of a separate class Ball which implements Thread.
Thread4 introduces a target to the game. Both are controlled by the same Thread (in
Runnable) so that when one stops they both stop.
Thread5 places the target in a separate class so that it moves independently of the ball as a
third Thread.
Programming exercise
Introduce a “monster” thread to the game. A monster moves around the screen trying to catch the
ball. The monster can bounce off the walls. If the monster catches the ball the ball dies.
A good version of the game will have the monster actually chasing the ball and not just moving at
random.
Simple shoot-em-up (Shoot2)
How the game is played
The user can fire a gun at the bottom of the screen by pressing the spacebar. Each time the
spacebar is pressed a new bullet flies upwards.
A target moves from right to left across the top of the screen.
If a bullet hits the target, the target dies in an explosion (very simple!). The user can start a
new target by pressing the ‘m’ key.
Each time the user fires the gun the ammunition count (which starts at 100) decreases by 1.
The game is over when the user has used up all the ammunition.
Unfortunately, the program gets rather complicated and you will need to understand object
programming before you try it yourself.
Thread control
Since the Bullet class needs to know the position of the target for collision detection, the
Target class is passed to the Bullet class as a parameter.
Each bullet object is run in a separate Thread with its own values of position and so on.
The various bullet threads are stopped (using return from the control loop if isAlive becomes
false) if the bullet reaches the top wall or if the bullet hits the target.
The target thread is stopped (by setting isAlive to false) it the target is hit by a bullet.
A new target thread is started if the user types the ‘m’ key.
Programming exercises
Enable the user to move the position of the gun left or right using the arrow keys.
Alternately, enable the user to change the direction of the gun by using the arrow keys.
Make the target move a little more randomly – perhaps up and down as well as left and right.
Make the game look better: include a background image and use better images for the gun and target.
While programming these games (as well as the final result) can be fun, it can also be very
frustrating.
What variables need to be passed between threads and how are you going to do this? If all your
threads are part of the main program (implementing Runnable) you can start by making shared
variables global. If you need to use a separate class (extending Thread) you must carefully plan how
you pass the variables between the classes: this can get messy!
How do you do your drawing to the screen? With a single thread you would use paint(), but with
many threads it might be better to get the current graphics context and draw to this context in run().
Don’t forget the techniques presented in previous notes for preventing flicker. In particular, if your
program starts using interesting images you should use double buffering.
A Double Buffering, 120
doubleValue, 25, 38
ActionListener, 17, 60 drawImage, 20
actionPerformed, 17 drawLine, 5
add, 15 drawOval, 5
Add, 16 drawRect, 5
addActionListener, 18
addAdjustmentListener, 64
addItemListener, 62
E
addKeyListener, 65 Equality operators, 29
AdjustmentEvent, 64 Events, 18, 60
AdjustmentListener, 64 extends, 87
adjustmentValueChanged, 64 Extracting substrings, 112
Applet methods, 42
init(), 42
paint(), 42 F
Arrays, 101 fillRect, 5
Array index out of bounds error, 102 float, 27, 35
Finding The Largest (Or Smallest), 103 floatValue, 38
null pointer error, 102 Fonts, 4
Sorting An Array, 103 for loop, 33, 77
Two-Dimensional Arrays, 105 format, 25
AudioClip, 22
G
B
getAudioClip, 22
block, 35, 49 getCodeBase, 20, 22
boolean, 35, 38 getDocumentBase, 20
boolean expression, 29 getGraphics, 120
break, 73 getHeight, 21
Break, 78 getImage, 20
getKeyText, 65
C getSize, 120
getSource, 23, 31, 60
Call-By-Reference, 50 getText, 18
Call-By-Value, 50 getWidth, 21
Casting, 26, 27, 37 global declaration, 9, 35
catch, 116 Graphical User Interface, 15
char, 35, 39 Graphics Objects, 5
Character methods, 40
charAt, 113
Checkboxes, 62 I
CheckboxGroup, 63 if, 28, 29, 71
Class, 4, 83 Compound if statement, 71
Classes, 54 if .. else statements, 71
Colors, 4 if.......else, 32
compareTo, 104 if....else, 31
Components, 15 Nested if statements, 71
compound statement, 33 implement, 18
concat, 112 import, 4
concatenate, 18 Inheritance, 87
Concatenating Strings, 112 init(), 9, 42
Constructors, 54 Instance methods, 53
Continue, 78 Instance variables, 49, 53
control variable, 33 instanceOf, 60
instantiate, 12
D Instantiate, 16
Instantiating an object, 83
dangling else, 72 int, 27, 35
DecimalFormat, 25 integer variable, 8
Declare, 16, 83 Interfaces, 54
default, 73 intValue, 38
destroy(), 42 isDigit, 40, 111
double, 27, 35 isLetter, 40, 111
isLetterOrDigit, 40, 111 Parameters, 50
isLowerCase, 40, 111 parseInt, 18, 38
isSpace, 40 play, 22
isUpperCase, 40, 111 Precedence, 27
isWhiteSpace, 40 Precedence of Mathematical Operations, 36
ItemEvent, 62 private, 53, 83
ItemListener, 62 Promoting, 26, 27, 36
itemStateChanged, 62 Properties of Strings, 112
protected, 53
public, 53, 83
J
Java shortcuts, 36 R
Radio Buttons, 63
K random, 27, 37
Keyboard events, 65 Relational operators, 29
keyPressed, 65 repaint(), 42
keyReleased, 65 replace, 14, 112
keyTyped, 65 requestFocus(), 65
return, 46, 49
round, 27, 37
L run, 117
length, 14, 112 Runnable, 117
local, 35
long, 27, 35 S
loop, 23
Scope Rules, 49
Scroll bars, 64
M setBounds, 64
max, 27, 37 setLayout(null), 64
MediaTracker, 121 shortcuts, 36
method call, 48 showStatus, 18
Method Overloading, 51 sleep, 116
Methods, 42 Special characters, 111
Modularising Graphics, 52 sqrt, 27, 37
modulus, 36 start, 118
Mouse events, 66 start(), 42
mouseClicked, 67 static, 118
mouseDragged, 67 Static methods, 53
mouseEntered, 67 Static variables, 53
mouseExited, 67 stop, 23
MouseListener, 66 stop(), 42
MouseMotionListener, 67 Stopping a Thread, 118
mouseMoved, 67 String methods, 14
mousePressed, 67 Strings and Characters, 111
mouseReleased, 67 Asigning values to strings, 111
Casting, 111
Changing Strings, 112
N Comparing char with strings, 111
Comparing strings, 112
nest for loops, 77
Concatenating Strings, 112
new, 12
Extracting Strings, 112
null pointer error, 102
Properties of Strings, 112
Number Types, 27
Strings, 5
Strings, 14
O Switch statements, 72
Object, 83
object-oriented programming, 83 T
Objects, 11
this, 18
Order of precedence, 39
Threads, 115
toLowerCase, 14, 40, 111
P toString, 18, 25
toUpperCase, 14, 40, 111
Packages, 4 trim, 14, 112
paint try, 116
More on paint(), 42
paint( ), 4
paint(), 42
parameter, 44
U Variables, 8
boolean, 38
update, 68, 121 void, 44
V W
valueOf, 18 While and do loops, 78
Variable names, 35 Window Coordinates, 5
Variable types, 35 Wrapping, 54
Java Exercises
Introductory exercises
Page Ex
6 1 Hello World
7 modifications
9 2 Integer variables + modifications
12 3 Objects +modifications + teacher check
14 4 Strings
16 5 Components partially completed
19 6 Previous program added to + modification
21 7 Images
Practical exercises
28 10_1 sum, product, quotient and maximum value.
10_2 counts each time the user presses button and prints
32 12_1 marks
12_2 histogram
12_3 voting
12_4 calculator
54 16_1 areas
16_2 lines and rectangles
80 18_4 primes
18_5 quadratics
89
Other programs