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

Unit III

JAVA

Uploaded by

Meera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views24 pages

Unit III

JAVA

Uploaded by

Meera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

******************************************************************************

*
Chapter 14 Applets
***************************************************************************
****
14.1 Introduction
 An Applet is a Java program that runs in a Web browser.
 Applets are small Java programs that are primarily used for Internet computing. They
can be transported over the Internet from one computer to another and runs using the
Appletviewer or any Web Browser that supports Java.
 An Applet, like any other application program, can do many things for us. It can perform
arithmetic operations, display graphics, play sounds, accept user input, create animation,
and play interactive games.
 An Applet is embedded in an HTML page using the APPLET tag and hosted on
a web server.
 Applets are used to make the web site more dynamic and entertaining.
Local and Remote Applets
 An applet developed locally and stored in a local system is known as a local applet.
When a Web page is trying to find a local applet, it does not need to use the Internet, and
therefore the local system does not require the Internet connection. It simply searches the
directories in the local system and locates and loads the specified applet.
 A remote applet is that which is developed by someone else and stored on a
computer connected to the Internet. If our system is connected to the Internet, we can
download the remote applet onto our system via the Internet and run it.
 In order to locate and load a remote applet, we must know the applet’s address on the
Web. This address is known as Uniform Resource Locator (URL) and must be specified
in the applet’s HTML document as the value of the CODEBASE attribute.
Example:

CODEBASE=http://www.netserve.com/applets
In the case of local applets, CODEBASE may be absent or may specify a local directory.
14.2 Differences between Applets and Applications
Applet Application
Applets are small Java programs that are Applications are stand-alone programs that can be
designed to be included with the HTML executed independently without using the web
web document. They require a Java-enabled browser.
web browser for execution.
Applet does not require a main function for Application program requires a main function
its execution. for its execution.
Applets can't read from or write to the files An application can read from or write to the files
on the local computer. on the local computer.
An Applet requires Graphical User Interface An application doesn't require Graphical User
(GUI). Interface (GUI).
Applets can't communicate with other The application can communicate with other
servers on the network. servers on the network.
Applets can only access the browser Applications can access all kinds of resources
specific services. They don’t have access to available on the system.
the local system.
An applet program is needed to perform An application program is needed to perform
small tasks or the part of it. some task directly for the user.

14.3 Applet Basics


 Applet is a Java program that can be embedded into a web page.
 It runs inside the web browser and works at client side.
 The applet code uses the services of the two classes, namely, Applet and Graphics from
the Java class library.
 The Applet class provides the necessary support for applets.
 The Applet class is contained in the java.applet package. Thus, all applets must import
java.applet.
 Applets must also import java.awt.AWT stands for Abstract Window Toolkit.
 Applets are executed by either a Web browser or an applet viewer.
 Applet contains several methods that give us detailed control over the
execution of our applet.
Example:

/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/
 This comment contains an APPLET tag that will run an applet called MyApplet in a
window that is 200 pixels wide and 60 pixels high.
 An applet code will have a general format as shown below:
import java.awt.*;
import java.applet.*;
………………….
………………….
public class appletclassnaame extends Applet
{
…………………..
…………………..
public void paint(Graphics G)
{
………………….
…………………. // Applet operations code
}
…………………..
…………………..
}
The appletclassname is the main class for the applet. When the applet is loaded, Java
creates an instance of the class, and then a series of Applet class methods are called on
that instance to execute the code.
Example:

// Simple Applet program


