Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fundamental of Java Programming

Similar presentations


Presentation on theme: "Fundamental of Java Programming"— Presentation transcript:

1 Fundamental of Java Programming
(630002) Unit – 5 Applets

2 Introduction An applet is a program that can be reference by the HTML source code of a web page. It is dynamically downloaded from a web server to a browser. The applet then executes within the environment provided by the browser. Alternatively we may use a tool such as the appletviewer to run it. It is important to note that downloading code from the internet and executing it on your computer is inherently dangerous.

3 Introduction Therefore applets don’t have same capacity as java applications. E.g. applets are normally not allowed to read or write to your local disk. This would be risky because they could accidentally or maliciously destroy any data stored on that device. They cannot execute any native code. Similarly starting other applications on the user’s machine is prohibited.

4 Introduction Also remember that our applet can open a socket connection back to the host from which it was downloaded, but not to any other host. The reason is but obvious the security of the data. E.g. if in one applet we program that it can open a connection with any terminal of the organization then hacker can steal the data of the organization which is very harmful to any organization or individual.

5 First Java Applet As we are at the starting point of applets let’s create our first applet and understand it line by line. ex\ex95.java ex\first.html ex\ex96.java The first and second lines import the java.applet.Applet and java.awt.Graphics classes. Remember that Applet class is the super class of all applets. The Graphics class is provided by the Abstract Window Toolkit (AWT).

6 First Java Applet Next four lines defines a Java comment. Within that comment is HyperText Markup Language(HTML) source code. The applet tag specifies which class contains the code for this applet. It also defines the width and height in pixels of the display area. Remember that here the given HTML is not a part of java code but it is just for the understanding of appletviewer.

7 First Java Applet The next line declares out first applet (ex95 / ex96) which extends Applet. Each applet that you create must extends this class. Next a method called paint() is defined. This method is responsible for generating the output of the applet. It accepts a Graphics object as its one argument. The paint method is automatically invoked whenever the applet needs to be displayed.

8 First Java Applet The actual output of the string is done by calling the drawString() method of the Graphics object. Its first argument is String to be displayed. The second and third arguments are the x and y coordinates at which to begin the string. Remember that here the top-left corner of the applet is always the origin at 0,0. the x coordinates increase as you move to the right and the y coordinates increase as you move down.

9 First Java Applet The appletviewer tool is one of the tools included in the Java Developer Kit (JDK). It executes an applet by using the HTML source code included in the comment at the top of the Java source file. Exercise : Play with the string and various arguments of drawString() method and see the different outputs in your applet.

10 The Life Cycle of an Applet
We already know that a Java application begins execution at the main() method of a class. However, an applet executes within an environment provided by a web browser or a tool such as the appletviewer. Therefore it does not have a main() method. Instead there are four methods that are called during the life cycle of an applet. They are : init() start() stop() destroy()

11 The Life Cycle of an Applet
The init() method is called only when the applet begins execution. It is common to place code here that needs to be executed only once, such as reading parameters that are defined in the HTML file. The start method is executed after the init() method complete execution. In addition this method is called by the applet viewer or web browser to resume execution of the applet.

12 The Life Cycle of an Applet
The stop() method is called by the applet viewer or web browser to suspend execution of an applet. Therefore the start() and stop() methods may be called multiple times during the life cycle of the applet. We will see in the next example that stop() method is invoked when the applet viewer is minimized and start() method is called when the applet viewer is later maximized.

13 The Life Cycle of an Applet
Finally the destroy() method is called by the applet viewer or web browser before the applet is terminated. Remember that the stop() method is invoked before destroy(). ex\applet\lifeCycleApplet.java ex\applet\lifeCycleApplet.html

14 The Graphics Class The graphics object encapsulates a set of methods that can perform graphics output. Specifically, it allows you to draw lines, ovals, rectangles, strings, images, characters and arcs. Various methods of the graphics class are as follows:

