510 likes | 526 Views
Learn how to create interactive Java applets for web browsers with step-by-step instructions and code examples. Understand the basics of HTML integration and applet execution.
E N D
System development with Java Instructors: Rina Zviel-Girshin Lecture 9 Rina Zviel-Girshin @ARC
Overview • Html • Applet • Graphics Rina Zviel-Girshin @ARC
Java and Applet • The reason people are excited about Java as more than just another OOP language is because it allows them to write interactive applets on the web. Rina Zviel-Girshin @ARC
Web Browser • In the browser environment the browser acts as an intermediate between the program and the operating system. • The JVM resides inside the browser. • The program can be simpler. • The program has to work in a graphical mode. • The program is called “Applet” (a small application). Rina Zviel-Girshin @ARC
Applets The program has to import two packages: • applet.Applet • awt The program (the class) has to extend the Applet class, using the following syntax: public class My extends Applet { // your code } Rina Zviel-Girshin @ARC
Basic applet code The final code looks like this: import java.awt.*; import java.applet.*; public class My extends Applet { // your code } Rina Zviel-Girshin @ARC
Stages of Writing and Executing • Create a java file. • Compile this file in the usual way and create .class file. • Applet can’t be run directly. • Applet has to be run in Browser and by the Browser. • Now you need to create an HTML file that will include your applet. Rina Zviel-Girshin @ARC
HelloWorld import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } } Rina Zviel-Girshin @ARC
Call to applet • The call to applet consist of: • the command APPLET • the name of the applet class • the dimensions of the panel in which the applet will run • Web browser will run your applet. Rina Zviel-Girshin @ARC
Example • Assuming the name of the applet class is HelloWorld.class the call to applet looks like this: <APPLET CODE = "HelloWorld.class" WIDTH = 150 HEIGHT= 50> </APPLET> Rina Zviel-Girshin @ARC
HTML The call to applet has to be in HTML file. The file can look as follows: <HTML><HEAD> <TITLE>Java applet test page</TITLE></HEAD> <BODY> <APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=50> </APPLET> </BODY></HTML> Rina Zviel-Girshin @ARC
Several worlds about HTML • HTML is the HyperText Markup Language. • HTML files are text files featuring semantically tagged elements. • HTML filenames are suffixed with .htm or .html. • Elements that are enclosed in angle brackets like <html>, <head>, and <title> are called tags. • Tags are case insensitive. <html> means the same thing as <HTML> as <Html> <HtMl>. Rina Zviel-Girshin @ARC
Several worlds about HTML • Most tags are matched with closing tags, and affect the text contained between them. • The closing tag syntax: </tagName> • Some tags have attributes. • An attribute is a name, followed by an = sign and the value. <applet code=“FileName.class” width=160> </applet> • To learn more about HTML: HTML Tutorial Rina Zviel-Girshin @ARC
Execution Assuming the file is called HelloWorld.html • The stages common to all, described above. • Open the file HelloWorld.html in the Browser. • The result is: HelloWorld.html Rina Zviel-Girshin @ARC
What is an applet • According to Sun "An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application....The Applet class provides a standard interface between applets and their environment." • Additional 4 definitions of the Applet: • A small application • A secure program that runs inside a web browser • A subclass of java.applet.Applet • An instance of a subclass of java.applet.Applet Rina Zviel-Girshin @ARC
Applet hierarchy Every applet is implemented by creating a subclass of the Applet class. java.lang.Object | +----java.awt.Component | +----java.awt.Container | +----java.awt.Panel | +----java.applet.Applet Rina Zviel-Girshin @ARC
Applet import declarations • The java.applet. and java.awt. prefixes tell the compiler which packages it should search for the Applet and Graphics classes. • The java.applet package contains classes that are essential to Java applets. • The java.awt package contains the most frequently used classes in the Abstract Window Toolkit (AWT), which provides the Java graphical user interface (GUI). Rina Zviel-Girshin @ARC
HelloWorld use predefined classes import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } } Inherits all functionality of the Applet the main function of our applet an instance of the predefined painter Graphics Rina Zviel-Girshin @ARC
Applet tag • <APPLET> references a source file that is not part of the HTML page. • This reference is code=“FileName.class” • But if your applet code resides somewhere other than the same directory as the page it lives on you use codebase attribute to specify its location. • The codebase attribute is a URL that points at the directory where the .class file is. • The code attribute is the name of the .class file itself. Rina Zviel-Girshin @ARC
Applet tag <APPLET CODE="HelloWorld.class" CODEBASE="http://www.yarden.ac.il/ip2" WIDTH=200 HEIGHT=200> </APPLET> • Browser would try to retrieve the applet from http://www.yarden.ac.il/ip2/HelloWorld.class regardless of where the HTML page was. • The formula for retrieving the applet from the URL: codebase + "/" + code. Rina Zviel-Girshin @ARC
Applet Lifecycle • The applet can go through a series of stages in it's lifecycle: • initial loading • starting to perform • suspending (e.g. when the focus shifts to another page) • destruction of the applet (closing the page) • For each stage there is a method called: • init() • start() • stop() • destroy() Rina Zviel-Girshin @ARC
Applet Lifecycle • The methods are two symmetrical pairs: • init - destroy • start - stop • In some cases we will wish to override the methods. • LifeCycle.html example. Rina Zviel-Girshin @ARC
LifeCycle import java.awt.*; import java.applet.*; public class LifeCycle extends Applet{ StringBuffer message; public void init() { message = new StringBuffer(); message.append("Initialised..."); } public void start() { message.append("Started..."); } public void paint(Graphics g) { g.drawString(message.toString(), 0, 25); } } Rina Zviel-Girshin @ARC
Applet Lifecycle Rina Zviel-Girshin @ARC
Finding an Applet's Size import java.applet.*; import java.awt.*; public class SizeApplet extends Applet { public void paint(Graphics g) { Dimension appletSize = this.getSize(); int appletHeight = appletSize.height; int appletWidth = appletSize.width; g.drawString("This applet is " + appletHeight + " pixels high by " + appletWidth + " pixels wide.", 15, appletHeight/2); } } Rina Zviel-Girshin @ARC
Applet's Size • Retrieving the applet size is straightforward with the getSize() method. • java.applet.Applet inherits this method from java.awt.Component. • getSize() returns a java.awt.Dimension object. • A Dimension object has two public int fields, height and width. • The output file SizeApplet.html Rina Zviel-Girshin @ARC
Passing Parameters to Applets • Parameters are passed to applets in name=value pairs in <PARAM> tags between the opening and closing APPLET tags. • Inside the applet, you read the values passed through the PARAM tags with the getParameter() method of the java.applet.Applet class. <APPLET code="DrawStringApplet.class" width=300 height=50> <PARAM name="Message" value=“Hello from Rina!"> </APPLET> Rina Zviel-Girshin @ARC
DrawStringApplet import java.applet.*; import java.awt.*; public class DrawStringApplet extends Applet { private String defaultMessage = "Hello!"; public void paint(Graphics g) { String inputFromPage = this.getParameter("Message"); if (inputFromPage == null) inputFromPage = defaultMessage; g.drawString(inputFromPage, 50, 25); } } Rina Zviel-Girshin @ARC
PARAM • An applet is not limited to one PARAM. • You can pass as many named PARAMs to an applet as you like. • An applet does not necessarily need to use all the PARAMs that are in the HTML. • The resulting output DrawStringApplet.html. Rina Zviel-Girshin @ARC
What applet can do? • An applet can: • Draw pictures on a web page • Create a new window and draw in it. • Play sounds. • Receive input from the user through the keyboard or the mouse. • Make a network connection to the server from which it came and can send to and receive arbitrary data from that server. Rina Zviel-Girshin @ARC
What applet can’t do? • Write data on any of the host's disks. • Read any data from the host's disks without the user's permission. • Delete files • Read from or write to arbitrary blocks of memory, even on a non-memory-protected operating system like the MacOS. All memory access is strictly controlled. Rina Zviel-Girshin @ARC
What applet can’t do? • Make a network connection to a host on the Internet other than the one from which it was downloaded. • Call the native API directly (though Java API calls may eventually lead back to native API calls). • Introduce a virus or trojan horse into the host system. • An applet is not supposed to be able to crash the host system. However in practice Java isn't quite stable enough to make this claim yet. Rina Zviel-Girshin @ARC
Drawing Shapes • Let's explore some of the methods of the Graphics class that draw shapes in more detail. • A shape can be filled or unfilled, depending on which method is invoked. • The method parameters specify coordinates and sizes. • Java coordinate system has the origin in the upper left corner. • Many shapes with curves, like an oval, are drawn by specifying its bounding box. Rina Zviel-Girshin @ARC
Graphics class • In Java all drawing takes place via a Graphics object. • The Graphics class provide methods for drawing a variety of graphical shapes: • lines • rectangles • ovals • circles • polygons Rina Zviel-Girshin @ARC
X Y g.drawLine (10, 20, 150, 45); or g.drawLine (150, 45, 10, 20); Drawing a Line 10 150 20 45 Rina Zviel-Girshin @ARC
Draw Line • Drawing straight lines with Java is easy. • Syntax: g.drawLine(xStart, yStart, xEnd, yEnd); • where (xStart, yStart) and (xEnd, yEnd) are the endpoints of your lines and g is the Graphics object you're drawing with. • DrawLine.html example. Rina Zviel-Girshin @ARC
DrawLine example import java.awt.*; import java.applet.*; public class DrawLine extends Applet { public void paint(Graphics g){ g.drawLine(50,20,50,150); g.drawLine(20,150,200,150); g.drawLine(0,0,200,200); } } Rina Zviel-Girshin @ARC
X 40 100 Y Drawing a Rectangle 50 20 g.drawRect (50, 20, 100, 40); Rina Zviel-Girshin @ARC
Drawing Rectangles • Three different types of rectangles can be drawn: • ordinary rectangles • rounded corners rectangles • three-dimensional rectangles with shaded border • Ordinary rectangles and rounded corners rectangles can be drawn in outline or filled with color form. Rina Zviel-Girshin @ARC
Rectangles • Ordinary rectangles g.drawRect(xStart, yStart, width, height); • Rounded corners rectangles g.drawRoundRect(xStart, yStart, width, height, arcWidth, arcHeight); • Three-dimensional rectangles with shaded border g.draw3DRect(xStart, yStart, width, height, raised); where fifth argument - raised - is boolean argument: true value means rectangle is raised, false value means rectangle is indented. Rina Zviel-Girshin @ARC
Rectangle example import java.awt.*; import java.applet.*; public class Rectangles extends Applet { public void paint(Graphics g) { g.drawRect(20,20,50,50); g.drawRoundRect(120,20,120,80,20,30); g.draw3DRect(20, 120, 50, 75, true); } } Rina Zviel-Girshin @ARC
Filling Rectangles • The drawRect() method draws an open rectangle, a box if you prefer. • If you want to draw a filled rectangle, use the fill…() method. • First you need to specify rectangle color g.setColor(Color) and then use one of the: g.fillRect(xStart, yStart, width, height); g.fillRoundRect(xStart, yStart, width, height, arcWidth, arcHeight); g.fill3DRect(xStart, yStart, width, height, raised); • FillRectangles.html example. Rina Zviel-Girshin @ARC
Filling Rectangles import java.awt.*; import java.applet.*; public class FillRectangles extends Applet { public void paint(Graphics g) { g.setColor(Color.blue); g.fillRect(20,20,50,50); g.setColor(Color.red); g.fillRoundRect(120,20,50,50,20,30); g.setColor(Color.lightGray); g.draw3DRect(20, 100, 50, 50, true); g.draw3DRect(120, 100, 50, 50, false); g.fill3DRect(80, 180, 50, 50, false); } } Rina Zviel-Girshin @ARC
Color • Color is a class in the AWT. • Individual colors like red or blue are instances of java.awt.Color: Color.red Color.blue • You create new colors using the same RGB triples. • Syntax Color pureRed = new Color(255, 0, 0) ; • Pure white is Color(255, 255, 255). • Values of first(red), second(green) and third (blue) arguments can move from 0-255. Rina Zviel-Girshin @ARC
Clear Rectangle • It is also possible to clear a rectangle that you've drawn. • Syntax is exactly what you'd expect: public abstract void clearRect(int x, int y, int width, int height) • Blink.html uses clearRect() to blink a rectangle on the screen. Rina Zviel-Girshin @ARC
Blink import java.applet.*; import java.awt.*; public class Blink extends Applet { public void paint(Graphics g) { int appletHeight = this.getSize().height; int appletWidth = this.getSize().width; int rheight=appletHeight/3; int rwidth=appletWidth/3; int rectTop = (appletHeight - rectHeight)/2; int rectLeft = (appletWidth - rectWidth)/2; for (int i=0; i < 1000; i++) { g.fillRect(rectLeft, rectTop, rwidth-1, rheight-1); g.clearRect(rectLeft, rectTop, rectWidth-1, rectHeight-1); } }} Rina Zviel-Girshin @ARC
X 80 50 Y Drawing an Oval 175 20 bounding rectangle g.drawOval (175, 20, 50, 80); Rina Zviel-Girshin @ARC
Ovals • Java has methods to draw outlined and filled ovals. g.drawOval(xStart, yStart, width, height); g.fillOval(xStart, yStart, width, height); • where width and height are “bounded box” properties. • The oval is drawn as large as it can be to touch the “bounded box”’s edges at their centers. • Ovals.html example. Rina Zviel-Girshin @ARC
Oval example import java.awt.*; import java.applet.Applet; public class Ovals extends Applet { public void paint(Graphics g) { int left = 5; int top = 5; // method that outputs series of ovals drawFilledOvals(g, left, top, this.size().width-10, this.size().height-10); } Rina Zviel-Girshin @ARC
Oval example public void drawFilledOvals(Graphics g, int x, int y, int w, int h) { g.setColor(Color.blue); while (h > 0) { g.fillOval(x, y, w, h); x += 10; y += 10; w -= 20; h -= 20; if (g.getColor() == Color.white) g.setColor(Color.blue); else g.setColor(Color.white); } } }//end of class Rina Zviel-Girshin @ARC