0% found this document useful (0 votes)
44 views64 pages

VIPS Unit 3 AWT COMPONENTS, Event, Anonymous Class, Layout Manager

Uploaded by

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

VIPS Unit 3 AWT COMPONENTS, Event, Anonymous Class, Layout Manager

Uploaded by

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

Faculty : Dr.

Nishtha Kansal
Assistant Professor
VIPS
OBJECTIVE OF AWT
•The objectives of this chapter are:
• To discuss the classes present in the java.awt package
• To understand the inheritance hierarchy of the AWT
• To outline the basic structure of GUIs
• To show how to add components to containers
• To understand how to use Layout Managers
• To understand basic graphics processing under the AWT
AWT (Abstract Windowing Toolkit)

• The AWT classes are contained in the java.awt package.


• It is one of Java’s largest packages.
• AWT is heavyweight i.e. its components are using the resources of
OS.
AWT Hierarrchy chart:
AWT (Abstract Windowing Toolkit)
Components
• Component is an object having a graphical representation that can be
displayed on the screen and that can interact with the user. For
examples buttons, checkboxes, list and scrollbars of a graphical user
interface.
Container

• The Container is a component in AWT that can contain another


components like buttons, textfields,labels etc.
• The classes that extends Container class are known as container such
as Frame, Dialog and Panel.
• 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.
Window

• The window is the container that have no borders and menu bars.
• It should use frame, dialog or another window for creating a 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.
• You will use a subclass of Window called Frame.
Frame
• 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.
• The Frame is the container that contain title bar and can have menu
bars. It can have other components like button, textfield etc.
• When a Frame window is created by a stand-alone application rather
than an applet, a normal window is created.
Frame
 Frame defines a top-level Window with Borders and a Menu Bar
 Frames are more commonly used than Windows

Once defined, a Frame is a Container which can contain Components

Syntax
Frame aFrame = new Frame(“Hello World”);
aFrame.setSize(100,100);
aFrame.setLocation(10,10);
aFrame.setVisible(true);
Example of Frame
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not
visible
}
public static void main(String args[]){
First f=new First();
}}
Note The setBounds(int xaxis, int yaxis, int width, int
height) method is used in the above example that sets the
position of the awt button.
List AWT Component example
import java.applet.Applet;
import java.awt.List;
import java.awt.Color;
public class Demo extends Applet {
public void init() {
List l = new List(8, true);
l.add("Desktop");
l.add("Laptop");
l.add("Tablet");
l.add("Phone");
l.add("Kindle");
l.add("Screen");
l.add("System");
add(l);
setBackground(Color.blue); } }
Examples of GUI based Applications

• Following are some of the examples for GUI based applications.


•  Automated Teller Machine (ATM)
•  Airline Ticketing System
•  Information Kiosks at railway stations
•  Mobile Applications
•  Navigation Systems
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)
Example Drawing Rectangles

// Draw rectangles
import java.awt.*;
import java.applet.*;
/* <applet code="Rectangles" width=300 height=200> Sample output from this program is
shown here:

</applet>
*/

public class Rectangles extends Applet {


public void paint(Graphics g) {
g.drawRect(10, 10, 60, 50);
g.fillRect(100, 10, 60, 50);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
g.fillRoundRect(70, 90, 140, 100, 30, 40);
}
}
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)
/ Draw Ellipses import java.awt.*;
import java.applet.*;
/*
<applet code="Ellipses" width=300 height=200>
</applet>
*/

public class Ellipses extends Applet {


public void paint(Graphics g) {
g.drawOval(10, 10, 50, 50);
g.fillOval(100, 10, 75, 50);}}
User Interface Elements
• UI elements : Thes are the core visual elements the user eventually
sees and interacts with. GWT provides a huge list of widely used and
common elements varying from basic to complex .
• Layouts: They define how UI elements should be organized on the
screen and provide a final look and feel to the GUI (Graphical User
Interface). This part will be covered in Layout chapter.
• Behavior: These are events which occur when the user interacts with
UI elements. This part will be covered in Event Handling .
How to Use
Buttons?
public class TestButton extends Frame {
public TestButton(String title){
super(title);
Button hw = new Button("Hello World!");
add(hw);
}
….
}

13
UNIT- Abstract Window Toolkit
ButtonTest.java

// Displays a frame containing a single button.


