0% found this document useful (0 votes)
4 views55 pages

AWT and Applet in Java With Examples

The document provides a comprehensive overview of Java Applets, including their definition, types (Applet and JApplet), advantages, drawbacks, and the Applet class structure. It details the applet life cycle, methods of the Applet class, and how to run applet programs using both a Java-enabled web browser and Appletviewer. Additionally, it includes examples of applet code and explains the repaint mechanism for updating applet displays.

Uploaded by

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

AWT and Applet in Java With Examples

The document provides a comprehensive overview of Java Applets, including their definition, types (Applet and JApplet), advantages, drawbacks, and the Applet class structure. It details the applet life cycle, methods of the Applet class, and how to run applet programs using both a Java-enabled web browser and Appletviewer. Additionally, it includes examples of applet code and explains the repaint mechanism for updating applet displays.

Uploaded by

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

Applet in Java with Examples

In this article, I am going to discuss Applet in Java with Examples.


1. What is Applet in Java?
2. Types of Applets in Java
3. Advantages & Drawbacks of Java Applet
4. The Applet Class in Java
5. Methods of Applet Class
6. Applet Life cycle in Java
7. How to run Applets Programs in Java?
8. What is Appletviewer?
9. How to run the Applet Program using Appletviewer?
10. Passing Parameters to Java Applet
Java Applet Introduction:
The Applet class is contained within java.applet package. The applet
contains several methods that offer you detailed control over the
execution of your applet. java.applet defines three interfaces :
AppletContext, AudioClip, and AppletStub. This chapter examines the
Applet class, which provides inspiration for applets.
Basically, in Java we have two types of applications:
1. Standalone Applications: The applications that are executed
in the context of a local machine are called standalone
applications. Their applications use w-1 of system resources
and the resources are not sharable. This kind of application
contains the main() method.
2. Distributed Applications: The applications that are executed
under the control of a browser are called distributed
applications. The amount of resources required is very
minimum and the resources are sharable. These applications
will not contain the main() method. To develop a distributed
GUI we use Applet.
What is Applet in Java?
An applet may be a Java program that registers on the server and can
be executed within the client. The applet may be a window that was
constructed either by using Applet or JApplet class. Applets may be a
special sort of program that’s embedded within the webpage to get the
dynamic content. It basically runs inside the browser and works on the
client-side.
All applets are subclasses of (either directly or indirectly) Applet.
Applets aren’t standalone programs. Instead, they run within either an
internet browser or an applet viewer. Execution of an applet doesn’t
begin at the main(). Actually, few applets even have main() methods.
Output to your applet’s window isn’t performed
by System.out.println(). Rather, in non-Swing applets, the output is
handled with various AWT methods, like drawString(), which outputs a
string to a specified X, Y location.

Types of Applets in Java:


It is important to state at the outset that there are two sorts of applets.
1. Applet: it’s based directly on Applet class. These applets use
the Abstract Window Toolkit (AWT) to supply the graphic
user interface(GUI). This sort of applet has been available
since Java was first created.
2. JApplet: it’s supported Swing class. Swing applets use the
Swing classes to supply the GUI. Swing offers a richer and
ofter easier-to-use interface than does the AWT. Thus,
Swing-based applets are now the foremost popular.
Note: The Applet class is employed for enabling the AWT package to
feature UI components and whereas JApplet class is employed for
enabling the swing package to feature UI components.
Advantages of Java Applet
There are many advantages to the applet. they’re as follows:
1. It works on the client-side therefore the reaction time is
extremely less.
2. It is Secured
3. It is often executed by browsers running under many
platforms, including Linux, Windows, Mac Os, etc.
Drawbacks of Applet in Java
• The plugin is required at the client browser to execute the
applet.
• An applet cannot load libraries or define native methods.
• An applet cannot read or write files on the execution host
and certain system properties.
• An applet cannot make network connections except to the
host that it came from.

The Applet Class in Java


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.

Methods of Java Applet Class