import java.awt.*;
import java.applet.*;
public class HelloWorldApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Hello World,10,100);
}
}
/*<applet code="HelloWorldApplet.class" height=300 width-200>
</applet>/*
Output:
Hello World
14.4 The Applet Class
 The Applet class defines the methods shown in Table 14.1.
 Applet provides all necessary support for applet execution, such as starting and stopping.
It also provides methods that load and display images, and methods that load and play
audio clips.
 Applet extends the AWT class Panel. In turn, Panel extends Container, which extends
Component. These classes provide support for Java’s window-based, graphical interface.
Thus, Applet provides all of the necessary support for window-based activities.
Method Description

void destroy() Called by the browser just before an applet is


terminated. Our applet will override this method if it needs
to perform any cleanup prior to its destruction.
AccessibleContext Returns the accessibility context for the invoking object.
getAccessibleContext()
AppletContext getAppletContext() Returns the context associated with the applet.
String getAppletInfo() Returns a string that describes the applet.
AudioClip getAudioClip(URL url) Returns an AudioClip object that encapsulates the audio
clip found at the location specified by url.
AudioClip getAudioClip(URL url, Returns an AudioClip object that encapsulates the audio
String clipName) clip found at the location specified by url and having the
name specified by clipName.
URL getCodeBase() Returns the URL associated with the invoking applet.
URL getDocumentBase() Returns the URL of the HTML document that invokes the
applet.
Image getImage(URL url) Returns an Image object that encapsulates the image found
at the location specified by url.
Image getImage(URL url, Returns an Image object that encapsulates the image found
String imageName) at the location specified by url and having the name
specified by imageName.
Locale getLocale() Returns a Locale object that is used by various locale-
sensitive classes and methods.
String getParameter(String Returns the parameter associated with paramName. null is
paramName) returned if the specified parameter is not found.
String[][] getParameterInfo() Returns a String table that describes the parameters
recognized by the applet. Each entry in the table must
consist of three strings that contain the name of the
parameter, a description of its type and/or range, and an
explanation of its purpose.
void init() Called when an applet begins execution. It is the first
method called for any applet.
boolean isActive() Returns true if the applet has been started. It returns false if
the applet has been stopped.
static final AudioClip Returns an AudioClip object that encapsulates the audio
newAudioClip(URL url) clip found at the location specified by url. This method is
similar to getAudioClip() except that it is static and can be
executed without the need for an Applet object.
void play(URL url) If an audio clip is found at the location specified by url, the
clip is played.
void play(URL url, String clipName) If an audio clip is found at the location specified by url with
the name specified by clipName, the clip is played.
void resize(Dimension dim) Resizes the applet according to the dimensions specified by
dim. Dimension is a class stored inside java.awt. It
contains two integer fields: width and height.
void resize(int width, int height) Resizes the applet according to the dimensions specified by
width and height.
final void setStub(AppletStub stubObj) Makes stubObj the stub for the applet. This method is used
by the run-time system and is not usually called by our
applet. A stub is a small piece of code that provides the
linkage between our applet and the browser.
void showStatus(String str) Displays str in the status window of the browser or applet
viewer. If the browser does not support a status window,
then no action takes place.
void start() Called by the browser when an applet should start (or
resume) execution. It is automatically called after init()
when an applet first begins.
void stop() Called by the browser to suspend execution of the applet.
Once stopped, an applet is restarted when the browser
calls start().

Table 14.1: The Methods Defined by Applet


14.5 Applet Architecture
 An applet is a window-based program. There are a few key concepts we must understand.
 First, applets are event driven. An applet resembles a set of interrupt service routines. An
applet waits until an event occurs. The AWT notifies the applet about an event by calling
an event handler.
 Second, the user initiates interaction with an applet - not the other way around. The user
interacts with the applet as he or she wants, when he or she wants. These interactions are
sent to the applet as events to which the applet must respond. For example, when the user
clicks a mouse inside the applet’s window, a mouse-clicked event is generated. If the user
presses a key while the applet’s window has input focus, a keypress event is generated.
 Applets can contain various controls, such as push buttons and check boxes. When the
user interacts with one of these controls, an event is generated.
14.6 Applet Life Cycle
 There are five methods that are called during the life cycle of an applet. They
are:
1) init()
2) start()
3) stop()
4) destroy()
5) paint()

 The life cycle of an applet is as shown in the figure below:

init() method
 The init() method is the first method to be called.
 Variable declaration and initialization operations are performed in this method.
 This method is called only once during the run time of our applet.
 The general form is:
public void init()
{
…………
………… (Action)
…………
}
start() method
 The start() method is called after init().
 The start() method contains the actual code of the applet that should run.
 It also executes whenever the applet is restored, maximized or moving from one tab to
another tab in the browser.
 The general form is:
public void start()
{
…………
………… (Action)
…………
}
stop() method
 The stop() method stops the execution of the applet.
 The stop() method executes when the applet is minimized or when moving from one tab
to another in the browser.
 The general form is:
public void stop()
{
…………
………… (Action)
…………
}
destroy() method
 The destroy() method executes when the applet window is closed or when the tab
containing the webpage is closed.
 The stop() method is always called before destroy(). The destroy() method removes the
applet object from memory.
 The general form is:
public void destroy()
{
…………
………… (Action)
…………
}
paint()
 The paint() method is used to redraw the output on the applet display area.
 The paint() method executes after the execution of start() method and whenever the
applet or browser is resized.
 The general form is:
public void paint(Graphics g)
{
…………
………… (Display statements)
…………
}
Example:

//Simple Java Program Using Applets


import java.applet.*;
public class MyApplet extends Applet
{
public void init()
{
System.out.println("Applet initialized");
}
public void start()
{
System.out.println("Applet execution started");
}
public void stop()
{
System.out.println("Applet execution stopped");
}
public void paint(Graphicsg)
{
System.out.println("Painting...");
}
public void destroy()
{
System.out.println("Applet destroyed");
}
}
Output:

Applet initialized
Applet execution started
Painting…
Painting…
Applet execution stopped
Applet destroyed
update()
 This method is called when the applet has requested that a portion of its window be
redrawn.
 The default version of update() first fills an applet with the default background color and
then calls paint().
 If we fill the background using different color in paint(), the user will experience a flash
of the default background each time update() is called – that is, whenever the window is
repainted.
 One way to avoid is to override the update() method so that it performs all necessary
display activities.
Example:
// Java program using update() method
import java.awt.*;
import java.applet.*;
/*
<applet code=PaintTest width=100 height=100>
</applet>
*/
public class PaintTest extends Applet
{
public void paint(Graphics g)
{
System.out.println("In paint");
}
public void update(Graphics g)
{
System.out.println("In update");
}
}

