AJAY CHAKRAVARTY
A.P.
CCSIT, TMU Moradabad
1
What is AWT?
Abstract Window Toolkit (AWT) is a collection of graphical user interface (GUI)
components (widgets) and other related services required for GUI programming
in Java. It is Java’s original platform-independent windowing, graphics and user-
interface widget tool kit. AWT is now part of Java Foundation Classes (JFC) and
serves as the standard application programming interface (API) for GUI
programming in Java.
2
Windows Fundamental
The AWT defines windows according
to a class hierarchy that adds
functionality and specificity with each
level. The two most common
windows are those derived from
Panel, which is used by applets, and
those derived from Frame, which
creates a standard application
window. Much of the functionality of
these windows is derived from their
parent classes. Thus, a description of
the class hierarchies relating to these
two classes is fundamental to their
understanding. Figure shows the
class hierarchy for Panel and Frame.
Let’s look at each of these classes
now. 3
Windows Fundamental
Component
At the top of the AWT hierarchy is the Component class. Component is an abstract
class that encapsulates all of the attributes of a visual component. All user interface
elements that are displayed on the screen and that interact with the user are
subclasses of Component. It defines over a hundred public methods that are
responsible for managing events, such as mouse and keyboard input, positioning
and sizing the window, and repainting. A Component object is responsible for
remembering the current foreground and background colors and the currently
selected text font.
Container
The Container class is a subclass of Component. It has additional methods that
allow other Component objects to be nested within it. Other Container objects can
be stored inside of a Container (since they are themselves instances of Component).
This makes for a multileveled containment system. A container is responsible for
laying out (that is, positioning) any components that it contains.
4
Windows Fundamental
5
Windows Fundamental
Panel
The Panel class is a concrete subclass of Container. It doesn’t add any new
methods; it simply implements Container. A Panel may be thought of as a
recursively nestable, concrete screen component. Panel is the superclass for Applet.
When screen output is directed to an applet, it is drawn on the surface of a Panel
object. In essence, a Panel is a window that does not contain a title bar, menu bar,
or border. This is why you don’t see these items when an applet is run inside a
browser. When you run an applet using an applet viewer, the applet viewer provides
the title and border.
Other components can be added to a Panel object by its add( ) method (inherited
from Container). Once these components have been added, you can position and
resize them manually using the setLocation(), setSize(),
setPreferredSize(),orsetBounds() methods defined by Component.
6
Windows Fundamental
Window
The Window class creates a top-level window. Atop-level window is not contained
within any other object; it sits directly on the desktop. Generally, you won’t create
Window objects directly. Instead, you will use a subclass of Window called Frame,
described next.
Frame
Frame encapsulates what is commonly thought of as a “window.” It is a subclass of
Window and has a title bar, menu bar, borders, and resizing corners. If you create a
Frame object from within an applet, it will contain a warning message, such as “Java
Applet Window,” to the user that an applet window has been created. This message
warns users that the window they see was started by an applet and not by software
running on their computer. (An applet that could masquerade as a host-based
application could be used to obtain passwords and other sensitive information
without the user’s knowledge.) When a Frame window is created by a stand-alone
application rather than an applet, a normal window is created.
7
Windows Fundamental
Canvas
Although it is not part of the hierarchy for applet or frame windows, there is one
other type of window that you will find valuable: Canvas. Canvas encapsulates a
blank window upon which you can draw.
8
Working with Graphics
The AWT supports a rich assortment of graphics methods. 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 corner and is 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:
• It is passed to an applet when one of its various methods, such as paint( ) or
update( ), is called.
• It is returned by the getGraphics( ) method of Component.
9
Display Lines
Lines are drawn by means of the drawLine( ) method, shown here:
void drawLine(int startX, int startY, int endX, int endY)
drawLine( ) displays a line in the current drawing color that begins at startX,startY
and ends at endX,endY.
10
Display Lines
11
Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle,
respectively.They are shown here:
void drawRect(int top, int left, int width, int height)
void fillRect(int top, int left, int width, int height)
The upper-left corner of the rectangle is at top,left. The dimensions of the rectangle
are specified by width and height.
12
Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle,
respectively.They are shown here:
void drawRect(int top, int left, int width, int height)
void fillRect(int top, int left, int width, int height)
The upper-left corner of the rectangle is at top,left. The dimensions of the rectangle are
specified by width and height. To draw a rounded rectangle, use drawRoundRect( ) or
fillRoundRect( ), both shown here:
void drawRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
void fillRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
A rounded rectangle has rounded corners. The upper-left corner of the rectangle is at
top,left. The dimensions of the rectangle are specified by width and height. The diameter
of the rounding arc along the X axis is specified by xDiam. The diameter of the rounding
arc along the Y axis is specified by yDiam. 13
Drawing Rectangles
14
Drawing Rectangles
15
Drawing Ellipses and Circles
To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These methods
are shown here:
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is specified
by top, left and whose width and height are specified by width and height. To draw
a circle, specify a square as the bounding rectangle.
16
Drawing Ellipses and Circles
17
Drawing Ellipses and Circles
18
Drawing Arc
Arcs can be drawn with drawArc( ) and fillArc( ), shown here:
void drawArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
The arc is bounded by the rectangle whose upper-left corner is specified by top,left and
whose width and height are specified by width and height. The arc is drawn from
startAngle through the angular distance specified by sweepAngle. Angles are specified in
degrees. Zero degrees is on the horizontal, at the three o’clock position. The arc is
drawn counterclockwise if sweepAngle is positive, and clockwise if sweepAngle is
negative. Therefore, to draw an arc from twelve o’clock to six o’clock, the start angle
would be 90 and the sweep angle 180.
19
Drawing Arc
20
Drawing Arc
21
Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon( ),
shown here:
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints)
The polygon’s endpoints are specified by the coordinate pairs contained within the x and
y arrays. The number of points defined by x and y is specified by numPoints. There are
alternative forms of these methods in which the polygon is specified by a Polygon object.
22
Drawing Polygons
23
Drawing Polygons
24
Working with Color
Color defines several constants (for example, Color.black) to specify a number of
common colors. You can also create your own colors, using one of the color constructors.
Three commonly used forms are shown here:
The first constructor takes three integers that specify the color as a mix of red, green,
and blue. These values must be between 0 and 255, as in this example:
new Color(255, 100, 100); // light red
The second color constructor takes a single integer that contains the mix of red, green,
and blue packed into an integer. The integer is organized with red in bits 16 to 23, green
in bits 8 to 15, and blue in bits 0 to 7.
25
Working with Color
Here is an example of this constructor:
int newRed = (0xff000000 | (0xc0 << 16) | (0x00 << 8) | 0x00);
Color darkRed = new Color(newRed);
The final constructor, Color(float, float, float), takes three float values (between 0.0 and
1.0) that specify the relative mix of red, green, and blue.
By default, graphics objects are drawn in the current foreground color. You can change
this color by calling the Graphics method setColor( ):
void setColor(Color newColor)
Here, newColor specifies the new drawing color. You can obtain the current color by
calling getColor( ), shown here:
Color getColor( ) 26
Working with Color
// Demonstrate color.
import java.awt.*;
import java.applet.*;
/*
<applet code="ColorDemo" width=300 height=200>
</applet>
*/
public class ColorDemo extends Applet
{
// draw lines
public void paint(Graphics g)
{
Color c1 = new Color(255, 100, 100);
Color c2 = new Color(100, 255, 100);
Color c3 = new Color(100, 100, 255);
27
Working with Color
g.setColor(c1);
g.drawLine(0, 0, 100, 100);
g.drawLine(0, 100, 100, 0);
g.setColor(c2);
g.drawLine(40, 25, 250, 180);
g.drawLine(75, 90, 400, 400);
g.setColor(c3);
g.drawLine(20, 150, 400, 40);
g.drawLine(5, 290, 80, 19);
g.setColor(Color.red);
g.drawOval(10, 10, 50, 50);
g.fillOval(70, 90, 140, 100);
28
Working with Color
g.setColor(Color.blue);
g.drawOval(190, 10, 90, 30);
g.drawRect(10, 10, 60, 50);
g.setColor(Color.cyan);
g.fillRect(100, 10, 60, 50);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
}
}
29
Working with Fonts
The AWT provides flexibility by abstracting font-manipulation operations and allowing for
dynamic selection of fonts. Fonts have a family name, a logical font name, and a face
name. The family name is the general name of the font, such as Courier. The logical
name specifies a category of font, such as Monospaced. The face name specifies a
specific font, such as Courier Italic.
30
Working with Fonts
31
Working with Fonts
32
Determining the Available Fonts
When working with fonts, often you need to know which fonts are available on your
machine. To obtain this information, you can use the getAvailableFontFamilyNames( )
method defined by the GraphicsEnvironment class. It is shown here:
String[ ] getAvailableFontFamilyNames( )
This method returns an array of strings that contains the names of the available font
families. In addition, the getAllFonts( ) method is defined by the GraphicsEnvironment
class. It is shown here:
Font[ ] getAllFonts( )
This method returns an array of Font objects for all of the available fonts. Since these
methods are members of GraphicsEnvironment, you need a GraphicsEnvironment
reference to call them.
33
Determining the Available Fonts
You can obtain this reference by using the getLocalGraphicsEnvironment() static
method, which is defined by GraphicsEnvironment. It is shown here:
static GraphicsEnvironment getLocalGraphicsEnvironment( )
// Display Fonts
/*
<applet code="ShowFonts" width=550 height=60>
</applet>
*/
import java.applet.*;
import java.awt.*;
public class ShowFonts extends Applet
{
34
Determining the Available Fonts
public void paint(Graphics g)
{
String msg = "";
String FontList[];
GraphicsEnvironment ge =GraphicsEnvironment.getLocalGraphicsEnvironment();
FontList = ge.getAvailableFontFamilyNames();
for(int i = 0; i < FontList.length; i++)
msg += FontList[i] + " ";
g.drawString(msg, 4, 16);
}
}
35
Creating and Selecting Fonts
To select a new font, you must first construct a Font object that describes that font. One
Font constructor has this general form:
Font(String fontName, int fontStyle, int pointSize)
Here, fontName specifies the name of the desired font. The name can be specified using
either the logical or face name. All Java environments will support the following fonts:
Dialog, DialogInput, Sans Serif, Serif, and Monospaced. Dialog is the font used by your
system’s dialog boxes. Dialog is also the default if you don’t explicitly set a font. You can
also use any other fonts supported by your particular environment, but be careful—these
other fonts may not be universally available.
The style of the font is specified by fontStyle. It may consist of one or more of these
three constants: Font.PLAIN, Font.BOLD, and Font.ITALIC. To combine styles, OR
them together. For example, Font.BOLD | Font.ITALIC specifies a bold, italics style.
36
Creating and Selecting Fonts
To use a font that you have created, you must select it using setFont( ), which is defined
by Component. It has this general form:
void setFont(Font fontObj)
Here, fontObj is the object that contains the desired font.
// Show fonts.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="SampleFonts" width=200 height=100>
</applet>
*/
37
Creating and Selecting Fonts
public class SampleFonts extends Applet
{
int next = 0;
Font f;
String msg;
public void init()
{
f = new Font("Dialog", Font.PLAIN, 12);
msg = "Dialog";
setFont(f);
addMouseListener(new MyMouseAdapter(this));
}
public void paint(Graphics g)
{
g.drawString(msg, 4, 20);
}
}
38
Creating and Selecting Fonts
class MyMouseAdapter extends MouseAdapter
{
SampleFonts sampleFonts;
public MyMouseAdapter(SampleFonts sampleFonts)
{
this.sampleFonts = sampleFonts;
}
public void mousePressed(MouseEvent me)
{
// Switch fonts with each mouse click.
sampleFonts.next++;
switch(sampleFonts.next)
{
case 0:
sampleFonts.f = new Font("Dialog", Font.PLAIN, 12);
sampleFonts.msg = "Dialog";
39
break;
Creating and Selecting Fonts
case 1:
sampleFonts.f = new Font("DialogInput", Font.PLAIN, 12);
sampleFonts.msg = "DialogInput";
break;
case 2:
sampleFonts.f = new Font("SansSerif", Font.PLAIN, 12);
sampleFonts.msg = "SansSerif";
break;
case 3:
sampleFonts.f = new Font("Serif", Font.PLAIN, 12);
sampleFonts.msg = "Serif";
break;
case 4:
sampleFonts.f = new Font("Monospaced", Font.PLAIN, 12);
sampleFonts.msg = "Monospaced";
break;
}
40
Creating and Selecting Fonts
if(sampleFonts.next == 4) sampleFonts.next = -1;
sampleFonts.setFont(sampleFonts.f);
sampleFonts.repaint();
}
41