The Applet class defines the following methods:
1. void destroy(): It is called by the browser just before an
applet is terminated. If it needs to perform any clean up
prior to its destruction, your applet will override this
method.
2. AccessibleContext getAccessibleContext(): It returns the
accessibility context for the invoking object.
3. AppletContext getAppletContext(): It returns the context
associated with the applet.
4. String getAppletInfo(): It returns a String that describes the
applet.
5. AudioClip getAudioclip(URL url): It returns an AudioClip
found at the location specified by URL.
6. AudioClip getAudioClip(URL url, String clipName): It
returns an AudioClip object found at the location specified
by URL and having the name specified by clipName.
7. URL getCodeBase(): It returns the URL associated with the
invoking applet.
8. URL getDocumentBase(): It returns the URL of the HTML
document.
9. Image getImage(URL url): It returns an Image object that
encapsulates the image of the location specified by the
URL.
10. Image getImage(URL url, String imageName): Returns an
Image object that encapsulates the image found at the
location specified by URL and having the name specified by
imageName.
11. Locale getLocale(): It returns a Locale object used by various
classes and methods.
12. String getParameter(String paramName): It returns the
parameter associated with paramName and returned Null
if the parameter is not found.
13. String[] [] getParameterInfo(): It returns a String table that
contains the name of the parameter, a description of its
type and/or range, and an explanation of its purpose.
14. void init(): It is the first method called for any applet. It is
called when an applet begins execution.
15. boolean isActive(): It returns true if the applet has been
started and returns false if the applet has been stopped.
16. static final AudioClip new AudioClip(URL url): It returns an
AudioClip found at the location specified by the URL. This
method is similar to getAudioClip() except that it is static
and can be executed without the need for an Applet object.
17. void play(URL url): If an audio clip is found at the location
specified by the URL, the clip is played.
18. void play(URL url, String clipName): If an audio clip is found
at the location specified by the URL with the name
specified by clipName.
19. void resize(Dimension dim): It is used to resize the applet
according to the dimensions specified by dim.
20. void resize(int width, int height): It is used to resize the
applet according to the dimensions specified by width and
height.
21. 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 your applet.
22. void showStatus(String str): It is used to display str in the
status window of the browser or applet viewer.
23. void start(): It is called by the browser when an applet
should start (or resume) execution. It is automatically
called after the init() method.
24. void stop(): It is called by the browser to suspend the
execution of the applet. Once stopped, an applet is
restarted when the browser calls start().
Applet Life cycle in Java:

Every Java Applet needs to go through a series of phases from


initialization to destruction in order to complete its execution. The first
step is to inherit the java.applet.Applet class. This class aids with
various methods that help in holding up a basic framework for the Java
Applets. The various methods involved in the life cycle of Java Applet
have been depicted in the below diagram.
An applet is a window-based program. Its architecture is different from
console-based programs. Applets are event-driven. An Applet waits
until an event occurs. The run-time system notifies the applet about an
event by calling an event handler provided by the applet. Then, the
applet must take appropriate action and then quickly return. This is a
crucial point.
The user can initiate the interaction with an Applet as he or she wants
when he or she wants. These interactions are now sent to the applet as
events to which the applet must respond. When the user interacts with
any of the controls, an event is generated.
An Applet Skeleton
The applets override a set of methods that provides the basic
mechanism by which the browser or applet viewer interfaces to the
applet and controls its execution. It is important to understand the
order in which the various methods are called. When an applet begins,
the following methods are called:
1. init()
2. start()
3. paint()
When an applet is terminated, the following sequence of method calls
takes place:
1. stop()
2. destroy()
Let’s look more closely at these methods.
init(): The init() method is the first method to be called where you
ought to initialize variables. This method is named just one occasion
during the run time of your applet.
start(): The start() method is named after init(). It’s also called to restart
an applet after it’s been stopped. When start() is named whenever an
applet’s HTML document is displayed onscreen. So, if a user leaves a
webpage and comes back, the applet resumes execution at the start().
paint(): The paint() method is named whenever your applet’s output
must be redrawn. This example can occur for several reasons. paint() is
additionally called when the applet begins execution. The paint()
method has a parameter of type Graphics. This parameter will contain
the graphics context, which describes the graphics environment during
which the applet is running. This context is employed whenever output
to the applet is required.
stop(): The stop() method is named when an internet browser leaves
the HTML document containing the applet- when it goes to a different
page. When stop() is named, the applet is perhaps running. You ought
to use stop() to suspend threads that don’t get to run when the applet
isn’t visible. You’ll restart them when start() is named if the user returns
to the page.
destroy(): The destroy() method is named when the environment
determines that your applet must be removed completely from
memory. At now, you ought to release any resources the applet could
also be using. The stop() method is usually called before destroy().
Overriding update()
In some situations, your applet may need to override another method
defined by the AWT, called update(). This method is called when your
applet has requested that a portion of its window be redrawn. The
default version of update() simply calls paint(). However, you can
override the update() method so that it performs more subtle
repainting. In general, overriding update() is a specialized technique
that is not applicable to all applets.
How to run Applets in Java?
An Applet program is compiled in the same way as you have been
compiling your console programs. However, there are two ways to run
an applet.

1. Using a Java-enabled web browser