14.7 Simple Applet Display Methods


 Applets are displayed in a window and they use the AWT to perform input and output.
drawString()
 The drawString() method is used to output a string to an applet.
 This method is a member of the Graphics class.
 It is called from within either update() or paint().
 The general form is:
void drawString(String message, int x, int y)

Here, message is the string to be output beginning at x, y. In a Java window, the upper left
corner is location 0, 0. The drawString method will not recognize newline characters. If
we want to start a line of text on another line, we must do so manually, specifying the
precise x, y locations where we want the line to begin.
setBackground()
 The setBackground() method is used to change the background color of an applet’s
window.
 This method is defined by the Component class.
 The general form is:
void setBackground(Color newColor)
Here, newColor specifies the new color. The class Color defines the constants shown
here that can be used to specify colors:

Color.black Color.magenta
Color.blue Color.orange
Color.cyan Color.pink
Color.darkGray Color.red
Color.gray Color.white
Color.green Color.yellow
Color.lightGray
Example:
setBackground(Color.green);

setForeground()
 The setForeground() method is used to change the color of the text in the applet’s
window. This method is defined by the Component class.
 The general form is:
void setForeground(Color newColor)
Here, newColor specifies the new color.
Example:
setForeground(Color.red);
 A good place to set the foreground and background colors is in the init() method. The
default foreground color is black. The default background color is light gray.
getBackground()
 The getBackground() method is used to obtain the current settings for the background
color.
 This method is also defined by the Component class. The general form is:
Color getBackground()
getForeground()
 The getForeground() method is used to obtain the current settings for the foreground
color.
 This method is also defined by the Component class. The general form is:
Color getForeground()
Example:
// A simple applet that sets the foreground and background colors and outputs a
string
import java.awt.*;
import java.applet.*;
/*
<applet code="Sample" width=300 height=50>
</applet>
*/
public class Sample extends Applet
{
String msg;
// Set the foreground and background colors.
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
msg="Inside init() –";
}
// Initialize the string to be displayed.
public void start()
{
msg+="Inside start()..";
}
// Display msg in applet window.
public void paint(Graphics g)
{
msg+="Inside paint().";
g.drawString(msg, 10, 30);
}
}
Output:
Requesting Repainting
repaint()
 The repaint() method causes the AWT runtime system to execute the update() method of
