Week 9 Power Point Slides

Download Report

Transcript Week 9 Power Point Slides

Applets
• An applet is similar to a Java program, but it runs
within a Web-browser on a client machine.
• For security, you cannot change anything on a client
system in a Java applet
• The browser gives the applet a piece of the browser
window, and Java controls that region
• The structure of an applet is different than an
application
– There is an init method instead of a main() method
– An applet inherits (extends) a Applet class. This means all
the methods in the applet class are available to the applet
you create
– Some methods that are available include init(), paint(),
update(), setSize(), and others.
Graphics class object
• Methods
–
–
–
–
–
–
–
g.drawArc(x, y, width, height, startAngle, endAngle);
g.fillArc(x, y, width, height);
g.drawLine(x1, y, x2, y2);
g.drawOval(x, y, width, height); or g.fillOval(x, y, width, height);
g.drawRect(x, y, width, height); or g.fillRect(x,y,width,height);
g.drawPolygon(x[], y[], x.length); or g.fillPolygon(x[], y[], x.length);
g.setColor(color);
• Notes
– x, x1, x2, x[] = distance from the left, y, y1, y2,y[] = distance from the
top
– width = how wide to draw, height = how high to draw
– color = the color to use for drawing
The Color Class
• Instantiate a color
Color c = new Color(red, green, blue);
Color c = new Color(red,green,blue,opacity);
• Set the current color for drawing
graphics.setColor(c);
• Fill a rectangle using the current color
graphics.fillRect(0,0,800,800);
A Rectangle applet
We override JApplet init and paint methods, this is polymorphism
import java.awt.*;
import javax.swing.*;
public class Picture extends JApplet // Inherit from the JApplet class
{ public void init()
{ setSize(new Dimension(800,800)); }
public void paint(Graphics g) { g.setColor(new Color(256*255));
g.fillRect(0,0,799,799);
g.setColor(new Color(0));
g.fillRect(50, 100, 100, 200); }
}
1.
2.
3.
4.
Import gets Java features that can be used if we ask for them
A Dimension object defines a width and height
setSize defines a size for the applet window
extends is a reserved word for inheriting from the Applet class
Testing and running an Applet
• In Jgrasp, simply click on the picture of the apple
• Create a web-page with the applet
<html>
<head><title>My Applet</title></head>
<body>
<applet code="MyPicture.class"
width="800" height="800"></applet>
</body></html>
Review
•
•
•
•
•
•
•
•
•
What is an applet?
What security concerns relate to an applet?
What is inheritance?
What is polymorphism?
How do you test your applet in JGrasp?
What does the init() method do?
What does the paint() method do?
How are colors represented in the computer?
What is the Graphics class? How do you use it in an applet?