0% found this document useful (0 votes)
13 views24 pages

Unit 05 Java Applets and Graphics Programming

Uploaded by

Harish Khojare
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
13 views24 pages

Unit 05 Java Applets and Graphics Programming

Uploaded by

Harish Khojare
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 24

Unit 05 Java Applets and Graphics Programming

What is an Applet ?
 An applet is a special kind of Java program that runs in a Java enabled browser.
 Applet is typically embedded inside a web page (HTML document) and runs in the browser.
 Applets are small Java applications that can be accessed on an Internet server, transported over
Internet, and can be automatically installed and run as apart of a web document
 The applet can produce a graphical user interface.
 Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.

Advantage of Applet
1. It works at client side so less response time.
2. Secured
3. It can be executed by browsers running under many platforms, including Linux, Windows, Mac Os
etc.
Drawback of Applet
Plugin is required at client browser to execute applet.
Hierarchy of Applet
Java Applet vs Java Application

Java Application Java Applet


Java Applications are the stand-alone Java Applets are small Java programs
programs which can be executed which are designed to exist within HTML
independently web document
Java Applications must have main() Java Applets do not need main() for
method for them to execute execution
Java Applets cannot run independently and
Java Applications just needs the JRE
require API’s
Java Applications do not need to extend Java Applets must extend
any class unless required java.applet.Applet class
Java Applications can execute codes from
Java Applets Applications cannot do so
the local system

Java Applications has access to all the Java Applets has access only to the
resources available in your system browser-specific services
Lifecycle of Java Applet

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed
Lifecycle of Java Applet
1. public void init(): This is the very first method to be invoked during the life cycle of an applet. In this
method, the variable that will be used further in the applet is initialized. One thing you must note here
is that this method can be invoked only once per applet life cycle.
2. public void start(): This is the second method that is invoked just after the init() method is called by
the browser. Each time a user revisits the web page containing the applet, start() method is invoked
and the applet is started.
3. public void stop(): This method is invoked whenever a user leaves the web page containing applet.
In other words, the stop() method is used to suspend the threads which are not required when the
applet is in the background or is not visible on the screen. These can be easily resumed using the start()
method.
4. public void destroy(): Finally, we have the destroy() method which is invoked in order to completely
remove an applet from the memory. This method is invoked only once per applet

One more method that is mostly used along with the above four is paint().

5. public void paint(Graphics g): This method is invoked whenever an applet needs to be redrawn or
repainted in the browser, irrespective of the cause. The paint() method takes one Graphic object as a
parameter that contains the graphics context in which the applet is being executed. Also, this method is
invoked each time output is expected from the applet.
Simple example of Applet by html file:

How to run an Applet?


There are two ways to run an applet
//First.java 1. By html file.
2. By appletViewer tool (for testing purpose).
import java.applet.Applet;
import java.awt.Graphics; To execute the applet by html file, create an applet and
compile it. After that create an html file and place the
public class First extends Applet{
applet code in html file. Now click the html file.
public void paint(Graphics g){
myapplet.html
g.drawString("welcome",150,150);
<html>
} <body>
<applet code="First.class" width="300" height="300">
}
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}

}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in
command prompt:

c:\>javac First.java
c:\>appletviewer First.java
Parameter in Applet

 We can get any information from the HTML file as a parameter.


 For this purpose, Applet class provides a method named getParameter().

Syntax:
public String getParameter(String parameterName)

import java.applet.Applet;
import java.awt.Graphics; myapplet.html
public class UseParam extends Applet{ <html>
public void paint(Graphics g){ <body>
String str=getParameter("msg"); <applet code="UseParam.class" width="300"
g.drawString(str,50, 50); height="300">
} <param name="msg" value="Welcome to applet">

</applet>
</body>
</html>
Graphics in Applet
java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified
width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the
default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the
specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default
color and specified width and height.
6. public abstract void setFont(Font font): is used to set the graphics current font to the specified
font.
Graphics in Applet

7) public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).
8) public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used
draw the specified image.
9) public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used draw a circular or elliptical arc.
10) public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used to fill a circular or elliptical arc.
11) public abstract void setColor(Color c): is used to set the graphics current color to the specified
color.
Example of Graphics in applet:
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);

g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
/* <applet code=" GraphicsDemo.class" width="300" height="300">
</applet> */
Working with colors

The AWT color system allows us to specify any color that we want.

• Color is encapsulated by the Color class.

• The Color class defines several constants (for example, Color.black, Color.red)
to specify a number of common colors.

• We can also create our own colors, using one of the color constructors.

Three commonly used forms are shown here:


1. Color(int red, int green, int blue)
2. Color(int rgbValue)
3. Color(float red, float green, float blue)
Working with colors

By default, graphics objects are drawn in the current foreground color.

• We can change this color by calling the Graphics method setColor( )

void setColor(Color newColor)

Here, newColor specifies the new drawing color.