the Component class which clears the window with the background color of the applet
and then calls the paint() method.
 The repaint() method has four forms. The simplest version of repaint() is shown here:
void repaint()
This version causes the entire window to be repainted. The following version specifies a
region that will be repainted:
void repaint(int left, int top, int width, int height)
Here, the coordinates of the upper-left corner of the region are specified by left and top,
and the width and height of the region are passed in width and height. These dimensions
are specified in pixels.
void repaint(long maxDelay)
void repaint(long maxDelay, int x, int y, int width, int height )
Here, maxDelay specifies the maximum number of milliseconds that can elapse before
update() is called. If the time elapses before update() can be called, it isn’t called. There is
no return value or exception thrown, so we must be careful.
14.8 Development and Execution of a Simple Applet
 The development and execution of an Applet involves the following steps:
1) Writing the applet’s code (.java file)
2) Compiling the applet’s code (.class file will be ready after compilation)
3) Writing the HTML code (.html file)
4) Invoking the appletviewer utility from a command shell window
Writing the applet’s code
// Java program to create an Applet
// HelloApplets.java
import java.awt.*;
import java.applet.*;

public class HelloApplets extends Applet


{
public void paint(Graphics g)
{
g.drawString(“Welcome to Java Applets”,65,35);
}
}

Compiling the applet’s code

 Compiling an applet is exactly the same as compiling an application. Therefore, we can


use the Java compiler to compile the applet.
 The steps required for compiling the HelloApplets applet are:
1. Move to the directory containing the source code and type the following command:

Javac HelloApplets.java
2. The compiled output file called HelloApplets.class is placed in the same directory as the
source.
3. If any error message is received, then we must check for errors, correct them and compile
the applet again.
Writing the HTML code

 The code for the HelloApplets.html file shall be keyed in, as shown here:

<html>
<head>
<title>Hello World !</title>
</head>
<body>
<applet code=”HelloApplets.class” width=400 height=200>
</applet>
</body>
</html>
Invoking the appletviewer utility from a command shell window
 The appletviewer is available as part of the Java Development Kit that we have been using
so far.
 We can use it to run our applet as follows:
appletviewer HelloApplets.html

14.9 The Status Window

 The showStatus() method is used to display a message in the status window of the
browser or applet viewer on which the applet is running.
 The status window is a good place to give the user feedback about what is occurring in
the applet, suggest options, or possibly report some types of errors.
 The status window also makes an excellent debugging aid, because it gives an easy way
to output information about our applet.

Example:

// Java program using the Status Window.


// StatusWindow.java
import java.awt.*;
import java.applet.*;

/*
<applet code="StatusWindow" width=300 height=50>
</applet>
*/
public class StatusWindow extends Applet
{
public void init()
{
setBackground(Color.cyan);
}
// Display msg in applet window.
public void paint(Graphics g)
{
g.drawString("This is in the applet window.",10,20);
showStatus("This is shown in the status window.");
}
}
14.10 The APPLET Tag
 The <APPLET> tag is used to incorporate an applet into a web page.
 The <APPLET> tag creates a space of the required size and then displays the applet output
in that space.
 The APPLET tag is used to start an applet from both an HTML document and from an
applet viewer.
 An applet viewer will execute each APPLET tag that it finds in a separate window, while
web browsers like Netscape Navigator, Internet Explorer, and HotJava will allow many
applets on a single page.
 The syntax for the standard Applet tag is shown here. Bracketed items are
optional.
<APPLET
[CODEBASE=codebase_URL]
CODE=AppletFileName.class
[ALT=alternate_text]
[NAME=applet_instance_name]
WIDTH=pixels
HEIGHT=pixels
[ALIGN=alignment]
[VSPACE=pixels]
[HSPACE=pixels]
>
[<PARAM NAME=name1 VALUE=value1>]
[<PARAM NAME=name2 VALUE=value2>]
………………
………………
[Text to be displayed in the absence of Java]
</APPLET>

The minimum required attributes are:

