0% found this document useful (0 votes)
2 views

BSC_2ndsem_java_lecture_12_AWT_Fundamentals

The document introduces the Abstract Window Toolkit (AWT), Java's first GUI framework, which is used for creating applets and standalone GUI applications. It details various AWT classes, window fundamentals, and how to create and manage frame windows, including event handling and graphics methods. Additionally, it provides code examples for creating AWT-based applications and handling mouse and keyboard events.

Uploaded by

aayushagp999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

BSC_2ndsem_java_lecture_12_AWT_Fundamentals

The document introduces the Abstract Window Toolkit (AWT), Java's first GUI framework, which is used for creating applets and standalone GUI applications. It details various AWT classes, window fundamentals, and how to create and manage frame windows, including event handling and graphics methods. Additionally, it provides code examples for creating AWT-based applications and handling mouse and keyboard events.

Uploaded by

aayushagp999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Introducing AWT

•The Abstract Window Toolkit (AWT) was Java’s first


GUI framework. ( Others are Swing and javaFX)
• AWT is used to create both Applets and stand alone
GUI based programs.
•The AWT classes are contained in the java.awt
package.
Web Resources: For AWT tutorial
(1) www.roseindia.net/java/example/java/awt/index.shtml
(2) www.tutorialpoints.com/awt/index.html
Few AWT classes
Class Description
AWTEvent Encapsulates AWT events.
AWTEventMulticaster Dispatches events to multiple
listeners.
BorderLayout The border layout manager. Border layouts
use five components: North, South, East,
West, and Center.
Button Creates a push button control.
Canvas A blank, semantics-free window.
CardLayout The card layout manager. Card layouts
emulate index cards. Only the one on top
is showing.
Checkbox Creates a check box control.
CheckboxGroup Creates a group of check box
controls.
Continued..
CheckboxMenuItem Creates an on/off menu item.
Choice Creates a pop-up list.
Color Manages colors in a portable, platform-independent
fashion.
Component An abstract superclass for various AWT components.

Container A subclass of Component that can hold other


components.
Cursor Encapsulates a bitmapped cursor.
Dialog Creates a dialog window.
Dimension Specifies the dimensions of an object. The width is
stored in width, and the height is stored in height.

EventQueue Queues events.


FileDialog Creates a window from which a file can be selected.
Window Fundamentals
• 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.
Class hierarchy
Components and Container

• 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.
• Except for menus, all user interface elements that are
displayed on the screen and that interact with the
user are subclasses of Component.
• 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
Panels
• The Panel class is a concrete subclass of Container.
• Panel is the superclass for Applet. When screen
output is directed to an applet, it is drawn on the
surface of a Panel object.
• A Panel is a window that does not contain a title
bar, menu bar, or border.
• When an applet is seen inside a web browser
these items are not seen.
• When you run an applet using an applet viewer,
the applet viewer provides the title and border.
Window
• The Window class creates a top-level window.
• A top-level window is not contained within
any other object; it sits directly on the
desktop.
• Generally, Window objects are not created
directly. Instead, a subclass of Window called
Frame is created.
Frame and Canvas
• 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.
• Canvas are derived from Component,
• Canvas encapsulates a blank window upon
which you can draw.
Working with Frame Windows
• Frames are used to create child windows within
applets, and top-level or child windows for stand-
alone applications.
• Two Frame’s constructors are:
Frame( ) throws HeadlessException
Frame(String title) throws HeadlessException

• A HeadlessException is thrown if an attempt is


made to create a Frame instance in an
environment that does not support user
interaction.
Continued
• The dimensions of the window is set after it
has been created using setSize() method.
void setSize(int newWidth, int newHeight)
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. The dimensions are specified in
terms of pixels.
Continued
• The getSize( ) method is used to obtain the
current size of a window. One of its forms is
shown here:
Dimension getSize( );
• After a frame window has been created, it will
not be visible until you call setVisible( ).
void setVisible(boolean visibleFlag)
The component is visible if the argument to this
method is true. Otherwise, it is hidden
Continued..
• Title in a frame window can be changed using
setTitle( ):
void setTitle(String newTitle)
• A program must remove the 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 AWT-Based Applet
• For Creating a new frame window from within an
AWT-based applet-
• First, create a subclass of Frame then override
Frame’s methods and provide event handling.
• Next, override any of the standard applet
methods, such as init( ), start( ), and stop( ), to
show or hide the frame as needed. Finally,
implement the
• windowClosing( ) method of the WindowListener
interface, calling setVisible(false) when the
window is closed.
Example
// Create a child frame window from within an
applet.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AppletFrame" width=300
height=50>
</applet>
*/
Continued..
// Create a subclass of Frame.
class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);