15 The Graphics Class Various methods of the class are as follows :
Usage void drawArc(int x, int y, int w, int h, int deg0, int deg1) Draws an arc between deg0 and deg1. the center of the arc is the center of a rectangle with upper-left corner at coordinates x and y, width w and height h. Remember that zero degree is at position 3 pm on a watch. The angle increases in a counterclockwise direction. void drawImage(Image img, int x, int y) Draws the image img so its upper-left corner is at x,y void drawLine(int x0, int y0, int x1, int y1) Draws a line between x0,y0 and x1, y1. void drawOval(int x, int y, int w, int h) Draws an oval . The center of the shape is center of a rectangle with upper-left corner at coordinates x and y, width w and height h.

16 The Graphics Class Various methods of the class are as follows :
Usage void drawPolygon(int x[], int y[], int n) Draws a polygon with n corners. The coordinates are given by the elements of x and y. The first and last point are automatically connected. void drawPolyline(int x[], int y[], int n) Draws a polyline with n corners. The coordinates are given by the elements of x and y. The first and last point are not automatically connected. void drawRect(int x, int y, int w, int h) Draws a rectangle with upper-left corner at coordinates x and y and width w, and height h. void drawString(String str, int x, int y) Draws str at location x,y. void fillArc(int x, int y, int w, int h, int deg0, int deg1) Draws a filled arc with given parameters – works same as drawArc method

17 The Graphics Class Various methods of the class are as follows :
Usage void fillOval(int x, int y, int w, int h) Draws a filled oval. Works same as drawOval method void fillePolygon(int x[], int y[], int n) Draws a filled polygon with n corners. Works same as drawPolygon method void fillRect(int x, int y, int w, int h) Draws a filled rectangle. Works same as drawRect method Color getColor() Gets the color of the current object Font getFont() Gets the font of the current object FontMetrics getFontMetrics() Gets the font metrics of the current object. ex\applet\drawLineApplet.java ex\applet\drawArcApplet.java ex\applet\drawPolygonApplet.java

18 The Graphics Class Exercise :
Write an applet that draws a rectangle. The dimensions of the applet should be 500 x 300 pixels. The rectangle should be centered in the applet and have a width and height of 300 and 200 pixels, respectively. Write an applet that draws a circle. The dimension of the applet should be 500 x 300 pixels. The circle should be centered in the applet and have a radius of 100 pixels.

19 Use of Colors The java.awt.Color class is used to work with colors. Each instance of this class represents a particular color. This section demonstrates how to draw colored strings, lines and shapes in an applet. It is possible to fill a shape such as an oval or rectangle with a color. This class has three consturctors. Color(int red, int green, int blue) Color(int rgb) Color(float r, float g, float b)

20 Use of Colors Here red, green and blue are int values that range between 0 and 255 (inclusive). The argument rgb contains encoding of a color in which the read, green and blue components are specified in bits 23 to 16, 15 to 8 and 7 to 0 respectively. Finally r,g and b are float values that range between 0.0 and 1.0f inclusive. The Color class also defines several constants that represent specific colors. These are black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white and yellow

21 Use of Colors Various methods of the class are as follows : Method
Usage Color brighter() Returns the brighter version of the current color object Color darker() Returns the darker version of the current color object boolean equals(Object o) Returns true if the current object and obj represents the same color value. int getBlue() Returns the blue component of the current object int getGreen() Returns the green component of the current object int getRGB() Retrns an int encoding of the current object int getRed() Returns the red component of the current object.

22 Use of Colors ex\applet\blueString.java ex\applet\colorApplet.java
ex\applet\ColorVertBars.java Exercise : Modify the above colorbars example to draw horizontal color bars. Draw a happy face with colors of your choice Draw Indian national flag with required colors. Draw an ice-cream cone with colors.