CODE=AppletFileName.class
WIDTH=pixels
HEIGHT=pixels
The attributes of the APPLET tag are as follows:
Attribute Meaning
CODEBASE= codebase_URL Specifies the URL of the directory in which the applet
resides. If the applet resides in the same directory as
the HTML file, then the CODEBASE attribute may be
omitted entirely.
CODE= AppletFileName.class CODE is a required attribute that gives the name of the
file containing our applet’s compiled .class file. This
file is relative to the code base URL of the applet,
which is the directory that the HTML file was in or the
directory indicated by CODEBASE if set.
ALT=alternate_text The ALT tag is an optional attribute used to specify a
short text message that should be displayed if the
browser understands the APPLET tag but can’t
currently run Java applets.
NAME=applet_instance_name A name for the applet may optionally be specified so
that other applets on the page may refer to this applet.
This facilitates inter-applet communication.
WIDTH=pixels WIDTH and HEIGHT are required attributes that give
HEIGHT=pixels the size (in pixels) of the applet display area.
ALIGN=alignment ALIGN is an optional attribute that specifies the
alignment of the applet. Possible values are: LEFT,
RIGHT, TOP, BOTTOM, MIDDLE, BASELINE,
TEXTTOP, ABSMIDDLE, and ABSBOTTOM.
VSPACE=pixels VSPACE specifies the amount of vertical blank space,
in pixels, above and below the applet. Used only when
some vertical alignment is specified with the ALIGN
attribute (TOP, BOTTOM, etc.). This attribute is
optional.
HSPACE=pixels HSPACE specifies the amount of horizontal blank
space, in pixels, on each side of the applet. Used only
when ALIGN is set to LEFT or RIGHT. This attribute
is optional.
PARAM NAME and VALUE The PARAM tag allows us to specify applet-specific
arguments in an HTML page. Applets access their
attributes with the getParameter() method.

14.11 Passing Parameters to Applets


 The Applet tag in HTML allows us to pass parameters to our applet.
 To retrieve a parameter, use the getParameter() method.
 It returns the value of the specified parameter in the form of a String object.
 Thus, for numeric and boolean values, we will need to convert their string representations
into their internal formats.
Example:
// Passing parameters to applets
// HelloJavaParam.java
import java.awt.*;
import java.applet.*;
public class HelloJavaParam extends Applet
{
String str;
public void init()
{
str=getParameter("string"); // Receiving parameter value
if (str==null)
str="Java";
str="Hello"+str; // Using the value
}
public void paint(Graphics g)
{
g.drawString(str,10,20);
}
}
The HTML file for HelloJavaParam applet.
<HTML>
<!-- Parameterized HTML file -- >
<HEAD>
<TITLE>Welcome to Java Applets </TITLE>
</HEAD>
<BODY>
<APPLET CODE=HelloJavaParam.class WIDTH=400 HEIGHT=200>
<PARAM NAME=”string” VALUE=”Applet!”>
</APPLET>
</BODY>
</HTML>

 Save this file as HelloJavaParam.html and then run the applet using the applet viewer as
follows:
appletviewer HelloJavaParam.html
14.12 Displaying Numeric Values
 In applets, we can display numerical values by first converting them into strings and then
using the drawString() method of Graphics class.
 We can do this easily by calling the valueOf() method of String class.
Example:

// Displaying numeric values


// NumericInput.java
import java.awt.*;
import java.applet.*;
/*
<applet code=”NumericInput” width=400 height=400>
</applet>
*/
public class NumericInput Extends Applet
{
public void paint(Graphics g)
{
int a=11;
int b=29;
int sum=a+b;
String S=”Sum:”+String.valueOf(sum);
g.drawString(S,100,100);
}
}

14.13 Getting input from the user

 Applets work in a graphical environment. Therefore, applets treat inputs as text strings.
 We must first create an area of the screen in which user can type and edit input items
(which may be any data type).
 We can do this by using the TextField class of the applet package. Once text fields are
created for receiving input, we can type the values in the fields and edit them, if necessary.
Example:

// Interactive input to an applet