2. Using appletviewer
Using a Java-enabled web-browser
To use an Applet by a Java-enabled web browser, one way to do this is
by using the APPLET tag. The applet is executed by a Java-enabled web
browser when it encounters the APPLET tag within the HTML file. To
view and test an applet, simply include a comment at the head of your
Java source code file that contains the APPLET tag. Here is an example
of such a comment:
/*
<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.

Using appletviewer
An Applet viewer creates an environment that mocks the look and feel
of a stand-alone program with no interaction with a web browser, even
though it does involve a browser to run an applet. The Appletviewer is
included with Sun’s JDK package, but not with Sun’s JRE package.
What is Appletviewer?
The AppletViewer is a standalone command-line program from Sun
Microsystems to run Java applets. The Appletviewer is usually employed
by developers for testing their applets before deploying them to an
internet site. The Appletviewer command connects to the documents
or resources designated by URLs and displays each applet referenced by
the documents in its own window.
How does Appletviewer work?
As a Java developer, it’s a preferred option for running Java applets that
don’t involve the utilization of an internet browser. The applet viewer
logically takes the place of an internet browser, it functions very
differently from an internet browser. The applet viewer operates on
HTML documents, but all it’s for is embedded applet tags; the other
HTML code within the document is ignored. Whenever the applet
viewer encounters an applet tag in an HTML document, it launches a
separate applet viewer window containing the respective applet.
How to run the Applet Program using Appletviewer?
This is the simplest way to run an applet. To execute a Java Applet in
this way, all you would like to try to do is, rather than create a separate
file for HTML code, you’ll directly add comments at the start of your
Java ASCII text file indicating the presence of APPLET tag within. If you
include a comment at the top of your Java ASCII text file that contains
the APPLET tag then your code is documented with a prototype of the
required HTML statements, and you’ll run your compiled applet merely
by starting the applet viewer together with your Java ASCII text file.
Example: An Applet Skeleton in Java
import java.awt.*;
import java.applet.*;
/*
<applet code ="AppletSkeleton" width=300 height=100>
</applet>
*/
public class AppletSkeleton extends Applet
{
public void init ()
{
//initialization
}
public void start ()
{
//start or resume execution
}
public void stop ()
{
//suspend execution
}
public void destroy ()
{
//perform shutdown activity
}
public void paint (Graphics g)
{
//display the content of window
}
}
Output:
Although this skeleton does not do anything, it can be compiled and
run. When run, it generates the following window when viewed with an
applet viewer:
Creating Hello World Applet in Java
import java.applet.Applet;
import java.awt.Graphics;

// HelloWorld class extends Applet


public class HelloWorldApplet extends Applet
{
// Overriding paint() method
@Override public void paint (Graphics g)
{
g.drawString ("Hello World", 20, 20);
}
}
Output:
Requesting Repaint : repaint() method
Whenever your applet needs to update the information displayed in its
window, it simply calls repaint(). The repaint() method is defined by the
AWT. It causes the AWT runtime system to execute a call to your
applet’s update() method, which, in its default implementation, calls
paint(). Thus, for another part of your applet to output to its window,
simply store the output and then call repaint(). The AWT will then
execute a call to paint(), which can display the stored information.

The repaint() method has four forms:


1. void repaint()
2. 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.
1. void repaint(long maxDelay)
2. void repaint(long maxDelay, int x, int y, int width, int
height)
Here, maxDelay specifies the maximum number of milliseconds that can
elapse before the update (0 is called. If the time elapses before the
update() can be called, it isn’t called. There’s no return value or
exception thrown.

Example: Creating a Simple Banner using Applet in Java


import java.awt.*;
import java.applet.*;

/*
<applet code ="RepaintApplet" width=300 height=50>
</applet>
*/
public class RepaintApplet extends Applet implements Runnable
{
String msg = "A simple Moving Banner.";
Thread t = null;
int state;
boolean stopFlag;

public void init ()


{
setBackground (Color.cyan); // To set Background color of an Applet
setForeground (Color.red); // To set Foreground color of an Applet
}

public void start ()


{
t = new Thread (this);
stopFlag = false;
t.start ();
}

public void run ()


{
char ch;
for (;;)
{
try
{
repaint();
Thread.sleep(250);
ch = msg.charAt (0);
msg = msg.substring(1, msg.length ());
msg += ch;
if (stopFlag)
break;
}
catch (InterruptedException ie)
{
}
}
}

public void stop ()


{
stopFlag = true;
t = null;
}

public void paint (Graphics g)


{
g.drawString (msg, 50, 30);
}
}
Output:

Using the status window


In addition to displaying information in its window, an applet can also
put a message to the status window of the browser or applet viewer on
which it’s running. To do so, call showStatus() with the String that you
simply want to be displayed. The status window may be a good place to
offer the user feedback about its occurring within the applet, suggest
options, or possibly report some sorts of errors.

Example to show the use of status window in 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);
}
public void paint (Graphics g)
{
g.drawString ("This is in the applet window", 10, 20);
showStatus ("This is shown in the status window.");
}
}
Output:
Passing Parameters to Applet in Java
The APPLET tag in HTML allows you to pass parameters to your 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, you will need to convert their string
representations into their internal formats.

Example: Passing Parameters to Applet in Java


import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="ParamDemo" width="300" height="300">
<param name=fontName value=Welcome>
</applet>
*/
public class ParamDemo extends Applet
{
String fontName;
public void init ()
{
fontName = getParameter ("pname");
if (fontName == null)
fontName = "Welcome to Applet Window";
fontName = "Hello " + fontName;
}
public void paint (Graphics g)
{
g.drawString (fontName, 0, 10);
}
}
Output:
Graphics in Applet with Examples
In this article, I am going to discuss Graphics in Apple with Examples.
Please read our previous article, where we discussed Applet in Java. At
the end of this article, you will understand what are graphics and when
and how to use Graphics in Applet with examples.