23 Displaying of Text We already know that drawString() method of Graphics class is used for displaying the text. A font determines the size and appearance of characters in a string. Information about a font is encapsulated by the java.awt.Font class. This class has only one constructor : Font (String name,int style, int ps) Here the name identifies the font. The style may be constant like BOLD, ITALIC or PLAIN. The ps will represent the point size of the font.

24 Displaying of Text After the font has been created we can use it in our graphics context. This is possible by calling the setFont() method of the Graphics class as follows : void setFont(Font f) Here f is the object of Font class. Now any string with that get the output with drawString() will be displayed with that font.

25 Displaying of Text The java.awt.FontMetrics class allows us to get several metrics about the size of a font. In addition we can also determine the size of a string that is displayed in that font. Remember that : All these values will be in pixels. This class has one constructor : FontMetrics(Font f) Here f is the object of Font Class for which we need the metrics.

26 Displaying of Text Various methods of the class are as follows :
Usage int charWidth(char c) Returns the width of c int getAscent() Returns the ascent (Value above the given baseline) int getDescent() Returns the descent (value below the given baseline) int getHeight() Returns the height int getLeading() Returns the leading int stringWidth(String str) Returns the width of str. ex\applet\FontDemo.java ex\applet\FontMetricsDemo.java

27 Use of Applet Dimensions
Till now we have seen that how to display strings, lines and shapes in an applet by using various methods of Graphics class. In all that methods we explicitly specify the output position. The main problem in that was when we resize the applet then our output will become improper. Now we will see that how we can do program in such a way that even if our applet size goes changed then also the output remains same.

28 Use of Applet Dimensions
For example, if we want to display a circle at the center of an applet. If the applet is resized, the circle remains positioned at its center. The getSize() method is used to determine the size of an applet. It has following form : Dimension getSize() A Dimension object is useful to manipulate the height and width. ex\applet\DimensionCircle.java ex\applet\DimensionString.java

29 Use of Applet Dimensions
Exercise : Write an applet that draws two lines in its display area. The first line begins at the upper-left corner and extends to the lower-right corner. The second line begins at the upper-right corner and extends to the lower-left corner. The applet should remain as it is even after resize.

30 The Applet Class All the applets extends the java.applet.Applet class. Here we see the inheritance relationship among the superclasses of Applet java.lang.Object java.awt.Component java.awt.Container java.awt.Panel java.applet.Applet

31 The Component Class The abstract Component class represents many of the different types of elements that you can include in a graphical user interface. Some of them are : buttons, choices, lists, scrollbars etc. There are more than 100 methods provided by this class but we take some of them as per our requirements.

32 The Component Class Various methods of the class are as follows :
Usage Image createImage(int w, int h) Returns an image object of dimenstion width and height Font getFont() Returns the current font FontMetrics getFontMetrics(Font f) Returns the font metrics of given font Color getForeground() Returns the foreground color Dimension getSize() Returns the size of the component Public void paint(Graphics g) Paints the component on g void repaint() Requests the JVM to schedule a call to update() void setBackground(Color c) Sets the background color with c void setFont(Font f) Sets the font to f void setForeground(Color c) Sets the foreground color with c public void update(Graphics g) Fills the component with its background color and calls paint()

33 The Applet Class Various methods of the class are as follows :
Usage void distroy() Destroys the applet AppletContext getAppletContext() Returns the Applet Context Image getImage(URL u) Returns an image object for the image at u String getParameter(String pname) Returns the value of parameter pname void init() Initializes the applet void showStatus() Displyes str on the status line void start() Starts this applet void stop() Stops this applet ex\applet\background_foreground.java ex\applet\parameterApplet.java

34 The Applet Class Exercise :
Write an applet that draws an ellipse. Accept two parameters that are the sizes of the two axes in pixels. Center the ellipse in the applet. Write an applet that sets the background color to cyan and draws a circle of radius 50 pixels centered in the middle of the applet. The dimension of the applet should be 120 x 120 pixels. Fill the circle with a magenta color.

