190 likes | 288 Vues
Learn the basics of Java applets, including structure, methods, and benefits. Explore how to define, run, and customize applets for interactive web content. Practice drawing graphics with applets in this hands-on lesson.
E N D
Lesson: Intro to Applets ICS3M
Learning Objectives • What is an applet? • Structure of an Applet • 6 standard methods of applet
2 Kinds of Java Program • Application • Has a main method • Text based • Applet • No main method • Must inherit from the Applet class. • GUI based (using frames)
What is an Applet? • An applet is a Java program that can be sent over the Internet and run under web browsers. Show Jag Game Demo
Benefits of Applets • Provide access to GUI features of Java. • They are portable. (i.e. can be run on many different computer platforms)
Structure of an Applet • All applets are classes that inherit from the class Applet. • Each applet must import the Applet class with the statement • import java.applet.Applet;
Defining an Applet import java.applet.Applet; import java.awt.Graphics; public class class-name extendsApplet { // your code } • Every applet must import the Applet and Graphics class. • Every applet must define a subclass of the Applet class.
Applet Methods • Applet class has a number of methods • They are often overridden by new versions of the methods in the new subclass applet.
Notes • We will only focused on overloading init, paint, and action methods. • Others will have the default behavior inherited from the Applet class, which in fact do nothing. • Applets can contain other user-defined methods which are called by any of the standard methods.
Applets • Every applet must implement at least one of the following methods: • public void init( ) • public void start ( ) • public void paint (Graphics g) Q: Where can you find the other method signature?
Running an Applet <html> <head> <title> The ExampleApplet applet </title> </head> <body> <h2> Here is the ExampleApplet applet </h2> <hr> <applet code="ExampleApplet.class" width="300" height="200"> </applet> <hr> </body> </html>
Example: HelloWorld • The Graphics object passed into paint method represents the applet’s onscreen drawing context. import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString(“Hello world!”, 50, 25); } }
Drawing Screen X ( x, y ) ( 0, 0 ) Y
drawString(“Hello World”, 10, 20) ( x, y ) ( 0, 0 ) Hello World Y
Graphic Class • clearRect • drawLine • drawOval • drawRect • drawString • fillRect • setColor • Look up the method signatures for the above methods and use it do complete the House assignment.
Class Exercise • Use methods in Graphics class, write an applet that draws a simple house with a roof and a window as shown below. Your applet must say “My House” at the base of the roof. • Demo “MyHouse” • Demo “Rhyme” • Demo “CircleBlocks” My House