2/4: Objects & Java Applets Objects: their nature –attributes & behaviors –inheritance –information hiding –classes: blueprints for objects Java Applets –what is an applet vs. an application? –where do applets work? –examples
Objects Objects have methods (behaviors or actions) and data (attributes) associated with them. Objects encapsulate these methods and data in OOP. Inheritance: You can create a new class that takes characteristics from an existing class, then define new characteristics in addition.
Java Applets An applet requires a browser to run. –An applet requires an HTML page to be displayed. –Applet tags are nested inside the HTML to load the class file. –Appletviewer: a “mini-browser” for viewing applets. Applets use different imported classes than applications. –EX: import javax.swing.JApplet; import java.awt.Graphics;
Sample Java Applet //java applet for 2/4 demonstration import javax.swing.JApplet; import java.awt.Graphics; public class Rectangles extends JApplet { public void paint ( Graphics g ) { super.paint ( g ); //call inherited paint meth. g.drawRect ( 20, 20, 120, 50 ); g.drawString ( "This is an Applet", 30, 40 ); g.fillArc ( 60, 60, 80, 220, 45, 125 ); } import statements class header method header statements: g.drawRect g.drawString g.fillArc
The HTML code To run Java applets, we need to embed them in a webpage. Save the webpage as whatever. Only Netscape 6 supports Java 2 (w/o help).
Java Applets JApplet is referred to as the superclass of Rectangles. –It is the class that Rectangles inherits most of its methods and objects from. “paint” is a method that comes from JApplet. –allows you to draw things on the applet window. “init” is a method that creates instances of classes.
To execute Java Applets Compile the Java file to make a class file. Create an HTML file to reference the class file. Save it in the same directory as the class file. Run the appletviewer (in the same directory as javac.exe & java.exe) and refer to the HTML file. A:\>c:\jdk1.3.1_01\bin\javac Rectangles.java A:\>c:\jdk1.3.1_01\bin\appletviewer viewer.html
Program of the Day: pg AdditionApplet.java –watch how an application can be ‘converted’ to work inside an applet Next time: –Algorithms –if & if/else control structures