35 The AppletContext interface
The java.applet.AppletContext interface defines methods that allows an applet to interect with the context (environment) in which it is executing. Various methods are as follows : Method Usage Applet getApplet(String appname) Returns the applet named appname Enumeration getApplets() Returns an enumeration of the applets in the current context void showDocument(Url u, String target) Retrieves the document at url and displays it in target void showStatus(String s) Displays s in the status line ex\applet\showDocumentApplet.java ex\applet\showDimensionInStatus.java

36 The AppletContext interface
Exercise : Write an applet that uses showStatus() to display the name of the current month, day and year. Also display this information in applet.

37 Use of Images We can display various images into our applet. For that we need to use Image class. We also need to use getImage() method of applet class which returns a java.awt.Image object. Image getImage(URL u) Image getImage(Url , String filename) Here the first fom accepts one argument that is absolute URL to identify the image resource. The second form uses two arguments, in which first argument is URL to identify the base location from where the image file can be downloaded and second is the name of that file.

38 Use of Images The drawImage() method of Graphics class initiates the downloading of an image and displayes subsets of the image data as it is like : boolean drawImage(Image img, int x, int y, ImageObserver io) Here the img is reference to the Image object, the coordinates will be decided by the x and y and the last parameter is an object of ImageObserver interface. We will use our applet itself as a ImageObserver. ex\applet\drawImageApplet.java

39 Use of Threads in Applets
In our earlier discussion we have seen the use of threads in simple applications. Now we can use threads in applets to display some kind of animation. The most important thing that we have to remember here is Threads must need to update the display after a particular period of time. You cannot invoke the paint method directly to update the display. The reason is that the JVM schedules a number of important tasks.

40 Use of Threads in Applets
Updating a display is only one of these. Garbage collection, I / O and thread management are others. Therefore your applet must invoke the repaint() method to request an update of the applet display. When the JVM determines that it is appropriate to perform this work at that time it will call the update() method. The default implementation of the update() method will clears the applet display with the background color and then invokes the paint().

41 Use of Threads in Applets
ex\applet\counterApplet.java ex\applet\randomDotsApplet.java Exercise : Write an applet that moves a 5x5 pixel filled rectangle along a circle with 100 pixels in radius and located at the center of the applet. Modify the dots example so that the points are connected by the lines. When a new dot is added to the applet, draw a line between it and the last dot.

42 Use of Threads in Applets
Exercise : Write an applet to display happy face with blinking eyes Write an applet in which you have to display a line moving upward / downward 10 times Create an applet make a traffic light and color of light changes after fix interval of time. Create an applet, display a name with different color after some seconds.

43 Use of Double Buffering
When we update our display with the use of multithreading at that time we have called update() method. Now in that method it will clear the entire display area with the background color. The paint() method is then called to generate the output of the applet. This may create sometime the problem of annoying flicker in the display. It occurs because the screen is frequently being cleared with one color and drawn with a different color.

44 Use of Double Buffering
Now, we will override the update() method so that the display is not cleared. Instead, it simply invokes the paint() method. The actual mechanism of paint() is, all drawing operations are done to a buffer and then that buffer will be copied to the screen. A background buffer can be created via the createImage() method of Component class like Image createImage(int w, int h) Here w and h specify the size of buffer. ex\applet\NoDoubleBufferApplet.java ex\applet\DoubleBufferApplet.java

45 Use of Double Buffering
Exercise : Write an applet that presents a message in its display area. The applet begins by displaying the first character of the message, waiting for t1 milliseconds, adding the second character, waiting for t1 milliseconds, adding the third character and so on. This operation continue until all the characters of the messages are visible. When all characters have been presented, the entire message remains visible for t2 milliseconds. Then the display area is cleared and the cycle repeats.

46 Use of Double Buffering
Exercise : Write an applet that simulates an analog clock. Write an applet that simulates a digital clock. Create a Marquee i.e, moving text.

47 Thank You


Download ppt "Fundamental of Java Programming"

Similar presentations


Ads by Google