Graphics in Applet:
All graphics are drawn relative to a window. This can be the main
window of an applet, a child window of an applet, or a stand-alone
application window. The origin of each window is at the top-left
Coordinates 0,0.

Coordinates are specified in pixels.


All output to a window takes place through a graphics context. A
graphics context is encapsulated by the Graphics class and is obtained in
two ways:
1. It is passed to an applet when one of its various methods,
such as paint() or update(), is called.
2. It is returned by the getGraphics( ) method of Component.
The Graphics class defines a number of drawing functions. Each shape
can be drawn edge-only or filled. Objects are drawn and filled in the
currently selected graphics color, which is black by default. When a
graphics object is drawn that exceeds the dimensions of the window,
the output is automatically clipped.
java.awt.Graphics class provides many methods for graphics
programming.

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): draw 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 the 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 an oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is
used to fill an oval with the default color and specified width and
height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is
used to draw a line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used to draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height,
int startAngle, int arcAngle): is used to draw a circular or
elliptical arc.
9. 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.
10. public abstract void setColor(Color c): is used to set the graphics
current color to the specified color.
11. public abstract void setFont(Font font): is used to set the
graphics current font to the specified font.
Examples to Understand Graphics in Applet:
import java.applet.Applet;
import java.awt.*;

/*
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
*/
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);
}
}
Output:
Example: Painting in Applet
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Painting extends Applet implements MouseMotionListener
{
public void init ()
{
addMouseMotionListener (this);
setBackground (Color.red);
}

public void mouseDragged (MouseEvent me)


{
Graphics g = getGraphics ();
g.setColor (Color.white);
g.fillOval (me.getX (), me.getY (), 5, 5);
}
public void mouseMoved (MouseEvent me)
{
}
}
Output:
Example to Display Digital Clock in an Applet
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;
/*
<applet code="DigitalClock" width="300" height="300">
</applet>
*/
public class DigitalClock extends Applet implements Runnable
{
Thread t = null;
int hours = 0, minutes = 0, seconds = 0;
String timeString = "";

public void init ()


{
setBackground (Color.green);
}
public void start ()
{
t = new Thread (this);
t.start ();
}

public void run ()


{
try
{
while (true)
{
Calendar cal = Calendar.getInstance ();
hours = cal.get (Calendar.HOUR_OF_DAY);
if (hours > 12)
hours -= 12;
minutes = cal.get (Calendar.MINUTE);
seconds = cal.get (Calendar.SECOND);

SimpleDateFormat formatter = new SimpleDateFormat ("hh:mm:ss");


Date date = cal.getTime ();
timeString = formatter.format (date);

repaint ();
t.sleep (1000); // interval given in milliseconds
}
}
catch (Exception e)
{
}
}

public void paint (Graphics g)


{
g.setColor (Color.blue);
g.drawString (timeString, 50, 50);
}
}
Output:

Example to Display Analog Clock in Applet


import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;
/*
<applet code="AnalogClock" width="300" height="300">
</applet>
*/
public class AnalogClock extends Applet implements Runnable
{
int width, height;
Thread t = null;
boolean threadSuspended;
int hours = 0, minutes = 0, seconds = 0;
String timeString = "";
public void init ()
{
width = getSize ().width;
height = getSize ().height;
setBackground (Color.black);
}
public void start ()
{
if (t == null)
{
t = new Thread (this);
t.setPriority (Thread.MIN_PRIORITY);
threadSuspended = false;
t.start ();
}
else
{
if (threadSuspended)
{
threadSuspended = false;
synchronized (this)
{
notify ();
}
}
}
}

public void stop ()


{
threadSuspended = true;
}

public void run ()


{
try
{
while (true)
{
Calendar cal = Calendar.getInstance ();
hours = cal.get (Calendar.HOUR_OF_DAY);
if (hours > 12)
hours -= 12;
minutes = cal.get (Calendar.MINUTE);
seconds = cal.get (Calendar.SECOND);
SimpleDateFormat formatter =
new SimpleDateFormat ("hh:mm:ss", Locale.getDefault ());
Date date = cal.getTime ();
timeString = formatter.format (date);
if (threadSuspended)
{
synchronized (this)
{
while (threadSuspended)
{
wait ();
}
}
}
repaint ();
t.sleep (1000);
}
}
catch (Exception e)
{
}
}
void drawHand (double angle, int radius, Graphics g)
{
angle -= 0.5 * Math.PI;
int x = (int) (radius * Math.cos (angle));
int y = (int) (radius * Math.sin (angle));
g.drawLine (width / 2, height / 2, width / 2 + x, height / 2 + y);
}

void drawWedge (double angle, int radius, Graphics g)


{
angle -= 0.5 * Math.PI;
int x = (int) (radius * Math.cos (angle));
int y = (int) (radius * Math.sin (angle));
angle += 2 * Math.PI / 3;
int x2 = (int) (5 * Math.cos (angle));
int y2 = (int) (5 * Math.sin (angle));
angle += 2 * Math.PI / 3;
int x3 = (int) (5 * Math.cos (angle));
int y3 = (int) (5 * Math.sin (angle));
g.drawLine (width / 2 + x2, height / 2 + y2, width / 2 + x, height / 2 + y);
g.drawLine (width / 2 + x3, height / 2 + y3, width / 2 + x, height / 2 + y);
g.drawLine (width / 2 + x2, height / 2 + y2, width / 2 + x3, height / 2 +
y3);
}

public void paint (Graphics g)


{
g.setColor (Color.pink);
drawWedge (2 * Math.PI * hours / 12, width / 5, g);
drawWedge (2 * Math.PI * minutes / 60, width / 3, g);
drawHand (2 * Math.PI * seconds / 60, width / 2, g);
g.setColor (Color.white);
g.drawString (timeString, 10, height - 10);
}
}
Output:
Abstract Windows Toolkit (AWT) in Java with
Examples