• We can obtain the current color by calling getColor( ), shown here:

Color getColor( )
A color demonstration of Applet
import java.awt.*;
import java.applet.*;
/*<applet code = “colorDemo.class" width = 400
height = 400>
</applet>*/
public class colorDemo extends Applet
{
public void paint(Graphics g)
{
Color c1= new Color (100,255,100);
g.setColor(c1);
g. drawRect (0,100,100,0);
g.setColor(Color.red);
g,drawString(“Rectangle", 90,150);} }
A program to demonstrate setBackground() and setForeground() color for Applet

import java.awt.*;
import java.applet.*;
public class backfore extends Applet {
public void paint(Graphics g) {
setBackground(Color.yellow);
g.setColor(Color.red);
g.drawString("Demo of background and
Foreground color",10,50); } }
/*
/*<applet code = “backfore.class" width =
300 height = 50>
</applet>*/
*/
Java Controls

The AWT supports the following types of controls:


 Labels
 Push buttons
 Check boxes
 Choice lists
 Lists
 Scroll bars
 Text editing
Adding control in applet

To do this,
1. First create an instance of the desired control
2. Add the control to a window by calling add( ), which is defined by Container.

The add( ) method has several forms, Component add(Component compObj);

Here, compObj is an instance of the control that we want to add.


A reference to compObj is returned.

Once a control has been added, it will automatically be visible whenever its parent window is
displayed.
Adding Controls -Label

1. A label is an object of type Label, and it contains a string, which it displays.

2. Labels are passive controls that do not support any interaction with the user.
3. Label defines the following constructors:

Label( ) - The first version creates a blank label.


Label(String str)- The second version creates a label that contains the string specified by str. This
string is left-justified.
Label(String str, int how)- The third version creates a label that contains the string specified by str
using the alignment specified by how. The value of how must be one of these three constants:
Label.LEFT, Label.RIGHT, or Label.CENTER. ExampleLabel one = new Label("One"); // instance
created
add(one); //control added in applet window
Example – Adding Label control

import java.awt.*;
import java.applet.*;
/* <applet code="LabelDemo" width=300 height=200> </applet> */
public class LabelDemo extends Applet
{ public void init()
{ Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three"); // add labels to applet window
add(one);
add(two);
add(three); } }
Font Class
The Font class defines these variables:-

Variable Meaning

protected String name Name of the font


protected int size Size of the font in points
protected int style Font style

There are four styles for displaying fonts in Java: plain, bold, italic, and bold italic. Three class constants are
used to represent font styles:

public static final int BOLD:The BOLD constant represents a boldface font.
public static final int ITALIC:The ITALIC constant represents an italic font.
public static final int PLAIN:The PLAIN constant represents a plain or normal font.

The combination BOLD/ITALIC represents a bold italic font. PLAIN combined with either BOLD or ITALIC
represents bold or italic, respectively.

public Font (String name, int style, int size):There is a single constructor for Font. It requires a name, style, and
size. name argument represents the name of the font to create.
Font Class
1. public String getName ():The getName() method returns the font's logical name. This is the name
that is passed to the constructor when the instance of the Font is created.

2. public String getFamily ():The getFamily() method returns the name of the font family to which
the invoking font belongs.

3. public int getStyle ():The getStyle() method returns the current style of the invoking font as an
integer. It is convenient to use the isPlain(), isBold(), and isItalic() methods to find out the current
style.

boolean isBold( )------> Returns true if the font includes the BOLD style value. Otherwise, false is
returned.
boolean isItalic( )------> Returns true if the font includes the ITALIC style value. Otherwise, false is
returned.
boolean isPlain( )------> Returns true if the font includes the PLAIN style value. Otherwise, false is
returned.

4. public int getSize ():The getSize() method returns the point size of the invoking font, as set by the
size parameter in the constructor. The actual displayed size may be different.
Font Class

5. public static Font getFont(String property):Returns the font associated with the system property
specified by property. Null is returned if property does not exist.

6. public static Font getFont(String property, Font defaultFont):- Returns the font associated with
the system property specified by property. The font specified by defaultFont is returned if
property does not exist.

7.public int hashCode ():The hashCode() method returns a hash code for the font. This hash code
is used whenever a Font object is used as the key in a Hashtable.

8. public boolean equals (Object o):The equals() method overrides the equals() method of Object to
define equality for two Font objects. Two Font objects are equal if their size, style, and name are
equal.

9. public String toString ():The toString() method of Font returns a string showing the current
family, name, style, and size settings
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE ="FontClass.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class FontClass extends java.applet.Applet
{
Font f;
String m;
public void init()
{
f=new Font("Arial",Font.ITALIC,20);
m="Welcome to Java";
setFont(f);
}
public void paint(Graphics g)
{
Color c=new Color(0,255,0);
g.setColor(c);
g.drawString(m,4,20);
}
}
Thank You

You might also like