// WARNING: Frame cannot be closed.
import java.awt.*;
// Driver class
public class ButtonTest {
public static void main(String[] args) {
Frame f = new ButtonTestFrame("Button Test");
f.setSize(150, 100);
f.setVisible(true);
}
}
// Frame class
class ButtonTestFrame extends Frame
{ public ButtonTestFrame(String
title) {
super(title);
setLayout(new FlowLayout());
add(b);b = new Button("Testing");
Button 14
}
UNIT-III} Abstract Window Toolkit
Adding Components to a
Frame
Frame created by the ButtonTest
program:

Pressing the “Testing” button has no effect.


21
Abstract Window
UNIT-III Toolkit
Adding Components to a Frame
 Instead of calling setSize, the main method in
ButtonTest could have called pack:
f.pack();
 pack makes the frame just large enough to
display the components within it:

 Regardless of whether setSize or pack is


called, the user can manually
22
resize the frame.
Abstract Window
UNIT-III Toolkit
Adding Components to a Frame

• It’s not necessary to have two separate classes,


(ButtonTest and ButtonTestFrame).
•  By moving the main method from ButtonTest to
ButtonTestFrame, the program could be condensed to one
class (ButtonTestFrame).

17

Abstract Window Toolkit UNIT-III


How to Use Labels?
public class TestLabel extends Frame {
public TestLabel(String title){
super(title);
Label label1 = new Label();
label1.setText("Label1");
Label label2 = new Label("Label2");
label2.setAlignment(Label.CENTER);
Label label3 = new Label("Label3");

add(label1,"North");
add(label2,"Center");
add(label3,"South");
}
}

Abstract Window Toolkit UNIT-III