1. Abstract Windows Toolkit (AWT) in Java


2. Why AWT is platform-dependent?
3. Advantages of GUI over CUI
4. Features of AWT in Java
5. AWT UI Aspects
6. AWT Hierarchy
7. AWT Component

Abstract Windows Toolkit (AWT) in Java:


AWT package is bundled with Java software by default, i.e., located in
rt.jar file (jre/lib).
AWT package is platform dependent API used for creating a graphical
user interface.
The AWT contains a number of classes and methods that allow you to
create and manage windows. It is also the foundation to build Swing.
When a user wants to interact with an application, the user has to
provide some information to the application and it can be done in two
ways:
Character User Interface(CUI): This interface is used to interact with
the application by typing some characters. This interface is not user
friendly because the user has to type all the commands and the user
has to remember all the commands. Example: DOS
Graphical User Interface(GUI): This interface will interact with the
application by using some graphics like menus, icons, images, etc. This
interface is user friendly because it prompts the user by providing the
options or menus. Example: Windows XP, Windows 7, etc.

Points To Remember:
1. To develop the GUI based applications we have to use AWT.
2. AWT stands for Abstract Windowing Toolkit.
3. The set of classes and interfaces which are required to develop
GUI components together are called “Toolkit”. The GUI
components will be used to design GUI programs.
4. Writing a program to display the created GUI components on the
windows is called “windowing”.
5. To display the components on the windows we need to take the
support of graphics available in the operating system. For a
developer, there is no direct interaction with the graphics and
hence graphics is “Abstract” to the developer.
6. Every GUI component will have a corresponding “PEER” class
which is responsible to interact with the graphics of the operating
system.

Why AWT is platform-dependent?


Java AWT components are platform-dependent because components
are displayed according to the view of the operating system.
Java AWT calls Operating systems subroutine for creating components
such as textbox, button, etc.
An application built on AWT looks like a windows application when it
runs on Windows, but the same application would look like a Mac
application when runs on Mac OS.

Note: AWT is rarely used nowadays because of its platform-dependent


and heavy-weight nature. AWT components are considered
heavyweight because they are being generated by the underlying
operating system(OS).

Advantages of GUI over CUI


1. They are easy to learn and use, i.e. users without experience can
also use the system quickly.
2. The user can interact with several different applications by
switching quickly from one task to another.
3. Information remains visible in its own window when attention is
switched.
4. Fast, full-screen interaction is possible with immediate access to
anywhere on the screen.
5. Some types of error situations can be avoided because they are
not allowed to occur through input.

Features of AWT in Java:


The Abstract Window Toolkit (AWT) supports Graphical User Interface
(GUI) programming. AWT features include:
• It is a set of native user interface components
• It is a robust event-handling model
• Applets have graphics and imaging tools, including shape, color,
and font classes
• The applet is having layout managers, for flexible window layouts
that do not depend on a particular window size or screen
resolution
• The applet contains Data transfer classes, for cut-and-paste
through the native platform clipboard

AWT UI Aspects
Every user interface considers the following three main aspects:
1. UI Elements: It refers to the core visual elements used for
interacting with the applications and which are visible to the
users.
2. Layouts: It defines how UI elements should be organized on the
screen and provide a final look and feel to the GUI.
3. Behavior: It defines the events which should occur when a user
interacts with UI elements.

AWT Hierarchy in Java


The AWT classes are contained in java.awt package.
It is one of Java’s largest packages.
Fortunately, because it is logically organized in a top-down, hierarchical
fashion, it is easier to understand and use than you might at first
believe.
The AWT defines windows according to a class hierarchy that is used to
add functionality and specificity to each level. The two most common
windows are Panel, which is used by applets, and Frame, which creates
a standard application window. Most of the functionalities of these
windows are derived from their parent classes.

AWT Component in Java


At the top of the AWT, the hierarchy is the component class. The
Component is an abstract class that encapsulates all of the attributes of
a visual component. All user interface elements that interact with the
user are subclasses of Component and are displayed on the screen.

Some useful methods of Component Class


1. public void add(Component c): It is used to insert a component
on this component.

