Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 9
Rina Overview Html Applet Graphics
Rina 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 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 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 Basic applet code The final code looks like this: import java.awt.*; import java.applet.*; public class My extends Applet { // your code }
Rina 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 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 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 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>
Rina HTML The call to applet has to be in HTML file. The file can look as follows: Java applet test page <APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=50>
Rina 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,, and are called tags. Tags are case insensitive. means the same thing as as.
Rina Several worlds about HTML Most tags are matched with closing tags, and affect the text contained between them. The closing tag syntax: Some tags have attributes. An attribute is a name, followed by an = sign and the value. To learn more about HTML: HTML TutorialHTML Tutorial
Rina Execution Assuming the file is called HelloWorld.html 1.The stages common to all, described above. 2.Open the file HelloWorld.html in the Browser. 3.The result is: HelloWorld.htmlHelloWorld.html
Rina 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 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 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 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); } use predefined classes Inherits all functionality of the Applet the main function of our applet an instance of the predefined painter Graphics
Rina Applet tag 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 Applet tag Browser would try to retrieve the applet from regardless of where the HTML page was. The formula for retrieving the applet from the URL: codebase + "/" + code.
Rina 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 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.LifeCycle.html
Rina 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 Applet Lifecycle MethodWhen CalledHow manyDescription initupon loading the applet onceinitializations,resource allocation,operations needed once for the lifetime of the applet startafter the init, and each time user returns to the page any number of times updating, calls method update(), which calls paint() to update the screen output, awakens suspended operations stopeach time user leaves the page any number of times suspension of operation destroyupon closing the applet (the page) oncedestruction, release of resources
Rina 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 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.htmlSizeApplet.html
Rina Passing Parameters to Applets Parameters are passed to applets in name=value pairs in 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.
Rina 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 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. DrawStringApplet.html
Rina 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 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 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 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 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 Drawing a Line X Y g.drawLine (10, 20, 150, 45); g.drawLine (150, 45, 10, 20); or
Rina 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.DrawLine.html
Rina 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 Drawing a Rectangle X Y g.drawRect (50, 20, 100, 40);
Rina 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 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 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 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.FillRectangles.html
Rina 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 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
Rina 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.Blink.html
Rina 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 Drawing an Oval X Y g.drawOval (175, 20, 50, 80); boundingrectangle
Rina 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.Ovals.html
Rina 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 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 Any Questions?