// UserInput.java
import java.awt.*;
import java.applet.*;
/*
<applet code=”UserInput” width=300 height=200>
</applet>
*/
public class NumericInput Extends Applet
{
TextField text1, text2;
public void init()
{
text1=new TextField(10);
text2=new TextField(10);
add(text1);
add(text2);
text1.setText(“0”);
text2.setText(“0”);
}
public void paint(Graphics g)
{
int x=0, y=0, z=0;
String s1, s2, s;
g.drawString(“Input a number in each box”,10,50);
try
{
s1=text1.getText();
x=Integer.parseInt(s1);
s2=text2.getText();
y=Integer.parseInt(s2);
}
catch (Exception ex){}
z=x+y;
s=String.valueOf(z);
g.drawString(“THE SUM IS: “,10,75);
g.drawString(s,100,75);
}
public boolean action(Event event, Object obj)
{
repaint();
return true;
}
}
14.14 The Graphics Class
 The Graphics class includes methods for drawing many different types of shapes, from
simple lines to polygons to text in a variety of fonts.
 To display text, we can use the paint() method,and a Graphics object.
 To draw a shape on the screen, we may call one of the methods available in the Graphics
class.
 Table 14.2 shows the most commonly used methods in the Graphics class.
 All the drawing methods have arguments representing end points, corners, or starting
locations of a shape as values in the applet’s coordinate system.
 To draw a shape, we only need to use the appropriate method with the required
arguments.
Table 14.2 Drawing Methods of the Graphics Class

Method Description
clearRect() Erases a rectangular area of the canvas.
copyArea() Copies a rectangular area of the canvas to another area.
drawArc() Draws a hollow arc.
drawLine() Draws a straight line.
drawOval() Draws a hollow oval.
drawPolygon() Draws a hollow polygon.
drawRect() Draws a hollow rectangle.
drawRoundRect() Draws a hollow rectangle with rounded corners.
drawString() Displays a text string.
fillArc() Draws a filled arc.
fillOval() Draws a filled oval.
fillPolygon() Draws a filled polygon.
fillRect() Draws a filled rectangle.
fillRoundRect() Draws a filled rectangle with rounded corners.
getColor() Retrieves the current drawing color.
getFont() Retrieves the currently used font.
getFontMetrics() Retrieves information about the current font.
setColor() Sets the drawing color.
setFont() Sets the font.

14.15 Lines and Rectangles


drawLine()
 The drawLine() method is used to draw a straight line.
 This method takes two pair of coordinates, (x1, y1) and (x2, y2) as arguments and draws
a line between them.
 For example, the following statement draws a straight line from the coordinate point (10,
10) to (50, 50);
g.drawLine(10, 10, 50, 50);

The g is the Graphics object passed to paint() method.

drawRect()

 The drawRect() method is used to draw a rectangle.


 This method takes four arguments. The first two represent the x and y coordinates of the
top left corner of the rectangle, and the remaining two represent the width and the height
of the rectangle.
 For example, the statement
g.drawRect(10, 60, 40, 30)

will draw a rectangle starting at (10, 60) having a width of 40 pixels and a height of 30
pixels. The drawRect() method draws only the outline of a box.
fillRect()
 The fillRect() method is used to draw a solid box.
 This also takes four parameters corresponding to the starting point, the width and the
height of the rectangle.
 For example, the statement
g.fillRect(60, 10, 30, 80);

drawRoundRect() and fillRoundrect()

 The drawRoundRect() and fillRoundRect() methods are used to draw rounded


rectangles (which are rectangles with rounded edges).
 These two methods are similar to drawRect() and fillRect() except thatthey taketwo extra
arguments representing the width and height of the angle of corners.
 These extra parameters indicate how much of corners will be rounded.
Example:

g.drawRoundRect(10, 100, 80, 50, 10, 10);


g.fillRoundRect(20, 110, 60, 30, 5, 5);
Example:
//Java program for drawing lines and rectangles
//LineRect.java
import java.awt.*;
import java.applet.*;
public class LineRect extends Applet
{
public void paint(Graphics g)
{
g.drawLine(10, 10, 50, 50);
g.drawRect(10, 60, 40, 30);
g.fillRect(60, 10, 30, 80);
g.drawRoundRect(10, 100, 80, 50, 10, 10);
g.fillRoundRect(20, 110, 60, 30, 5, 5);
g.drawLine(100, 10, 230, 140);
g.drawLine(100, 140, 230, 10);
}
}
LineRect.html
<APPLET
CODE=LineRect.class
WIDTH=250
HEIGHT=200>
</APPLET>
Output:

