Title: An Introduction to Applets
1An Introduction to Applets
- There are two kinds of Java programs
applications and applets - All the programs we wrote last semester were
applications they have a main - This semester we will write Applets
- Applets run within a web page
- For each assignment, we will create two files
the java program and the web page (.html)
2Applets
- When you visit a website and see this Java logo,
a Java Applet is being loaded into your web
browser - An applet can do almost anything that an
application can - But they look differentthere is no main
3Writing a Hello World applet in JCreator
- The first time you start JCreator, you will see a
screen like the one below - Click "Finish" to accept the file associations
4Configuring JCreator at school to use your
network Z drive
- Don't try this at home kids!
- Choose Configure Options
- Click on "Directories"
- Under "Default Project Directory" enter Z\Java\
5Writing a Hello World applet in JCreator
- Open JCreator
- Choose File Close Workspace to close any open
files - Choose File New Project
- Click on Basic Java Applet and click Next
- Give your class a NameIll call mine Assignment1
- Click Finish
- JCreator automatically generates both the Java
and html code
6Writing a Hello World applet in JCreator
- The Java code Assignment1.java looks like this
7- The html code Assignment1.htm looks like this
8Java is very picky about names
- Do NOT use spaces in class names.
- It's difficult to change the name of a class.
Make sure you choose the name you want when you
make a new project. If you make a mistake with
the name, it's best just to start over. - You can change the name of the .html file
JCreator will give it the same name as the class
(Assignment1.htm in this case) but you can change
it to anything you want
9Running the Applet
- Choose Build Compile Project
- You should see Process Completed
- Choose Build Execute Project
- You should see
10Uploading the applet
- When you build your applet, it creates a .class
file - To put your applet on the internet, you need to
upload - The .class file
- The .html file
- To find these files, go to your Z drive and
look in your Java folder. Find the Assignment1
folder, and inside of that the classes folder - You will then upload both Assignment1.class and
Assignment1.htm to your website - You will then put a link on your homepage to
Assignment1.htm
11Uploading the applet
- To upload to pages.google.com, just click on the
upload button on the right side of the site
manager page - Then browse to your .class and .html files one at
a time
12Adding a link
- To put a link to your first assignment, click on
the link button, give your link a title, choose
"Your Files" and choose the .htm file - Remember, your program can't run without a
webpage (.htm or .html file)
13Adding a link
- Your homepage should now have a link to your
first assignment
14Adding a link
- Clicking on the link should bring up a webpage
that looks like this
15Assignment 1
- Create a home page
- Create a Hello World applet
- Upload the .class and .htm files for the applet
to your website - Link your home page to your Hello World page
- Send an email with the URL of your home page and
your java code to room334_at_gmail.com
16Guidelines for Applet Creation
- IMPORTANT Always choose File Close Workspace
to close the previous project before starting a
new one
17Guidelines for Applet Creation
- Here are some guidelines to follow to help you
create applets - Well discuss the details of what they all mean
later on - Every applet must have a comment at the top
telling who wrote it, etc - / Mr Simon, Java Mods 10-11
- Assignment 1 /
18Guidelines / Applet Creation
- Every applet must have two import statements
- import java.awt.
- import java.applet.
- Every applet is stored in a file whose name is
XYZ.java - Every applet has
- public class XYZ extends Applet
19Guidelines / Applet Creation
- (Most) every applet contains a paint method
- public void paint(Graphics g)
-
-
-
- The body of the paint method does the drawing
that is required
20Guidelines / Applet Creation
- The size of the applet is set in the HTML code in
the applet tag - ltAPPLET CODE"XYZ.class" WIDTH"300"
HEIGHT"300"gt - IMPORTANT the name of the class has to match
both the name of the .java file and the name used
in the applet tag.
21Guidelines / Applet Creation
- Good Style
- The name of a class should always start with a
capital letter. (e.g. MyApplet) - Method (function) names should start with a
lowercase letter. If the name uses more that one
word, capitalize each additional word. (e.g.
drawArc) - Variable names should start with a lower case
letter that indicates the data type. (e.g.
nNumPeople, dDouble, cChar, sString). This is
called Hungarian Notation.
22Indentation
- Just like in C, code in curly braces should be
indented as part of good style - Luckily, JCreator makes this much easier. It will
automatically indent inside of curly braces - And it gives you an indentation tool that lets
you indent blocks of code with one click! Yippee!
23Graphics in Java
- Unlike C, Java comes with built in graphics
- Putting the following statement at the top of
your program allows you to use the graphics
methods - import java.awt.
- There are various methods that allow us to draw
shapes including lines, rectangles, ovals and
polygons both unfilled and filled
24An applet that draws a Red Square
- import java.awt.
- import java.applet.
- public class RedSquare extends Applet
-
- public void paint(Graphics g)
-
- g.setColor(Color.red)
- g.fillRect(20,20,100,100)
-
25An applet that draws a Red Square
26Some Graphics methods
- void setColor(Color color)
- void drawArc(int x, int y, int width,
- int height,int startAngle, int
arcAngle) - void drawLine(int x1, int y1, int x2, int y2)
- void drawOval(int x, int y, int width,int height)
- void drawRect(int x, int y, int width, int
height) - void drawString(String s, int x, int y)
- void drawRoundRect(int x, int y, int width,
- int height, int xRounding, int
yRounding) - void draw3DRect(int x, int y, int width,
- int height,
boolean raised) - void drawPolygon(int xPoints, int yPoints,
- int
nPoints) - void drawPolyline(int xPoints, int yPoints,
- int
nPoints) - //and for every draw method, there is a fill
method
27The Graphics Class
- Drawing is done within the space specified by a
bounding rectangle
28The Color Class
- There are a collection of 13 predefined colors
Color.black, Color.blue, Color.cyan,
Color.darkGray, Color.gray, Color.green,
Color.lightGray, Color.magenta, Color.orange,
Color.pink, Color.red, Color.white, Color.yellow - And, you can create a new color using Color(red,
green, blue), where RGB are in the range 0-255 - g.setColor(new Color(125,35,89))
29The Color Class
- Set the background color using
- void setBackground(Color color)
- Set the drawing color using
- void setColor(Color color)
- For example
- setBackground(Color.yellow)
- g.setColor(Color.white)
- g.drawLine(50, 50, 100, 200)
- g.setColor(Color.black)
- g.drawRect(70, 80, 100, 25)
30drawArc
- For Assignment 2, you must use drawArc (you may
use other methods as well) - drawArc has the following prototype
- void drawArc(int x, int y, int width,
- int height, int startAngle,
- int arcAngle)
- x, y, width, and height set the bounding
rectangle
31drawArc
- startAngle and arcAngle set the starting point
and length of the arc - g.drawArc(20, 20,200,100,90,180)
90
180
0
270
32drawArc
- Of course, all you see on the screen is the arc
- g.drawArc(20, 20,200,100,90,180)
33Adding a number to a string
- int nNum 5
- g.drawString("Total " nNum, 20, 20)
- //displays Total 5
- The operator can be used to add a number to a
stringmuch easier than C! - The order makes a difference!
- g.drawString("X" 2 3, 20, 20)
- //displays X23
- g.drawString("X" (2 3), 20, 20)
- //displays X5
34Cast
- Most of Java's syntax comes from C, but there
are some important differences - Java is strongly typed
- This means it's very strict about data types
- int nNum 5.6
- In C this would store 5 in nNum, but in Java
it's an error. To fix it you need a cast - int nNum (int)5.6
35Math.random()
- Java has a Math class with many methods
- random() returns a random double between 0 and 1
(including 0 but not 1) - g.drawString("A random number "
- Math.random(), 20, 20)
- //Displays something like
- //A random number 0.382590608216294
36Math.random()
- Just like C, you can cast a double into an int
- g.drawString("A random number "
- (int)(Math.random()2), 20, 20)
- /(Math.random()2) gives a random number between
0 and 1.999999. . . - cast as an int, we get either 0 or 1 /
37Problem Generate a random integer between 0 and
100
- First we need a random decimal
- Math.random() 101
- Gives a random decimal between 0.0 and 100.9999.
. . - (int)(Math.random()101)
- Gives a random integer between 0 and 100
38Problem Create a random integer between 3 11
(including 3 but not 11)
39Problem Create a random integer between 3 11
(including 3 but not 11)
- First, we'll solve a simpler problemsubtract 3
so we start at zero
40Problem Create a random integer between 3 11
(including 3 but not 11)
- First, we'll solve a simpler problemsubtract 3
so we start at zero - That, is, a random integer from 0 to 8 (including
3 but not 11) - (int)(Math.random() ??)
41Problem Create a random integer between 3 11
(including 3 but not 11)
- First, we'll solve a simpler problemsubtract 3
so we start at zero - That, is, a random integer from 0 to 8 (including
3 but not 11) - (int)(Math.random() 8)
42Problem Create a random integer between 3 11
(including 3 but not 11)
- Now, add 3 to shift the range back up
- (int)(Math.random() 8) 3
43Watch out for this mistake
- (int)Math.random()101
- is always zero!
44Watch out for this mistake
- (int)Math.random()101
- If Math.random() is cast as an int before being
multiplied, the result is always zero - The fix
- (int)(Math.random()101)
45The paint() and init() methods
- The paint() method is called automatically when a
screen update is needed - The paint() method may be called many times. If
you have something that should only run once, put
it in init() - init() is called once, before paint(). It's
generally used to initialize values.
46An applet with init() and paint() methods
- import java.awt.
- import java.applet.
- public class TwoMethodDemo extends Applet
-
- int nNum
- public void init()
-
- nNum 3
- setBackground(Color.blue)
-
- public void paint(Graphics g)
-
- g.setColor(Color.red)
- g.fillRect(10,10,200,200)
- g.setColor(Color.white)
- g.drawString("nNum is " nNum,105,105)
-
47An applet with init() and paint() methods
48Practice quiz questions Write an expression
- that will make a random decimal between 0 and 5
(including 0 but not 5) - that will make a random integer between 0 and 5
(including 0 but not 5) - that will make a random integer between -2 and 3
(including -2 but not 3) - What is the output of the following line
- g.drawString(("One" 2) (3 4),20,20)
49switch statements
- switch statements work the same in Java and C
- int nNum 1
- switch (nNum)
-
- case 0
- g.drawString("nNum is zero",20,20)
- break
- case 1
- g.drawString("nNum is one",20,20)
- break
- default
- g.drawString("nNum isn't zero or one",20,20)
50Relational and logical operators
- Relational and logical operators are the same in
Java and C - Relational operators compare two values gt gt lt
lt ! - Logical operators work with expressions that are
true or false - !
51Practice quiz questions
- Fill in the blanks to produce the image shown
above - g.drawRect(30,30,150,120)
- g.drawArc(___,___,___,___,____,_____)
- gt is an example of a __________ operator
- is an example of a _________ operator
- What is the output of the following line
- g.drawString("Y" (2 3 "Z"),20,20)
- Use Math.random() to create a random integer
between gt4 and lt4 (including 4 but not
including 4)
52Practice with , and !
- The argument weekday is true if it is a weekday,
and the argument vacation is true if we are on
vacation. We sleep in if it is not a weekday or
we're on vacation. Return true if we sleep in. - boolean sleepIn(boolean weekday,
- boolean vacation)
- return ??
53Practice with , and !
- Our Job is to translate not a weekday or we're on
vacation into a Java statement that evaluates
into true or false and return it. - boolean sleepIn(boolean weekday,
- boolean vacation)
- return ?? ?? ??
54Practice with , and !
- not a weekday or we're on vacation
- boolean sleepIn(boolean weekday,
- boolean vacation)
- return weekdayfalse ?? ??
55Practice with , and !
- not a weekday or we're on vacation
- boolean sleepIn(boolean weekday,
- boolean vacation)
- return weekdayfalse ??
56Practice with , and !
- not a weekday or we're on vacation
- boolean sleepIn(boolean weekday,
- boolean vacation)
- return weekdayfalse
- vacationtrue
57Practice with , and !
- not a weekday or we're on vacation
- boolean sleepIn(boolean weekday,
- boolean vacation)
- return !weekday vacation
58Good Style is easy to understand
- The preferred solutions are a direct translation
of the problem not a weekday or we're on
vacation. There are other correct solutions, but
they are much more confusing - boolean sleepIn(boolean weekday,
- boolean vacation)
- return !(weekday !vacation)
-
- This is ugly and confusing, but it does work!
59In class Monkey Trouble
- http//www.javabat.com/prob?idWarmup.monkeyTroubl
e - We have two monkeys, A and B. We are in trouble
if they are both smiling or if neither of them is
smiling. Return true if we are in trouble.
60In class Monkey Trouble
- Hint
- We have two monkeys, A and B. We are in trouble
if they are both smiling or if neither of them is
smiling. Return true if we are in trouble. - return (??) (??)
61Modifying the .html file
- The web pages that JCreator makes automatically
are pretty plain - They have a black background and your program
- We can add html code to format the look of the
webpage - html is not a programming language, it's a
Mark-Up language
62Adding to the head
- ltHTMLgt
- ltHEADgtltTITLEgtMr. Simon's first Java
Program!lt/TITLEgt - lt/HEADgt
- ltBODY BGCOLOR"000000"gt
- ltCENTERgt
- ltAPPLET
- code "Assignment1.class"
- width "500"
- height "300"
- gt
- lt/APPLETgt
- lt/CENTERgt
- lt/BODYgt
- lt/HTMLgt
63Adding to the head
- ltHTMLgt
- ltHEADgtltTITLEgtMr. Simon's first Java
Program!lt/TITLEgt
64Adding to the body
- ltHTMLgt
- ltHEADgtltTITLEgtMr. Simon's first Java
Program!lt/TITLEgt - lt/HEADgt
- ltBODY BGCOLORblack TEXTwhitegt
- ltCENTERgt
- lth1gtCheck this out!lt/h1gt
- ltAPPLET
- code "Assignment1.class"
- width "500"
- height "300"
- gt
- lt/APPLETgt
- lt/CENTERgt
- lt/BODYgt
- lt/HTMLgt
65Adding to the body
- ltBODY BGCOLORblack TEXTwhitegt
- ltCENTERgt
- lth1gtCheck this out!lt/h1gt
- ltAPPLET
66Colors can also be specified with hexadecimal
codes
- ltBODY BGCOLORblack TEXT"54ff9f "gt
- ltCENTERgt
- lth1gtCheck this out!lt/h1gt
67Some useful html tags
- bold ltbgttextlt/bgt
- italicized ltigttextlt/igt
- type-written ltttgttextlt/ttgt
- Headings lth1gtLargest Headinglt/h1gt through
lth6gtSmallest Headinglt/h6gt - Horizontal Rule lthrgt
- Paragraph ltpgt ... lt/pgt
- Font Sizes ltfont size1gt slightly larger font
lt/fontgt (you can use other numbers, including
negative)
68Some useful html tags
- Important Alignments add align"left" ,
align"right", align"center" i.e. lth1
align"right"gtbig heading right alignedlt/h1gt - Line break ltbrgt i.e. Line One.ltbrgtLine Two.
- Preformatted Text ltpregt ... lt/pregt
- Regular link lta href"http//url_here.com/"gttext
for linklt/agt - Mail Link lta href"mailtousername_at_host.com"gtemai
l melt/agt - Inline Images ltimg src"http//url_here.com/direc
tory/graphic.gif"gt - Center Tag ltcentergt lt/centergt
69Some useful html tags
- (Hidden) Comments lt!-- Your user cannot see this
unless they read your source code --gt - Unordered List
- ltulgt
- ltligt first item lt/ligt
- ltligt second item lt/ligt
- lt/ulgt
- Ordered List (numbered)
- ltolgt
- ltligt item 1 lt/ligt
- ltligt item 2 lt/ligt
- lt/olgt
- ltcodegt lt/codegt Uses courier font
70Simple Animation using a Timer
- To do animation in Java correctly requires
significantly more code than animation in C - Well learn the correct way to do animation in
assignment 12 - Heres another, easier way to do animation using
a timer
71The Universal Animation Loop
- The Universal Animation Loop is
- Erase MoveDrawWait
- Its the same principle when we use a timer, but
it looks different in Java - We create a timer, and it fires every so often
- Every time it fires, we move the object and
repaint the screen (the screen is automatically
erased in Java)
72Let's start with a program that paints a
rectangle in a random position
- import java.awt.
- import java.applet.
- public class GraphicsDemo extends Applet
- public void init()
-
- public void paint(Graphics g)
- g.fillRect(50,(int)(Math.random()
200),50,50) -
73Add two import statements
- import java.awt.
- import java.applet.
- import java.awt.event.
- import javax.swing.Timer
- public class GraphicsDemo extends Applet
- public void init()
-
- public void paint(Graphics g)
- g.fillRect(50,(int)(Math.random()
200),50,50) -
74Add implements ActionListener
- import java.awt.
- import java.applet.
- import java.awt.event.
- import javax.swing.Timer
- public class GraphicsDemo extends Applet
- implements
ActionListener - public void init()
-
- public void paint(Graphics g)
- g.fillRect(50,(int)(Math.random()
200),50,50) -
75Add the Timer
- import java.awt.
- import java.applet.
- import java.awt.event.
- import javax.swing.Timer
- public class GraphicsDemo extends Applet
- implements
ActionListener - Timer theTimer
- public void init()
- theTimer new Timer(500,this)
- theTimer.start()
-
- public void paint(Graphics g)
- g.fillRect(50,(int)(Math.random()
200),50,50) -
76Add actionPerformed
- import java.awt.
- import java.applet.
- import java.awt.event.
- import javax.swing.Timer
- public class GraphicsDemo extends Applet
implements ActionListener - Timer theTimer
- public void init()
- theTimer new Timer(500,this)
- theTimer.start()
-
- public void paint(Graphics g)
- g.fillRect(50,(int)(Math.random()
200),50,50) -
- public void actionPerformed(ActionEvent ae)
-
- repaint()
77The Finished program
- import java.awt.
- import java.applet.
- import java.awt.event.
- import javax.swing.Timer
- public class GraphicsDemo extends Applet
implements ActionListener - Timer theTimer
- public void init()
- theTimer new Timer(500,this)
- theTimer.start()
-
- public void paint(Graphics g)
- g.fillRect(50,(int)(Math.random()
200),50,50) -
- public void actionPerformed(ActionEvent ae)
-