2. public void setSize(int width, int height): It is used to set the size
(height and width) of the component.
3. public void setLayout(LayoutManager m): It defines the layout
manager of the component.

4. public void setStatus(boolean status): It is used to change the


visibility of the component, by default false.

Container
The Container class is a subclass of the Component class. It has
additional methods that allow other component objects to be nested
within it. A container provides a space where a component can be
located. A Container in AWT is a component itself and it adds the
capability to add the component to itself.
Panel
The Panel class is a concrete subclass of Container. It provides space in
which an application can attach any other component. The default
layout manager for a panel is the FlowLayout layout manager.
It is visually represented as a window that does not contain a title bar,
menu bar, or border. Panels don’t have any visible bounding lines. You
can delimit them with different background colors.
Window
The Window class creates a top-level window with no border and no
menubar.
It uses BorderLayout as a default layout manager. A window must have
either a frame, dialog, or another window defined as its owner when
it’s constructed.
It could be used to implement a pop-up menu. A Window object blocks
input to other application windows when it is shown.
Dialog
Dialog class’s instance always needs an associated Frame class instance
to exist.
Dialog class is also a subclass of Window and comes with the border as
well as the title. An instance of the Dialog class cannot exist without an
associated instance of the Frame class.
Frame
A-Frame may be a top-level window with a title and a border. It can
produce other components like buttons, text fields, etc.
The default layout for a frame is BorderLayout.
Frames are capable of generating the subsequent sorts of window
events:
WindowOpened,
WindowClosing,
WindowClosed,
WindowIconified,
WindowDeiconified,
WindowActivated,
WindowDeactivated.

When a Frame window is made by a stand-alone application instead of


an applet, a traditional window is made.
Frame’s Constructors
Here are two of Frame’s constructors:

1. Frame(): It creates a standard window that does not contain a


title.
2. Frame(String title): It creates a window with the title specified by
the title.
Note: You cannot specify the dimensions of the window. Instead, you
must set the size of the window after it has been created.
Methods of Frames
1. void setSize(int newWidth, newHeight): It is used to set the
dimensions of the window by specifying the width and height
fields of the dimensions. The dimensions are specified in terms of
pixels.
2. void setSize(Dimension newSize): The new size of the window is
specified by newWidth and newHeight, or by the width and height
fields of the Dimension object passed in newSize.
3. Dimension getSize() : The getSize() method is used to obtain the
current size of a window. This method returns the current size of
the window contained within the width and height fields of a
Dimension object.
4. void setVisible(Boolean visibleFlag): The component is visible of
the argument to this method is true. Otherwise, it is hidden.
5. void setTitle(String newTitle): You can change the title in a frame
window using setTitle(). Here, newTitle is the new title for the
window.
6. windowClosing(): When using a frame window, your program
must remove that window from the screen when it is closed, by
calling setVisible(false). To intercept a window-close event, you
must implement the windowClosing() method of the
WindowListener interface. Inside windowClosing(), you must
remove the window from the screen.

Creating a Frame Window in an Applet


The frame can be created in two ways:
1. Create the object of the Frame class directly.
Frame f = new Frame();

2. Create the object of any class that extends the Frame class.
MyFrame mf = new MyFrame();

Example to create a frame by creating the object of the frame class


directly using AWT in Java
import java.awt.*;
public class FrameDemo1
{
public static void main (String[]args)
{
Frame f = new Frame ();
Label lb = new Label ("Hello World");
f.add (lb);
f.setVisible (true);
f.setSize (300, 300);
}
}
Output:

Example to create a frame by extending the frame class using AWT in


Java
import java.awt.*;
public class FrameDemo2 extends Frame
{
public static void main (String[]args)
{
FrameDemo2 fd = new FrameDemo2 ();
Button btn = new Button ("Hello World");
fd.add (btn);
fd.setVisible (true);
fd.setSize (500, 200);
}
}
Output:
AWT Controls in Java with Examples
In this article, I am going to discuss AWT Controls in Java with
Examples. Please read our previous article, where we
discussed Abstract Windows Toolkit (AWT) in Java. At the end of this
article, you will understand the following pointers in detail which are
related to AWT Controls in java with Examples.
1. AWT Controls in Java
2. Labels
3. Buttons
4. Canvas
5. Checkbox
6. Radio Buttons
7. AWT Choice Control in Java
8. List Control
9. AWT Scroll Bar Control in java
10. AWT TextComponent Controls in Java
AWT Controls in Java:
Controls are components that allow a user to interact with your
application in various ways. The AWT supports the following types of
controls:

Labels
The easiest control to use is a label. A label contains a string and is an
object of type Label. Labels are passive controls that do not support any
interaction with the user.
Creating Label : Label l = new Label(String);

Label Constructors:
1. Label() throws HeadlessException: It creates a blank label.
2. Label(String str) throws HeadlessException: It creates a label that
contains the string specified by str.
3. Label(String str, int how): It 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, Label.CENTER.
Label Methods:
1. void setText(String str): It is used to set or change the text in a
label by using the setText() method. Here, str specifies the new
label.
2. String getText(): It is used to obtain the current label by calling
getText() method. Here, the current label is returned.
3. void setAlignment(int how): It is used to set the alignment of the
string within the label by calling setAlignment() method. Here,
how is one of the alignment constants?