Applet

Applet Started

14.16 Circles and Ellipses


drawOval() and fillOval()
 The drawOval() method is used to draw a circle or an ellipse. Ovals are just like
rectangles with overly rounded corners.
 The drawOval() method takes fourarguments: the first two represent the top left corner
of the imaginary rectangle and the other two represent the height and width of the oval
itself.
 If the width and height are the same, the oval becomes a circle.
 The oval’s coordinates are actually the coordinates of an enclosing rectangle.
 The drawOval() method draws outline of an oval, the fillOval() method draws a solid
oval.
 The code segment shown below draws a filled circle with an oval.
setColor()
 The setColor() method is used to set the color of an object.
g.setColor(Color.green);
 After setting the color, all drawing operations will occur in that color.
Example:

//Java Program for drawing Ellipses


import java.awt.*;
import java.applet.*;
/*
<applet code="Ellipses" width=300 Height=300>
</applet>
*/
public class Ellipses extends Applet
{
public void paint(Graphics g)
{
g.drawOval(10,10,60,50);
g.fillOval(100,10,75,50);
g.drawOval(190,10,90,30);
g.fillOval(70,90,140,100);
}
}

Output:
14.17 Drawing Arcs
drawArc() & fillArc()
 The drawArc() method is used to draw an arc.
 The drawArc() designed to draw arcs takes six arguments. The first four are the same as
the arguments for drawOval() method and the last two represent the starting angle of the
arc and the number of degrees around the arc.
 The fillArc() method is used to fill anarc.Filled arcs are drawnas if they were sections of
a pie.
Example:

//Java Program for drawing arcs


import java.awt.*;
import java.applet.*;
/*
<applet code="Arcs" width=300 Height=300>
</applet>
*/
public class Arcs extends Applet
{
public void paint(Graphics g)
{
g.drawArc(10,40,70,70,0,75);
g.fillArc(100,40,70,70,0,75);
g.drawArc(10,100,70,80,0,175);
g.fillArc(100,100,70,90,0,270);
g.drawArc(200,80,80,80,0,180);
}
}

Output:
Write a Java program to draw a human face.

//Applet for drawing a human face


import java.awt.*;
import java.applet.*;
/* <applet code=Face width=300 height=300></applet> */
public class Face extends Applet
{
public void paint(Graphics g)
{
g.drawOval(40, 40, 120, 150); // Head
g.drawOval(57, 75, 30, 20); // Left eye
g.drawOval(110, 75, 30, 20); // Right eye
g.fillOval(68, 81, 10, 10); // Pupil (left)
g.fillOval(121, 81, 10, 10); // Pupil (right)
g.drawOval(85, 100, 30, 30); // Nose
g.fillArc(60, 125, 80, 40, 180, 180); // Mouth
g.drawOval(25, 92, 15, 30); // Left ear
g.drawOval(160, 92, 15, 30); // Right ear
}
}
Output:

14.18 Drawing Polygons


 Polygons are shapes with many sides. A polygon may be considered a set of lines
connected together.
drawPoygon() & fillPolygon()

 The drawPolygon() method of the Graphics class is used to draw a polygon.


 This method takes three arguments:
 An array of integers containing x coordinates
 An array of integers containing y coordinates
 An integer for the total number of points
 The fillPolygon() method is used to fill a polygon.

Example:

//Java Program for drawing a Polygon


import java.awt.*;
import java.applet.*;
/*
<applet code="Polygon" width=300 Height=300>
</applet>
*/
public class Polygon extends Applet
{
public void paint(Graphics g)
{
int xpoints[]={30,200,30,200,30};
int ypoints[]={30,30,200,200,30};
int num=5;
g.drawPolygon(xpoints,ypoints,num);
}
}
Output:

You might also like