AWT and Applet in Java With Examples
AWT and Applet in Java With Examples
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;
/*
<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;
/*
<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.
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.
/*
<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);
}
repaint ();
t.sleep (1000); // interval given in milliseconds
}
}
catch (Exception e)
{
}
}
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.
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.
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.
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.
2. Create the object of any class that extends the Frame class.
MyFrame mf = new MyFrame();
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?
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:
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.
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 CanvasDemo ()
{
prepareGUI ();
}
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");
import java.awt.event.*;
import java.awt.*;
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);
}
});
}
}