4. int getAlignment(): It is used to obtain the current alignment,


getAlignment() is called.

Example to understand AWT Label Control in Java:


import java.awt.*;

import java.awt.event.*;
public class Main
{
void main ()
{
Frame f = new Frame ("Main Window");
Label lb1 = new Label ("Label 1",Label.CENTER);
Label lb2 = new Label ("Label 2",Label.LEFT);
lb1.setSize(100,100);
lb2.setSize(100,100);

lb1.setBackground(Color.red);
f.add (lb1);
f.add (lb2);
f.setVisible (true);
f.setSize (500, 400);

//f.dispose();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
}
Output:

AWT Button Control in Java


The most widely used control is Button. A button is a component that
contains a label and that generates an event when it is pressed.
Creating Button : Button b = new Button(String label);

Button Constructors:
1. Button() throws HeadlessException: It creates an empty button.
2. Button(String str) throws HeadlessException: It creates a button
that contains str as a label.
Button Methods :
1. void setLabel(String str): You can set its label by calling setLabel().
Here, str is the new Label for the button.
2. String getLabel(): You can retrieve its label by calling getLabel()
method.

Example to understand AWT Button Control in Java:


import java.awt.*;
import java.awt.event.*;

public class ButtonDemo extends Frame


{
Button b1, b2;
ButtonDemo ()
{
b1 = new Button ("OK");
b2 = new Button ("CANCEL");
this.setLayout (null);
b1.setBounds (100, 100, 80, 40);;
b2.setBounds (200, 100, 80, 40);
this.add (b1);
this.add (b2);
this.setVisible (true);
this.setSize (300, 300);
this.setTitle ("button");
this.addWindowListener (new WindowAdapter ()
{
public void windowClosing (WindowEvent we)
{
System.exit (0);
}
});
}
public static void main (String args[])
{
new ButtonDemo ();
}
}
Output:

AWT Canvas Control in java


Canvas encapsulates a blank window upon which you can draw in an
application or receive inputs created by the user.

Canvas Constructor:
1. Canvas() : Constructs a new Canvas.
2. Canvas (GraphicsConfiguration config) : Constructs a new Canvas
given a GraphicsConfiguration object.

Canvas Methods:
1. void addNotify(): It is used to create the peer of the canvas.
2. void createBufferStrategy(int numBuffers): It is used to create a
new strategy for multi-buffering on this component.
3. BufferStrategy getBufferStrategy(): It is used to return the
BufferStrategy used by this component.
Example to understand AWT Canvas Control in Java:
import java.awt.*;
import java.awt.event.*;

public class CanvasDemo


{
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public CanvasDemo ()
{
prepareGUI ();
}

public static void main (String[]args)


{
CanvasDemo awtControlDemo = new CanvasDemo ();
awtControlDemo.showCanvasDemo ();
}

private void prepareGUI ()


{
mainFrame = new Frame ("Java AWT Examples");
mainFrame.setSize (400, 400);
mainFrame.setLayout (new GridLayout (3, 1));
mainFrame.addWindowListener (new WindowAdapter ()
{
public void windowClosing (WindowEvent windowEvent)
{
System.exit (0);
}
});
headerLabel = new Label ();
headerLabel.setAlignment (Label.CENTER);
statusLabel = new Label ();
statusLabel.setAlignment (Label.CENTER);
statusLabel.setSize (350, 100);

controlPanel = new Panel ();


controlPanel.setLayout (new FlowLayout ());
mainFrame.add (headerLabel);
mainFrame.add (controlPanel);
mainFrame.add (statusLabel);
mainFrame.setVisible (true);
}

private void showCanvasDemo ()


{
headerLabel.setText ("Control in action: Canvas");
controlPanel.add (new MyCanvas ());
mainFrame.setVisible (true);
}
class MyCanvas extends Canvas
{
public MyCanvas ()
{
setBackground (Color.GRAY);
setSize (300, 300);
}

public void paint (Graphics g)


{
Graphics2D g2;
g2 = (Graphics2D) g;
g2.drawString ("It is a custom canvas area", 70, 70);
} }}
Output:

AWT Checkbox Control in java


A checkbox may be a control that’s used to turn an option on or off. It
consists of a little box that will either contain a check or not. There’s a
label related to each checkbox that describes what option the box
represents. You modify the state of a checkbox by clicking on.
Checkboxes are often used individually or as a part of a gaggle.
Checkboxes are objects of the Checkbox class.
Creating Checkbox : Checkbox cb = new Checkbox(Label);
Checkbox Constructor
1. Checkbox() throws HeadlessException: Creates a checkbox whose
label is initially blank. The state of the checkbox is unchecked.
2. Checkbox(String str) throws HeadlessException: Creates a
checkbox whose label is specified by str. The state of the checkbox
is unchecked.
3. Checkbox(String str, Boolean on) throws HeadlessException: It
allows you to line the initial state of the checkbox. If one is true,
the checkbox is initially checked; otherwise, it’s cleared.
4. Checkbox(String str, Boolean on, CheckboxGroup cbGroup)
throws HeadlessException or Checkbox(String str,
CheckboxGroup cbGroup, Boolean on) throws
HeadlessException: It creates a checkbox whose label is specified
by str and whose group is specified by cbGroup. If this checkbox
isn’t a part of a gaggle, then cbGroup must be null. the worth of
on determines the initial state of the checkbox.
Methods of Checkbox
1. boolean getState(): To retrieve the present state of a checkbox.
2. void setState(boolean on): To line its state, call setState(). Here, if
one is true, the box is checked. If it’s false, the box is cleared.
3. String getLabel(): you’ll obtain the present label related to a
checkbox by calling getLabel().
4. void setLabel(String str): To line the label, call setLabel(). The
string passed in str becomes the new label related to the invoking
checkbox.
import java.awt.*;
import java.awt.event.*;

public class Main extends Frame implements ItemListener {


String msg = "";
Checkbox winXP, winVista, solaris, mac;

public Main() {
setTitle("Checkbox Demo");
setSize(250, 200);
setLayout(new FlowLayout());
// Create checkboxes
winXP = new Checkbox("Windows XP", true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");

// Add checkboxes to frame


add(winXP);
add(winVista);
add(solaris);
add(mac);

// Add item listeners


winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);

// Add window listener to handle closing


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public void itemStateChanged(ItemEvent ie) {


repaint();
}

public void paint(Graphics g) {


msg = "Current state: ";
g.drawString(msg, 20, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 20, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 20, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 20, 140);
msg = " Mac OS: " + mac.getState();
g.drawString(msg, 20, 160);
}

public static void main(String[] args) {


Main demo = new Main();
demo.setVisible(true);
}
}
Output:

CheckboxGroup: Radio Buttons


It is possible to make a group of mutually exclusive checkboxes during
which one and just one checkbox up the group are often checked at
anybody time. These checkboxes are often called radio buttons because
they act just like the station selector on a car radio, only one station is
often selected at anybody’s time. To create a group of mutually
exclusive checkboxes, you want to first define the group to which
they’re going to belong then specify that group once you construct the
checkboxes. Checkbox groups are objects of the type CheckboxGroup.
Only the default constructor is defined, which creates an empty group.
Creating Radiobutton :
CheckboxGroup cbg = new CheckboxGroup();
Checkbox rb = new Checkbox(Label, cbg, boolean);
CheckboxGroup Methods
1. Checkbox getSelectedCheckbox(): You can determine which
checkbox in a group is currently selected by calling
getSelectedCheckbox().
2. void setSelectedCheckbox(Checkbox which): You can set a
checkbox by calling setSelectedCheckbox(). Here, is the checkbox
that you simply want to be selected. The previously selected
checkbox is going to be turned off.

Example to understand AWT CheckboxGroup Control in Java:

import java.awt.event.*;
import java.awt.*;

public class Main {


public static void main(String[] args)
{
Font fnt = new Font("Times New Roman", Font.BOLD, 18);
Font fnt1 = new Font("Arial1", Font.BOLD, 16);
Frame f = new Frame("My Frame");
f.setBackground(Color.cyan);
f.setSize(500,500);
f.setLocation(300,100);
f.setLayout(null);

Label l1 = new Label("Enter Name",Label.CENTER);


//l1.setText("Enter Name");
//l1.setSize(250,250);
l1.setBounds(100,100,120,40);
l1.setLocation(100,200);
l1.setBackground(Color.green);
l1.setFont(fnt);

Label l2 = new Label("Enter Class",Label.RIGHT);


//l2.setText();
//l1.setSize(250,250);
l2.setBounds(100,200,120,40);
l2.setLocation(100,250);
l2.setBackground(Color.green);
l2.setFont(fnt);

Button b1 = new Button("Click Me");


b1.setFont(fnt1);
b1.setSize(100,60);
b1.setBackground(Color.yellow);
b1.setLocation(100,300);

CheckboxGroup cbg = new CheckboxGroup();

Checkbox cb1 = new Checkbox("Cricket",cbg, true);


cb1.setLocation(450,150);
cb1.setBounds(250,200,100,50);
cb1.setFont(fnt1);
cb1.setBackground(Color.red);

Checkbox cb2 = new Checkbox("Singing",cbg,false);


//cb2.setLocation(450,250);
cb2.setBounds(250,240,100,50);
cb2.setFont(fnt1);
cb2.setBackground(Color.yellow);

Checkbox cb3 = new Checkbox("Dancing",cbg,false);


// cb3.setLocation(450,300);
cb3.setBounds(250,280,100,50);
cb3.setFont(fnt1);
cb3.setBackground(Color.green);

f.add(cb1);
f.add(cb2);
f.add(cb3);

f.add(l1);
f.add(l2);
f.add(b1);

f.setVisible(true);

f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
}

You might also like