// create an object to handle window events


MyWindowAdapter adapter = new
MyWindowAdapter(this);

// register it to receive those events


addWindowListener(adapter);
}
Note: addWindowListener(new MyWindowadapter(this);
Continued..
public void paint(Graphics g) {
g.drawString("This is in frame window", 10, 40);
}
} // end class
Continued..
class MyWindowAdapter extends WindowAdapter {
SampleFrame sampleFrame;
public MyWindowAdapter(SampleFrame
sampleFrame) {
this.sampleFrame = sampleFrame;
}
public void windowClosing(WindowEvent we) {
sampleFrame.setVisible(false);
}
}
Continued..
public class AppletFrame extends Applet {
Frame f;
public void init() {
f = new SampleFrame("A Frame Window");
f.setSize(250, 250);
f.setVisible(true);
}
public void start() {
f.setVisible(true);
}
public void stop() {
f.setVisible(false);
}
public void paint(Graphics g) {
g.drawString("This is in applet window", 10, 20);
}
}
Continued..
Handling Events in a Frame Window
• Since Frame is a subclass of Component, it
inherits all the capabilities defined by
Component.

• For example, you can override paint( ) to


display output, call repaint( ) when you need to
restore the window, and add event handlers.

• Whenever an event occurs in a window, the


event handlers defined by that window will be
called. Each window handles its own events.
Example
The following program creates an applet and a
window that responds to mouse events. The
main applet window also responds to mouse
events.
Experiment with this program to see that mouse
events are sent to the window in which the
event occurs.
Code..
// Handle mouse events in both child and applet
windows.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="WindowEvents" width=300
height=50>
</applet>
*/
Continued..
// Create a subclass of Frame.
class SampleFrame extends Frame
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX=10, mouseY=40;
int movX=0, movY=0;
SampleFrame(String title) {
super(title);
// register this object to receive its own mouse events
addMouseListener(this);
addMouseMotionListener(this);
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
Continued..
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
} // Is it required to give empty method here??
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 10;
mouseY = 54;
msg = "Mouse just entered child.";
repaint();
}
Continued..
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 10;
mouseY = 54;
msg = "Mouse just left child window.";
repaint();
}
// Handle mouse pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
Continued..
public void mouseReleased(MouseEvent me) {
mouseX = me.getX(); // save coordinates
mouseY = me.getY();
msg = "Up";
repaint();
} // Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
movX = me.getX();
movY = me.getY();
msg = "*";
repaint();
}
Continued..
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// save coordinates
movX = me.getX();
movY = me.getY();
repaint(0, 0, 100, 60);
}
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
g.drawString("Mouse at " + movX + ", " + movY, 10, 40);
}
}
Continued..
class MyWindowAdapter extends WindowAdapter {
SampleFrame sampleFrame;
// Constructor
public MyWindowAdapter(SampleFrame sampleFrame)
{
this.sampleFrame = sampleFrame;
}
public void windowClosing(WindowEvent we) {
sampleFrame.setVisible(false);
}
}
Continued..
// Applet window.
public class WindowEvents extends Applet
implements MouseListener, MouseMotionListener {
SampleFrame f;
String msg = "";
int mouseX=0, mouseY=10;
int movX=0, movY=0;
// Create a frame window.
public void init() {
f = new SampleFrame("Handle Mouse Events");
f.setSize(300, 200);
f.setVisible(true);
// register this object to receive its own mouse events
addMouseListener(this);
addMouseMotionListener(this);
}
Continued..
// Remove frame window when stopping applet.
public void stop() {
f.setVisible(false);
}
// Show frame window when starting applet.
public void start() {
f.setVisible(true);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
}
Continued..
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 24;
msg = "Mouse just entered applet window.";
repaint();
} // Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 24;
msg = "Mouse just left applet window.";
repaint();
}
Continued..
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
Continued..
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
movX = me.getX();
movY = me.getY();
msg = "*";
repaint();
} // Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// save coordinates
movX = me.getX();
movY = me.getY();
repaint(0, 0, 100, 20);
}
Continued..
// Display msg in applet window.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
g.drawString("Mouse at " + movX + ", " + movY, 0, 10);
}
}
output
Creating a Windowed Program
To create standalone AWT-based applications,
create an instance of the window or windows
inside main( ).
For example, the following program creates a
frame window that responds to mouse clicks
and keystrokes:
Code
import java.awt.*;
import java.awt.event.*;
// Create a frame window.
public class AppWindow extends Frame {
String keymsg = "This is a test.";
String mousemsg = "";
int mouseX=30, mouseY=30;
public AppWindow() {
addKeyListener(new MyKeyAdapter(this));
addMouseListener(new MyMouseAdapter(this));
addWindowListener(new MyWindowAdapter(this));
}
Continued..
public void paint(Graphics g) {
g.drawString(keymsg, 10, 40);
g.drawString(mousemsg, mouseX, mouseY);
}
// Create the window.
public static void main(String args[]) {
AppWindow appwin = new AppWindow();
appwin.setSize(new Dimension(300, 200));
appwin.setTitle("An AWT-Based Application");
appwin.setVisible(true);
}
}
Continued..
class MyKeyAdapter extends KeyAdapter {
AppWindow appWindow;
public MyKeyAdapter(AppWindow appWindow) {
this.appWindow = appWindow;
}
public void keyTyped(KeyEvent ke) {
appWindow.keymsg += ke.getKeyChar();
appWindow.repaint();
}
}
Continued..
class MyMouseAdapter extends MouseAdapter {
AppWindow appWindow;
public MyMouseAdapter(AppWindow appWindow) {
this.appWindow = appWindow;
}
public void mousePressed(MouseEvent me) {
appWindow.mouseX = me.getX();
appWindow.mouseY = me.getY();
appWindow.mousemsg = "Mouse Down at " +
appWindow.mouseX +
", " + appWindow.mouseY;
appWindow.repaint();
}
}
Continued..
class MyWindowAdapter extends WindowAdapter {
AppWindow appWindow;
public MyWindowAdapter(AppWindow
appWindow) {
this.appWindow = appWindow;
}
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
Continued..
Once created, a frame window takes on a life of
its own. Notice that main( ) ends with the call
to appwin.setVisible(true). However, the
program keeps running until you close the
window.
In essence, when creating a windowed
application, use main( ) to launch its top-level
window. After that, the program will function as
a GUI-based application, not like the console-
based program.
Output
Displaying Information Within a Window
• Window has the ability to present high-
quality text and graphics.
• The AWT includes several methods that
support graphics. 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 standalone application window.
• All output to a window takes place through a
graphics context
Continued..
A graphics context is encapsulated by the Graphics
class. Here are two ways in which a graphics context
can be obtained:
• It is passed to a method, such as paint( ) or
update( ), as an argument.
• It is returned by the getGraphics( ) method of
Component.
• The Graphics class defines a number of methods
that draw various types of objects, such as lines,
rectangles, and arcs. In several cases, objects can
be drawn edge-only or filled. Objects are drawn
and filled in the currently selected color, which is
black by default.
Introducing Graphics Methods
Drawing Lines
• Lines are drawn by means of the drawLine( )method,
void drawLine(int startX, int startY, int endX, int endY )
• The drawRect( ) and fillRect( ) methods display an
outlined and filled rectangle, respectively.
• void drawRect(int left, int top, int width, int height)
• void fillRect(int left, int top, int width, int height)
• The upper-left corner of the rectangle is at left, top.
The dimensions of the rectangle are specified by
width and height.
Drawing Rectangles
To draw a rounded rectangle, use
drawRoundRect( ) or fillRoundRect( ),

void drawRoundRect(int left, int top, int width,


int height, int xDiam, int yDiam)

void fillRoundRect(int left, int top, int width, int


height, int xDiam, int yDiam)
Drawing Ellipses and Circles
•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.
To draw an ellipse, use drawOval( ). To fill an ellipse, use
fillOval( ).
void drawOval(int left, int top, int width, int height)
void fillOval(int left, int top, int width, int height)
The ellipse is drawn within a bounding rectangle whose
upper-left corner is specified by left, top and whose
width and height are specified by width and height. To
draw a circle, specify a square as the bounding
rectangle
Drawing arcs

• Arcs can be drawn with drawArc( ) and fillArc( ), shown here:


void drawArc(int left, int top, int width, int height, int startAngle,
int sweepAngle)
void fillArc(int left, int top, int width, int height, int startAngle,int
sweepAngle)
• The arc is bounded by the rectangle whose upper-left corner is
specified by left, top 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 counter clockwise 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
Drawing Polygons
• It is possible to draw arbitrarily shaped figures using
drawPolygon( ) and fillPolygon( ),
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 these arrays is
specified by numPoints. There are alternative forms of
these methods in which the polygon is specified by a
Polygon object.
Drawing different shapes
• It is possible to draw arbitrarily shaped figures using
drawPolygon( ) and fillPolygon( )
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 these arrays is
specified by numPoints. There are alternative forms
of these methods in which the polygon is specified
by a Polygon object.
Demonstrating the Drawing Methods
// Draw graphics elements.
import java.awt.*;
import java.applet.*;
/*
<applet code="GraphicsDemo" width=350 height=700>
</applet>
*/
public class GraphicsDemo extends Applet {
public void paint(Graphics g) {
// Draw lines.
g.drawLine(0, 0, 100, 90);
g.drawLine(0, 90, 100, 10);
g.drawLine(40, 25, 250, 80);
Continued..
// Draw rectangles.
g.drawRect(10, 150, 60, 50);
g.fillRect(100, 150, 60, 50);
g.drawRoundRect(190, 150, 60, 50, 15, 15);
g.fillRoundRect(280, 150, 60, 50, 30, 40);
// Draw Ellipses and Circles
g.drawOval(10, 250, 50, 50);
g.fillOval(90, 250, 75, 50);
g.drawOval(190, 260, 100, 40);
Continued..
// Draw Arcs
g.drawArc(10, 350, 70, 70, 0, 180);
g.fillArc(60, 350, 70, 70, 0, 75);
// Draw a polygon
int xpoints[] = {10, 200, 10, 200, 10};
int ypoints[] = {450, 450, 650, 650, 450};
int num = 5;
g.drawPolygon(xpoints, ypoints, num);
}
}
Continued..
Sizing Graphics
To size a graphics object to fit the current size of the window
in which it is drawn. To do so, first obtain the current
dimensions of the window by calling getSize( ) on the window
object. It returns the dimensions of the window encapsulated
within a Dimension object. Once you have the current size of
the window, you can scale your graphical output accordingly.

To demonstrate this technique, here is an applet that will start


as a 200´200-pixel square and grow by 25 pixels in width and
height with each mouse click until the applet gets larger than
500´500. At that point, the next click will return it to 200´200,
and the process starts over. Within the window, a rectangle is
drawn around the inner border of the window; within that
rectangle, an X is drawn so that it fills the window. This applet
works in appletviewer, but it may not work in a browser
window.
code
// Resizing output to fit the current size of a window.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="ResizeMe" width=200 height=200>
</applet>
*/
public class ResizeMe extends Applet {
final int inc = 25;
int max = 500;
int min = 200;
Dimension d;
Continued..
public ResizeMe() {
addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
int w = (d.width + inc) > max?min :(d.width + inc);
int h = (d.height + inc) > max?min :(d.height + inc);
setSize(new Dimension(w, h));
}
}); // Annonymous Inner class is used
}
public void paint(Graphics g) {
d = getSize();
g.drawLine(0, 0, d.width-1, d.height-1);
g.drawLine(0, d.height-1, d.width-1, 0);
g.drawRect(0, 0, d.width-1, d.height-1);
}
}
Question and Answer
Question: Method drawstring() is an abstract method( method
with no body, then how does it work when called in paint?
Answer: drawstring() method is a method of Graphics class which
itself is an abstract class. The Graphics class provides the means to
access different graphics devices. It is the class that lets you draw
on the screen, display images, and so forth. Graphics is an abstract
class because working with graphics requires detailed knowledge of
the platform on which the program runs. The actual work is done
by concrete classes that are closely tied to a particular platform.
Your Java Virtual Machine vendor provides the necessary concrete
classes for your environment. One need not worry about the
platform-specific classes; once you have a Graphics object, you
can call all the methods of the Graphics class, confident that the
platform-specific classes will work correctly wherever your
program runs.
Continued…
Use g.getClass().getName() method to find out
the class which is providing methods of Graphics
class.

You might also like