How to Use
Checkboxes?
public class TestCheckbox extends Frame {
public TestCheckbox(String title){
super(title);

CheckboxGroup cbg = new


CheckboxGroup();
Checkbox cb1 = new
Checkbox("American
Express",cbg,false);
Checkbox cb2 = new Checkbox("Visa",cbg,false); Checkbox
cb3 = new Checkbox("Mastercard",cbg,true);
add(cb1,"North");
add(cb2,"Center");
add(cb3,"South");
}
Abstract Window Toolkit
… UNIT-III 25
How to Use
Choices?
public class TestChoice extends Frame {
public TestChoice(String title){
super(title);

Choice choice = new Choice();


choice.add("ichi");
choice.add("ni");
choice.add("san");
add(choice);
}

20

Abstract Window Toolkit UNIT-III


How to Use TextField & TextArea
public class TestText extends Frame {
public TestText(String title){
super(title);

TextField textField = new TextField(20);


TextArea textArea = new TextArea(5, 20);

textArea.setEditable(false);
textField.setText("TextField");
textArea.setText("TextArea Line1 \n TextArea Line2");

add(textField,"North");
add(textArea,"South");
}

}

Abstract Window Toolkit UNIT-III


How to Use
Lists?
public class TestList extends Frame {
public TestList(String title){
super(title);
List l = new List(2, true); //prefer 2 items visible
l.add("zero");
l.add("uno");
l.add("dos");
l.add("tres");
l.add("cuatro");
l.add("cinco");
l.add("seis");
l.add("siete");
l.add("ocho");
l.add("nueve");
add(l);
22
}
Abstract Window Toolkit UNIT-III
How to Use
Menus?
public class TestMenu extends Frame {
public TestMenu(String title){
super(title);

MenuBar mb = new MenuBar();


setMenuBar(mb);

Menu m1 = new Menu("Menu


1");

mb.add(m1);
MenuItem mi1_1 = new MenuItem("Menu Item 1_1"); m1.add(mi1_1);
m1.addSeparator();
MenuItem mi1_2 = new MenuItem("Menu Item 1_2"); m1.add(mi1_2);

Menu m2 = new Menu("Menu 2"); // mb.add(m2);


} m1.add(m2); 23
MenuItem mi2_1 = newWindow
Abstract CheckboxMenuItem("Menu
Toolkit Item 2_1");
UNIT-III… m2.add(mi2_1);
How to Use Canvases
and Graphics
Primitives?
For drawing geometric shapes, texts, and
images
An abstract class
– the extended class must override paint()
Line
Oval

RoundRectangle Rectangle

Polygon Arc
Abstract Window Toolkit UNIT-III 30
drawLine(x1,y1,x2,y2)

class MyCanvas extends Canvas {


public void paint(Graphics g)
{ g.setColor(Color.blue);
int x1 = 161, (x1,y1)
y1 =
186,
(x2,y2)
x2 = 181,
y2 = 206;
g.drawLine(x1,y1,x2,y2);
}

Abstract Window Toolkit UNIT-III 31


fillOval(x,y,w,h) drawOval(x,y,w,h)
g.setColor(Color.blue);
{
int x = 239,
y = 186,
w = 48,
h = 32;
g.fillOval(x,y,w,h);
}

26

Abstract Window Toolkit UNIT-III


fillPolygon(int[] xs, int[] ys)
drawPolygon(int[] xs, int[] ys)
g.setColor(Color.green);
{
int xs[] = {161,161,185,209,185,161};
int ys[] = {310,334,358,334,310,310};
g.fillPolygon(xs,ys,6);
}

Abstract Window Toolkit UNIT-III


fillRect(x,y,w,h)
drawRect(x,y,w,
h)
g.setColor(Color.pink);
{
int x = 239,
y = 248,
w = 48,
h = 32;
g.fillRect(x,y,
w,h);
}

Abstract Window Toolkit UNIT-III


fillRoundRect(x,y,w,h,rw,rh)
drawRoundRect(x,y,w,h,rw,rh)
g.setColor(Color.yellow);
{
int x = 161,
y = 248,
w = 48,
h = 32,
roundW = 25,
roundH = 25;
g.fillRoundRect(x,y,w,h,roundW,roundH)
;
}

Abstract Window Toolkit UNIT-III


fillArc(x,y,w,h,sa,a)
drawArc(x,y,w,h,sa,
a)
g.setColor(Color.orange);
{
int x = 239,
y = 310,
w = 48,
h = 48,
startAngle
= 20,
angle = 90;
g.fillArc(x,y,w,h,startAngle,angle)
;
}
Abstract Window Toolkit UNIT-III
drawString(s,x,
y) FontMetrics

(x,y)

Abstract Window Toolkit UNIT-III


drawString, Font, &
FontMetrics
class MyCanvas extends Canvas {

public void paint(Graphics g)


{ g.setFont(new
Font("Dialog",0,20)); FontMetrics
fm = g.getFontMetrics(); int x =
100;
int y = 100;
g.drawString("Hello",x,y);
y = y+fm.getHeight();
g.drawString("World",x,y)
;
}
Abstract Window Toolkit UNIT-III
}
drawImage(image,x,y,w,h,o
b)
Image im = Toolkit.getDefaultToolkit().getImage(name);

g.drawImage(im, x, y, w, h, observer);

Abstract Window Toolkit UNIT-III


drawImage
public class TestImage extends Frame {
Image im;

public TestImage(String title){


super(title);
im =
Toolkit.getDefaultToolk
it().getImage("jp2.jpg");
if (im==null)
{ System.out.println("No
image"); System.exit(0);
}
}
public void paint(Graphics g)
{ g.drawImage(im,0,0,im.getHeight(this),im.getWidth(this),th
is);
} …
UNIT-III}
Layout of Components

• BorderLayout
 GridLayout
– north, south, west, east & center – tabular form (rows &
• FlowLayout columns)
– left to right & top down  GridBagLayout
• CardLayout – tabular form(variable
– stack of panels row heights and
column widths)

Abstract Window Toolkit UNIT-III


Use Layout Managers
setLayout(new BorderLayout());
setLayout(new CardLayout(());
setLayout(new FlowLayout());
setLayout(new
GridLayout(rows,columns,xgap,
ygap));
Default layout managers
– Windows (Frames &
Dialogs)
• BorderLayout
Abstract Window Toolkit – Panels (Applets) UNIT-III
Border Layout (cont)
The regions of the BorderLayout are defined as
follows:

North

West Center East

South

Abstract Window Toolkit UNIT-III


How to Use
BorderLayout?
import java.awt.*;
public class TestBorderLayout {
public static void main(String[] args){
Frame f = new Frame("TestBorderLayout");
f.setSize(200,200);
f.add("North", new Button("North"));
f.add("South", new Button("South"));
f.add("East", new Button("East"));
f.add("West", new Button("West"));
f.add("Center", new Button("Center"));
f.setVisible(true);
}
}
Abstract Window Toolkit UNIT-III
How to Use
FlowLayout?
import java.awt.*;
public class TestFlowLayout {
public static void main(String[] args)
{ Frame f = new
Frame("TestFlowLayout");
f.setSize(200,200);
f.setLayout(new FlowLayout());
f.add(new Button("Button 1"));
f.add(new Button("Button 2"));
f.add(new Button("Button 3"));
f.add(new Button("Button 4"));
f.add(new
f.setVisible(true);
Button("Button 5"));
}
Abstract Window Toolkit } UNIT-III
How to Use CardLayout?
import java.awt.*;

public class TestCardLayout {


public static void main(String[] args)
{ Frame f = new Frame("TestCard
Layout"); f.setSize(200,200);
f.setLayout(new CardLayout());
f.add("GraphicsPanel",new
GraphicsPanel()); f.add("LabelPanel",new
LabelPanel()); f.add("ButtonPanel",new
ButtonPanel());
f.setVisible(true);
}
Abstract Window Toolkit } UNIT-III
How to Use GridLayout?
import java.awt.*;
public class TestGridLayout {
public static void main(String[] args)
{ Frame f = new
Frame("TestGridLayout");
f.setSize(200,200);
f.setLayout(new GridLayout(2,3));
f.add(new Button("Button 1"));
f.add(new Button("Button 2"));
f.add(new Button("Button 3"));
f.add(new Button("Button 4"));
f.add(new Button("Button 5"));
f.setVisible(true);
}
Events
What is an Event?
An event is an object that describes a state change in a source.

Changing the state of an object is known as an event. For example, click on


button, dragging mouse etc. The java.awt.event package provides many event
classes and Listener interfaces for event handling.
Event Sources
A source is an object that generates an event. This occurs when the internal
state of that object changes in some way. Sources may generate more than one
type of event.
public void addTypeListener(TypeListener el)
Event Sources

public void addTypeListener(TypeListener el)


Type is the name of the event, and
 el is a reference to the event listener.
When such an event occurs, the registered listener is notified.
This is known as unicasting the event.
A source must also provide a method that allows a listener to
unregister an interest in a specific type of event.
The general form of such a method is this:
public void removeTypeListener(TypeListener el)
Event Listeners

• A listener is an object that is notified when an event occurs. It has two


major requirements.
• First, it must have been registered with one or more sources to receive
notifications about specific types of event.
• Second, it must implement methods to receive and process these
notifications.
• For example, the MouseMotionListener interface defines two
methods to receive notifications when the mouse is dragged or
moved.
The ActionEvent Class

• An ActionEvent is generated when a button is pressed, a list item is


double-clicked, or a menu item is selected. The ActionEvent class
defines four integer constants that can be used to identify any
modifiers associated with an action event: ALT_MASK,
CTRL_MASK, META_MASK, and SHIFT_MASK.
Event Classes
At the root of the Java event class hierarchy is EventObject, which is in
java.util. It is the superclass for all events. Its one constructor is shown
here:
EventObject(Object src)
Here, src is the object that generates this event.
EventObject contains two methods: getSource( ) and toString( ). The
getSource( ) method returns the source of the event. Its general form is
shown here:
Object getSource( )
 toString( ) returns the string equivalent of the event.
Table:Main Event Classes in
java.awt.event
The ActionEvent Class

• ActionEvent has these three constructors:


ActionEvent(Object src, int type, String cmd)
ActionEvent(Object src, int type, String cmd, int modifiers)
ActionEvent(Object src, int type, String cmd, long when, int modifiers)
• src is a reference to the object that generated this event.
• The type of the event is specified by type, and its command string is cmd.
• The argument modifiers indicates which modifier keys (ALT, CTRL,
META, and/or SHIFT) were pressed when the event was generated.
• The when parameter specifies when the event occurred.
Button event
• A push button is a component that contains a label and that generates
an event when it is pressed. Push buttons are objects of type Button.
Button defines these two constructors:
• Button( ) throws HeadlessException
• Button(String str) throws HeadlessException
• The first version creates an empty button.
• The second creates a button that contains str as a label.
Example of Creating a Frame
Window in an Applet

Create a subclass of Frame.


Override any of the standard applet methods, such as init( ),
start( ), and stop( ).
Implement the windowClosing( ) method of the WindowListener
interface, calling setVisible(false) when the window is closed.
Example of Creating a Frame Window in an Applet
• // Create a child frame window from within an applet. class MyWindowAdapter extends WindowAdapter {
import java.awt.*; SampleFrame sampleFrame;
import java.awt.event.*; import java.applet.*; /* public MyWindowAdapter(SampleFrame
sampleFrame)
<applet code="AppletFrame" width=300 height=50>
{ this.sampleFrame = sampleFrame;}
</applet> */
public void windowClosing(WindowEvent we)
// Create a subclass of Frame.
{ sampleFrame.setVisible(false); } }
class SampleFrame extends Frame { // Create frame window.
SampleFrame(String title) { super(title); public class AppletFrame extends Applet {
// create an object to handle window events Frame f;
MyWindowAdapter adapter = new MyWindowAdapter(this); public void init() {
// register it to receive those events
f = new SampleFrame("A Frame Window");
f.setSize(250, 250); f.setVisible(true);}
addWindowListener(adapter);
public void start() { f.setVisible(true); }
}
public void stop() { f.setVisible(false); }
public void paint(Graphics g) { public void paint(Graphics g) {
g.drawString("This is in frame window", 10, 40); g.drawString("This is in applet window", 10, 20); } }
}}
Creating a Frame Window in an Applet

Output :

The following applet creates a subclass


of Frame called SampleFrame.
A window of this subclass is instantiated
within the init( ) method of AppletFrame.
Notice that SampleFrame calls Frame’s
constructor. This causes a standard frame
window to be created with the title
passed in title. This example overrides
the applet’s start( ) and stop( ) methods
so that they show and hide the child
window, respectively.
Adapter Anonymous Class
 One most important special feature provided by Java, called an adapter class.
Adapter classes are useful when you want to receive and process only some of the
events not all that are handled by a particular event listener interface (if you have 5
event method for particular event e.g MouseEvent but you want to implement
only 1 or 2 method only) .
For example, the MouseMotionAdapter class has two methods,
 mouseDragged( )
 mouseMoved( )
 These are the methods defined by the MouseMotionListener interface. If you were
interested in only mouse drag events, then you could simply extend
MouseMotionAdapter and override mouseDragged( ). The empty implementation(not
implemented) of mouseMoved( ) would handle the mouse motion events for you.
Adapter Anonymous Class

• Its init( ) method creates an instance of MyMouseAdapter and


registers that object to receive notifications of mouse events. It also
creates an instance of MyMouseMotionAdapter and registers that
object to receive notifications of mouse motion events.
Annonymous adapter Class Example
// Demonstrate an adapter. // Handle mouse clicked.
import java.awt.*; public void mouseClicked(MouseEvent me) {
import java.awt.event.*; adapterDemo.showStatus("Mouse clicked");
import java.applet.*;
/*applet code="AdapterDemo" width=300 height=100>
}}
</applet>*/ class MyMouseMotionAdapter extends
public class AdapterDemo extends Applet { MouseMotionAdapter {
public void init() { AdapterDemo adapterDemo;
addMouseListener(new MyMouseAdapter(this)); public MyMouseMotionAdapter(AdapterDemo
addMouseMotionListener(new adapterDemo) {
MyMouseMotionAdapter(this));
}}
this.adapterDemo = adapterDemo;
class MyMouseAdapter extends MouseAdapter { }
AdapterDemo adapterDemo; // Handle mouse dragged.
public MyMouseAdapter(AdapterDemo adapterDemo) { public void mouseDragged(MouseEvent me) {
this.adapterDemo = adapterDemo;
}
adapterDemo.showStatus("Mouse dragged");
}}
Annonymous adapter Class Example
• Note :In the given example
Output: MouseMotionListener
and MouseListener interfaces
saves you a considerable amount
of effort and prevents your code
from becoming cluttered with
empty methods.
Anonymous Inner Classes Example

An anonymous inner class is // Anonymous inner class demo.


one that is not assigned a name. import java.applet.*;
import java.awt.event.*;
 Consider the applet shown in
/*<applet code="AnonymousInnerClassDemo"
the following Example listing. width=200 height=100></applet>*/
Given example goal is to display public class AnonymousInnerClassDemo extends
the string “Mouse Pressed” in Applet { public void init() {
the status bar of the applet addMouseListener(new MouseAdapter() {
viewer or browser when the public void mousePressed(MouseEvent me) {
mouse is pressed. showStatus("Mouse Pressed");}
});}}

You might also like