[go: up one dir, main page]

0% found this document useful (0 votes)
33 views99 pages

UNIT-5 OOP Lecture Notes

oops

Uploaded by

bhargavialluri30
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)
33 views99 pages

UNIT-5 OOP Lecture Notes

oops

Uploaded by

bhargavialluri30
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/ 99

Unit- 5 - AWT

Java AWT : AWT Features :


➢Java AWT (Abstract Window Toolkit) is an
➢ A set of native user interface components.
API to develop GUI or window-based applications
in java. ➢ A robust Event-handling model.

➢API (Application Programming Interface), it ➢ Graph ics and imaging tools, including
is a collection of classes, interfaces, and
shapes, colour, and font classes.
subpackages helps to develop the program.
➢Java AWT components are platform- ➢ Layout managers, for flexible window layouts

dependent. that do not depend on a particular window size or


➢AWT is heavyweight i.e., its components are
screen resolution.
using the resources of OS.
➢The java.awt package provides classes for ➢ Data transfer classes, for cut-and-paste through

AWT API such as TextField, Label, TextArea, the native platform clipboard.
RadioButton, CheckBox, Choice, List etc.
1
AWT Class Hierarchy

Java AWT Classes:


➢ The AWT classes are contained in the
java.awt package. It is one of Java’s largest
packages.
➢ Component is the base class or abstract
class that encapsulates all 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 many public methods that are
responsible for managing events, such as
mouse and keyboard input, positioning
and sizing the window, and repainting.
2
AWT Class Hierarchy
Java AWT Classes:
➢ Container class is the sub class of
Component.
▪ The Container is a component in AWT that
can contain another components like
buttons, textfields, labels etc.
▪ It has additional methods that allow other
Component objects to be nested within it.
▪ Container is responsible for laying out
(that is, positioning) any components that
it contains, using various Layout
Managers.
▪ The classes that extends Container class are
known as container such as Frame, Dialog
and Panel.
3
AWT Class Hierarchy
Java AWT Classes:
➢ Window class creates a top-level window.
▪ A top-level window is not contained within any
object; it sits directly on the desktop.
▪ The window is the container that have no borders
and menu bars.
▪ Window objects are won’t created directly instead
we must use the subclass Frame or Dialog for
creating a window.
➢ Frame is the subclass of Window and has a
title bar, menu bar, borders, and resizing
corners.
▪ When a Frame window is created by an
application, a normal window is created.
▪ It can have other components like button,
textfields etc.
4
AWT Class Hierarchy
Java AWT Classes:
➢ Panel is the subclass of container.
▪ Panel is a window that does not contains a
title bar, menu bar and borders.
▪ Other components like button, textfields etc.
can be added to Panel object by it add()
method.
▪ Once these components have been added,
you can position and resize them manually
using the setLocation(), setSize(),
setPreferredSize(), or setBounds() methods
defined by Component.
➢ Canvas encapsulates a blank window upon
which you can draw.
▪ Canvas is one other type of window. 5
AWT Class Hierarchy

6
Build GUI using AWT

Steps :

➢ Create Container such as Frame or Dialog (for an application), or an Applet (for web

application). The job of Container is to hold and display Components.

➢ Create some Components, such as Button, TextField, List, Panels, etc. by creating an

object under the appropriate component subclass.

➢ Add your Components to your Container.

➢ Arrange, or layout your Components.

➢ Attach Listeners to your Components.

7
Methods of Component Class

8
Working with Frame (Container)
Frame :
▪ void setSize(int newWidth, int newHeight) -
➢ In Java, most of the AWT applications are
size of the window is specified by newWidth
created using Frame window.
and newHeight. The dimensions are specified
➢ Frame class has two different constructors,
in terms of pixels.
▪ Frame() – This form creates a standard
▪ Dimension getSize() - This method returns
window that does not contain a title.
the current size of the window contained
▪ Frame(String title) - This form creates a
within the width and height fields of a
window with the title specified by title.
Dimension object.
1. Creating a Frame : There are two ways to
3. Hiding and Showing a Window
create a GUI using Frame in AWT.
▪ void setVisible(boolean visibleFlag) - After a
▪ By Instantiating Frame class
frame window has been created, it will not be
▪ By extending Frame class
visible until you call setVisible().
2. Setting the Window’s Dimensions : It must
▪ The component is visible if the argument to
be set the size of the window after it has been
this method is true. Otherwise, it is hidden.
created.
9
I. Creating Frame Window by Instantiating Frame class

import java.awt.*;
public class Testawt
{
public Testawt()
{
Frame fm=new Frame(“GUI from LBRCE-CSE-A”);
//Creating a frame
Label lb = new Label("welcome to Java AWT Class");
//Creating a label
fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}

10
II. Creating Frame Window by Extending Frame class
import java.awt.*;
public class Testawt1 extends Frame
{
public Testawt1()
{
setTitle("LBRCE-CSE-B"); //setting title.

Button btn=new Button("Hello World - ClickMe");

add(btn); //adding a new Button.

setSize(400, 400); //setting size.

setLayout(new FlowLayout());//set default layout for


frame.

setVisible(true); //set frame visibility true.


}

public static void main (String[] args)


{
Testawt1 ta = new Testawt1(); //creating a frame.
}
}
11
Closing AWT Window (Frame)

➢ Closing the AWT Window or Frame can be done by calling dispose() or System.exit(0)

inside windowClosing() method.

➢ The windowClosing() method is found in WindowListener interface and

WindowAdapter class.

➢ There are many ways to override windowClosing() method.

▪ By inheriting (extends) WindowAdapter class

▪ By implementing WindowListener interface

12
I. By inheriting WindowAdapter class
import java.awt.*;
import java.awt.event.*;
public class Testawtc extends WindowAdapter
{
Testawtc()
{
Frame fm=new Frame("GUI from LBRCE-CSE-A");

fm.addWindowListener(this); // adding WindowListener


to the frame

Label lb = new Label("Welcome to Java AWT Class");


fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}

// overriding the windowClosing() method


public void windowClosing (WindowEvent e) {
System.exit(0); // or fm.dispose();
}
public static void main(String args[])
{
Testawtc tac = new Testawtc();
}} 13
II. By implementing WindowListener interface

import java.awt.*; public void windowActivated(WindowEvent e) {}


import java.awt.event.WindowEvent; public void windowIconified(WindowEvent e) {}
import java.awt.event.WindowListener;
public void windowOpened(WindowEvent e) {}
public class Testawtc1 extends Frame implements public void windowClosing(WindowEvent e) {
WindowListener
{ dispose();
public Testawtc1() }
{
addWindowListener(this); public void windowDeactivated(WindowEvent e) {}
setTitle("LBRCE-CSE-B"); //setting title. public void windowDeiconified(WindowEvent e) {}
Button btn=new Button("Hello World - ClickMe"); public void windowClosed(WindowEvent e) {}

add(btn); //adding a new Button.


public static void main (String[] args)
setSize(400, 400); //setting size. {
setLayout(new FlowLayout()); //set default Testawtc1 ta = new Testawtc1();
layout for frame. //creating a frame.
setVisible(true); //set frame visibilty true. }
} }
14
Points to Remember about AWT Window (Frame)

1. While creating a frame (either by instantiating or extending Frame


class), Following two attributes are must for visibility of the frame:
1. setSize(int width, int height);
2. setVisible(true);
2. When you create other components like Buttons, TextFields, etc. Then
you need to add it to the frame by using the method - add(Component's
Object);
3. You can add the following method also for resizing the frame -
setResizable(true);

15
Working with Panel (Container)
Panel :
▪ Panel is a window that does not contains a Panel p2=new Panel();
p2.setBackground(Color.blue);
title bar, menu bar and borders. Label lb2 = new Label("Panel 2 Blue");
▪ Other components like button, textfields etc. p2.add(lb2);
Button bt2 = new Button("Button 2");
can be added to Panel object by it add() p2.add(bt2);
add(p2);
method. }
Example : }
public class SamplePanel
import java.awt.*;
{
class SampleJavaPanel extends Frame
public static void main(String[] args)
{
{
SampleJavaPanel()
SampleJavaPanel panelframe = new
{
SampleJavaPanel();
setLayout(new FlowLayout());
Panel p1 = new Panel();
panelframe.setTitle("Java AWT Panels Example");
p1.setBackground(Color.red);
panelframe.setSize(500,300);
Label lb1 = new Label("Panel 1 Red");
panelframe.setVisible(true);
p1.add(lb1);
}
Button bt1 = new Button("Button 1");
}
p1.add(bt1);
add(p1);
16
Working with Panel (Container) - Output

17
setBounds() Method

The layout managers are used to automatically


decide the position and size of the added
components.
Syntax :
In the absence of a layout manager, the position
setBounds(int x-coordinate, int y-coordinate,
and size of the components must be set
int width, int height)
manually by using setBounds() method.
▪ This puts the upper left corner at location (x,
setBounds() :
y), where x the number of pixels from the left
▪ The setBounds() method needs four
of the screen and y is the number from the top
arguments. The first two arguments are x and
of the screen.
y coordinates of the top-left corner of the
▪ height and width are as before.
component, the third argument is
the width of the component, and the fourth
argument is the height of the component.

18
Panel with setBounds() Method - Example
import java.awt.*; Panel p2=new Panel();
class SampleJavaPanel extends Frame p2.setBackground(Color.blue);
{ p2.setBounds(350,100,200,50);
SampleJavaPanel()
{ add(p2);
setTitle("Java AWT Panels Example"); Label lb2 = new Label("Panel 2 Blue");
setSize(800,400);
setVisible(true); p2.add(lb2);
setLayout(null); Button bt2 = new Button("Button 2");

Panel p1 = new Panel(); p2.add(bt2);


p1.setBackground(Color.red); }
p1.setBounds(100,100,200,50);
public static void main(String[] args)
add(p1); {

Label lb1 = new Label("Panel 1 Red"); SampleJavaPanel panelframe = new


p1.add(lb1); SampleJavaPanel();
Button bt1 = new Button("Button 1");
p1.add(bt1); }
}
19
Panel with setBounds() Method - Ouput

20
Working with Dialog (Container)
import java.awt.*;
Dialog : public class SampleDialog
▪ The Dialog control represents a top-level {
public static void main(String[] args)
window with a border and a title used to take {
Frame frame = new Frame("Java AWT Dialog
some form of input from the user.
Example");
▪ It inherits the Window class. frame.setLayout(new FlowLayout());
frame.setSize(400, 400);
▪ Unlike Frame, it doesn't have maximize and frame.setBackground(Color.white);
frame.setVisible(true);
minimize buttons.
Dialog d1 = new Dialog(frame,"Java Dialog
Example", true);
Constructor : d1.setLayout(new FlowLayout());
d1.setSize(400, 200);
Dialog(Frame owner, String title, boolean d1.setBackground(Color.gray);
model)
Button bt1 = new Button("Button!!");
Constructs an initially invisible Dialog with the bt1.setSize(20,10);
d1.add(bt1);
specified owner Frame, title and modality. d1.setVisible(true);
}
}
21
Working with Dialog (Container) - Output

22
AWT Components

➢ A Component is an object with a graphical representation that can be displayed on the screen and

that can interact with the user.

➢ The Component class is the base and abstract parent of the nonmenu-related AWT components.

1. Button (java.awt.Button)

▪ To create a Button object, simply create an instance of the Button class by calling one of the

constructors. The most used constructor of the Button class takes a String argument, that gives

the Button object a text title.

▪ The two constructors are:


Button() // Constructs a Button with no label.
Button(String label) // Constructs a Button with the specified label.

▪ When a user presses on a Button object an event is generated. The label of the button that is

pressed can be obtained.


23
1. Button (java.awt.Button) - Example
import java.awt.*;
public class SampleButton
{ Output:
Button bt1, bt2, bt3;
SampleButton()
{
Frame f = new Frame("Java AWT Button
Example");
bt1= new Button();
bt2= new Button("Click here");
bt3= new Button();
bt3.setLabel("Button3");
/* Add Buttons on the Frame. */
f.add(bt1);
f.add(bt2);
f.add(bt3);
/* Set properties of the Frame. */
f.setLayout(new FlowLayout());
f.setSize(260,220);
f.setVisible(true);
}
public static void main(String[] ar) {
SampleButtonsb = new SampleButton();
}}
24
2. Checkboxes (java.awt.Checkbox)

2. Checkboxes (java.awt.Checkbox)

▪ Checkboxes are two states, on and off. The state of the button is returned as the Object

argument, when a Checkbox event occurs.

▪ To find out the state of a checkbox object we can use getState() that returns a true or

false value.

▪ To find the label of the checkbox using getLabel() that returns a String object.

Constructor:

Checkbox(String, boolean)

String indicates the content to be displayed for the checkbox.

Boolean – true indicates default selected item.


25
2. Checkboxes (java.awt.Checkbox) - Example
public class SampleCheckbox
{
SampleCheckbox()
{ Output:
Frame f= new Frame("Java AWT Checkbox
Example");
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
f.setBackground(Color.lightGray);

Checkbox cb1 = new Checkbox();


cb1.setBounds(100,100,50,50);
Checkbox cb2 = new Checkbox("Yes",true);
cb2.setBounds(180,100,50,50);
Checkbox cb3 = new Checkbox("No");
cb3.setBounds(270,100,50,50);

f.add(cb1);
f.add(cb2);
f.add(cb3);
}
public static void main(String[] ar) {
SampleCheckbox sc = new SampleCheckbox();
} }
26
3. Radio Buttons (java.awt.CheckboxGroup)

3. Radio Buttons (java.awt.CheckboxGroup)

▪ The CheckboxGroup class is used to group together a set of Checkbox buttons.

▪ Exactly one check box button in a CheckboxGroup can be in the "on" state at any

given time. Pushing any button sets its state to "on" and forces any other button that is

in the "on" state into the "off" state.

▪ The following code example produces a new check box group, with three check boxes:
CheckboxGroup cbg = new CheckboxGroup();
add(new Checkbox("one", cbg, true));
add(new Checkbox("two", cbg, false));
add(new Checkbox("three", cbg, false));

27
3. Radio Buttons (java.awt.CheckboxGroup) - Example
public class CheckboxGroupDemo
{
CheckboxGroupDemo() {
Frame ck_groupf= new Frame("CheckboxGrouping"); Output:
CheckboxGroup obj = new CheckboxGroup();

Checkbox ckBox1 = new Checkbox("CSM", obj, true);


ckBox1.setBounds(100,100, 50,50);

Checkbox ckBox2 = new Checkbox("IT", obj, false);


ckBox2.setBounds(100,150, 50,50);

Checkbox ckBox3 = new Checkbox("CSE", obj, false);


ckBox3.setBounds(100,200, 50,50);

ck_groupf.add(ckBox1);
ck_groupf.add(ckBox2);
ck_groupf.add(ckBox3);
ck_groupf.setSize(400,400);
ck_groupf.setLayout(null);
ck_groupf.setVisible(true);
}
public static void main(String args[]) {
new CheckboxGroupDemo(); }
}
28
4. Choice Buttons (java.awt.Choice)

▪ Choice Buttons displays a selection; however, it requires less space and allows us to add items to
the menu dynamically using the addItem() or add() method.
import java.awt.*; Button bt1= new Button("Submit");
public class SampleChoice f.add(lb1);
{ f.add(ch);
SampleChoice() f.add(bt1);
{ }
Frame f = new Frame("Java AWT Choice public static void main(String[] ar) {
Example"); SampleChoice sl = new SampleChoice();
f.setLayout(new FlowLayout()); }
f.setBackground(Color.lightGray); }
f.setSize(300,300);
f.setVisible(true);

Label lb1 = new Label("Select your country from


the Menu: ");
Choice ch = new Choice();
ch.addItem("India");
ch.addItem("Australia");
ch.addItem("America");
ch.addItem("Russia");
ch.addItem("France");
ch.addItem("China"); 29
5. List (java.awt.List)

▪ Creates a list with n items in the list. Specify the “n” elements in the constructor space and
allows us to add elements to the list using the add() method ONLY.
public class SampleList Button bt1= new Button("Submit");
{
SampleList() f.add(lb1);
{ f.add(list);
Frame f = new Frame("Java AWT Choice f.add(bt1);
Example"); }
f.setLayout(new FlowLayout()); public static void main(String[] ar) {
f.setBackground(Color.lightGray); SampleList sl = new SampleList();
f.setSize(300,300); }
f.setVisible(true); }
Label lb1 = new Label("Select your country from
the Menu: ");

List list = new List(6);


list.add("India");
list.add("Australia");
list.add("America");
list.add("Russia");
list.add("France");
list.add("China"); 30
6. TextField (java.awt.TextField)

6. TextFields (java.awt.TextField)

▪ Are areas where the user can enter text.

▪ They are useful for displaying and receiving text messages.

▪ We can make this textfield read-only or editable. We can use the setEditable(false) to

set a textfield read-only.

▪ There are numerous ways that we can construct a Textfield object:


TextField text1 = new TextField(); // no properties
TextField text2 = new TextField("Some text"); // a textfield with a predefined String
TextField text3 = new TextField(40); // a textfield with a predefined Size
TextField text4 = new TextField("Some text", 50); // combination of the two

31
6. TextArea (java.awt.TextArea)

The following are the constructors for a TextArea component :


TextArea(String text) // with the specified text.
TextArea(String text, int rows, int columns)
// with the specified text, and with the specified number of rows and columns.
TextArea(String text, int rows, int columns, int scrollbars)
// with the specified text, and with the rows, columns, and
// scroll bar visibility as specified either as SCROLLBARS_BOTH,
// SCROLLBARS_HORIZONTAL_ONLY, SCROLLBARS_NONE
// or SCROLLBARS_VERTICAL_ONLY

The TextArea object can be created as follows:


TextArea t = new TextArea("Test TextArea", 30, 5,
TextArea.SCROLLBARS_VERTICAL_ONLY);

32
6. TextArea (java.awt.TextArea) - Example
import java.awt.*;
public class TextAreaDemo1
{
TextAreaDemo1()
{
Frame textArea_f= new Frame();
TextArea area=new TextArea("Welcome to Java
Programming",30,5,TextArea.SCROLLBARS_BOTH
);

area.setBounds(30,40, 200,200);
textArea_f.add(area);
textArea_f.setSize(300,300);
textArea_f.setLayout(null);
textArea_f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaDemo1();
}
}
33
AWT Component - Example
import java.awt.*;
import java.awt.event.*; Choice choice = new Choice();
public class ComponentExam extends WindowAdapter choice.addItem("Choice Item 1");
{ choice.addItem("Choice Item 2");
ComponentExam() choice.addItem("Choice Item 3");
{ fm.add(choice);
Frame fm = new Frame("Example of Multiple
Components"); Label l = new Label("Test Label");
fm.setSize(600,300); fm.add(l);
fm.setVisible(true);
fm.setLayout(new FlowLayout()); TextField t = new TextField("Test TextField",30);
fm.addWindowListener(this); fm.add(t);
}
Button b = new Button("Test Button");
fm.add(b); public void windowClosing(WindowEvent e)
{
Checkbox cb = new Checkbox("Test System.exit(0);
Checkbox"); }
fm.add(cb); public static void main(String args[])
{
CheckboxGroup cbg = new CheckboxGroup(); ComponentExam CE = new ComponentExam();
fm.add(new Checkbox("CB Item 1", cbg, false)); }
fm.add(new Checkbox("CB Item 2", cbg, false)); }
fm.add(new Checkbox("CB Item 3", cbg, true));
34
AWT Component - Output

35
7. Canvas (java.awt.Canvas)

▪ Canvas class is a part of Java AWT. Canvas is a blank rectangular area where the user

can draw or trap input from the user.

▪ The canvas is used to provide a place to draw using mouse pointer. We can use it to get

user architectural user input.

▪ Canvas class inherits the Component class.

▪ public class Canvas extends Component.

Constructor of the Canvas class :

1.Canvas(): Creates a new blank canvas.

2.Canvas(GraphicsConfiguration c): Creates a new canvas with a specified graphics

configuration.
36
7. Canvas (java.awt.Canvas)

Graphics() - Constructs a new Graphics object.


5. drawLine(int x1, int y1, int x2, int y2) -
1. setColor() – Sets the color to the component.
Draws a line, using the current color, between
2. fillOval(int x, int y, int width, int height) –
the points (x1, y1) and (x2, y2) in this graphics
Create an Oval and filled with color.
context's coordinate system.
3. drawRect(int x, int y, int width, int height)
6. drawString(String str, int x, int y)
- Draws a highlighted outline of the specified
Draws the text given by the specified string,
rectangle.
using this graphics context's current font and
4. draw3DRect(int x, int y, int width, int
color.
height, boolean raised) - Draws a 3-D

highlighted outline of the specified rectangle.

37
7. Canvas (java.awt.Canvas) - Example

class MyCanvas extends Canvas


import java.awt.*; {
public class CanvasExample public MyCanvas() {
{ setBackground(Color.GRAY);
public CanvasExample() setBounds(100,80,500, 500);
{ }
Frame f = new Frame("Canvas Example"); public void paint(Graphics g)
f.setLayout(null); {
f.setSize(800, 800); g.setColor(Color.red);
f.setVisible(true); g.fillOval(75, 75, 100, 75);
g.setColor(Color.blue);
MyCanvas Myc = new MyCanvas(); g.drawOval(200, 75, 100, 75);
f.add(Myc); g.setColor(Color.green);
} g.draw3DRect(75,175,100,75,true);
public static void main(String args[]) g.setColor(Color.magenta);
{ g.drawRect(200,175,100,75);
new CanvasExample(); g.setColor(Color.yellow);
} g.drawLine(300,300,150,150);
} g.drawString("Welcome to Canvas
Graphics", 75,50);
} }
38
7. Canvas (java.awt.Canvas) – Output

39
8. MenuItem and Menu

➢ The object of MenuItem class adds a simple labeled menu item on menu. The items
used in a menu must belong to the MenuItem.
➢ The object of Menu class is a pull-down menu component which is displayed on the
menu bar. It inherits the MenuItem class.
Steps:
1. Create a Menu bar object under MenuBar class and attach that to a container frame
using setMenuBar().
2. Create a Menu (fields to be displayed on Menu Bar) using object of Menu class and
attach them to the bar.
3. Use the MenuItem class to create Menu items belongs to a particular Menu in the
MenuBar.
Note: Sub Menu’s created as Menu Items and attach them to Menu.
40
8. MenuItem and Menu - Example
class MenuDemo1 {
sub_menu1.add(b1);
MenuDemo1() {
sub_menu1.add(b2);
Frame menu_f= new Frame("LBRCE-CSE-A Menu
sub_menu1.add(b3);
and MenuItem Demo");
sub_menu1.add(b4);
menu_f.setSize(400,400);
Menu menu12 = new Menu("File (Shapes) ");
menu_f.setLayout(null);
menu_f.setVisible(true); Menu sub_menu12=new Menu("Sub Menu" );
//Create a Menu bar and set it to frame MenuItem x1=new MenuItem("Oval");
MenuBar menu_bar = new MenuBar(); MenuItem x2=new MenuItem("Rectangle");
menu_f.setMenuBar(menu_bar);
menu12.add(sub_menu12);
Menu menu11 = new Menu("File (Colors) ");
menu12.add(x1);
menu12.add(x2);
MenuItem a1=new MenuItem("Red");
menu_bar.add(menu12);
MenuItem a2=new MenuItem("Green");
Menu sub_menu1=new Menu("Sub Menu" ); MenuItem y1=new MenuItem("Circle");
MenuItem y2=new MenuItem("Round");
menu11.add(a1); MenuItem y3=new MenuItem("Square");
menu11.add(a2);
menu11.add(sub_menu1); sub_menu12.add(y1);
menu_bar.add(menu11); sub_menu12.add(y2);
MenuItem b1=new MenuItem("Light Red"); sub_menu12.add(y3);
MenuItem b2=new MenuItem("Drak Red"); }
MenuItem b3=new MenuItem("Light Green"); public static void main(String args[]) {
MenuItem b4=new MenuItem("Dark Green"); new MenuDemo1(); } }
41
8. MenuItem and Menu - Output

42
9. PopupMenu (java.awt.PopupMenu)
➢ PopupMenu can be dynamically popped up at specific position within a component. It inherits
the Menu class.
import java.awt.*;
import java.awt.event.*;
class PopupMenuDemo1 pop_menu.add(pop_cut);
{ pop_menu.add(pop_copy);
PopupMenuDemo1() pop_menu.add(pop_paste);
{
Frame pop_menuf= new Frame("LBRCE pop_menuf.addMouseListener(new MouseAdapter()
==>PopupMenu Demo"); {
pop_menuf.setSize(400,400); public void mouseClicked(MouseEvent a)
pop_menuf.setLayout(null); {
pop_menuf.setVisible(true); pop_menu.show(pop_menuf , a.getX(), a.getY());
}
PopupMenu pop_menu = new PopupMenu("*Edit*"); });
pop_menuf.add(pop_menu);
MenuItem pop_cut = new MenuItem("Cut"); }
pop_cut.setActionCommand("Cut"); public static void main(String args[])
{
MenuItem pop_copy = new MenuItem("Copy"); new PopupMenuDemo1();
pop_copy.setActionCommand("Copy"); }
}
MenuItem pop_paste = new MenuItem("Paste");
pop_paste.setActionCommand("Paste"); 43
9. PopupMenu (java.awt.PopupMenu)

44
Unit- 5 – AWT – Layout Manager

➢ The layout will specify the format or the order in ➢ Whenever a container is resized (or sized for the

which the components have got to be placed on the primary time), the layout manager is employed to

container. position each of the components within it.

➢ Layout Manager is responsible to rearrange the ➢ The setLayout( ) method has the subsequent

components on the container consistent with the general form:

required layout. void setLayout(LayoutManager layoutObj)


➢ A layout manager is an instance of any class that
➢ Here, layoutObj may be a regard to the specified
implements the LayoutManager interface.
layout manager, disable the layout manager and
➢ The layout manager is about by the setLayout( ) position components manually, by passing null for
method. layoutObj.

➢ If no call to setLayout( ) is formed, then the default ➢ Then the form and position of every sets

layout manager is employed. manually, using the setBounds() method defined by


Component.

1
Types of Layout Managers - BorderLayout

1. Border Layout :

➢ This layout will display the components along the border of the container.

➢ This layout contains five locations where the component can be displayed.

➢ Locations are North, South, East, west, and Center. The default region is the center.

➢ The above regions are the predefined static constants belongs to the BorderLayout class.

➢ Whenever if other regions’ spaces are not in use automatically container selects as a center region

default and component occupies surrounding region’s spaces of the window and that damages look

and feel of the user interface.

2
1. java.awt.BorderLayout

➢ The border layout provides a collection of public static final int NORTH: The North layout

constants used for positioning components. constant at top of the container.

➢ The regions discussed here identified by a public static final int SOUTH: The South layout

corresponding constant name NORTH, SOUTH,


constant at bottom of the container.
EAST, WEST, and the constant for the middle region public static final int CENTER:

as CENTER. The Center layout constant in the middle of the


container.
a
➢ Constants for each region used in our code public static final int WEST: The West layout
are listed below:
constant at the right of the container.

public static final int E AST: The E a st layout

constant at the left of the container.


3
BorderLayout Constructors
1. BorderLayout ( )
➢ BorderLayout Class is used to create a border layout but without gaps between the components.
import java.awt.*;
public static void main(String[] args)
public class border
{ {
border() new border();
{
Frame F = new Frame(); }
F.setSize(300, 300);
}
F.setVisible(true);

Button b1=new Button("**Button-1**");


Button b2=new Button("**Button-2**");
Button b3=new Button("**Button-3**");
Button b4=new Button("**Button-4**");
Button b5=new Button("**Button-5**");

F.add(b1,BorderLayout.NORTH);
F.add(b2,BorderLayout.SOUTH);
F.add(b3,BorderLayout.EAST);
F.add(b4,BorderLayout.WEST);
F.add(b5);
}
4
BorderLayout Constructors
2. BorderLayout (int hgap, int vgap)
BorderLayout (int hgap, int vgap) is also written as BorderLayout (int, int) is used to create a border layout with
the given horizontal (hgap) and vertical (vgap) gaps or spaces between the components.
public class borderlayout_spaces public static void main(String[] args)
{
public borderlayout_spaces() {
{
new borderlayout_spaces();
Frame F = new Frame("BorderLayout with Spaces");
F.setSize(400,300); }
F.setVisible(true); }
F.setLayout(new BorderLayout(20,30));
F.setBackground(Color.green);

Button b1=new Button("**North**");


F.add(b1,BorderLayout.NORTH); Button
b2=new Button("**EAST**");
F.add(b2,BorderLayout.EAST);
Button b3=new Button("**CENTER**");
F.add(b3,BorderLayout.CENTER); Button
b4=new Button("**WEST**");
F.add(b4,BorderLayout.WEST);
Button b5=new Button("**SOUTH**");
F.add(b5,BorderLayout.SOUTH);
} 5
2. java.awt.FlowLayout

Constructors in FlowLayout
➢ FlowLayout is one of AWT’s layout managers used
1.FlowLayout(): Constructs an instance of FlowLayout as
to arrange the components in a manner from left to
center-aligned and with 5 pixels gap between the
right, just like words in a paragraph.
components.
➢ When no. of components increases than the window
2.FlowLayout(int align): Constructs a
size, then by default, Java enables FlowLayout to FlowLayout with a given alignment with 5 pixels gap
arrange the components to fit in the windowpane. between the components.

➢ FlowLayout is the default layout provided by layout 3.FlowLayout(int align, int horizontalGap,
int verticalGap): Constructs a FlowLayout with a given
manager for Panel. And BorderLayout is default for
alignment and with a given horizontal and vertical gap
Frame, Dialog containers.
between the components.
➢ FlowLayout uses some default settings such as center ➢This constructor will align by the specified align field as
alignment with five pixels gaps between components RIGHT, LEFT or CENTER and also provides the option for

horizontally and vertically. adding horizontal gap and the vertical gap between
components.
6
FlowLayout Example-1
import java.awt.*; frame1.add(box8); frame1.add(box9); frame1.add(box10);
public class FlowDemo1 frame1.setLayout(new FlowLayout(FlowLayout.LEFT));
{
FlowDemo1() frame1.setSize(200,200); frame1.setVisible(true);
{ }
Frame frame1=new Frame(); public static void main(String[] args) { new FlowDemo1(); }
}
Button box1=new Button("1");
Button box2=new Button("2");
Button box3=new Button("3");
Button box4=new Button("4");
Button box5=new Button("5");
Button box6=new Button("6");
Button box7=new Button("7");
Button box8=new Button("8");
Button box9=new Button("9");
Button box10=new Button("10");

frame1.add(box1);
frame1.add(box2);
frame1.add(box3); 7
frame1.add(box4);
frame1.add(box5);
frame1.add(box6);
frame1.add(box7);
FlowLayout Example-2
import java.awt.*; public static void main(String[] args)
public class FlowLayoutDemo {
{
FlowLayoutDemo () new FlowLayoutDemo ();
{ }
Frame f = new Frame("FlowLayout for CSE-A"); Label l1 =
new Label ("Enter UserId"); TextField tf1 = new TextField }
(30);
Label l2 = new Label ("Password "); TextField tf2
= new TextField (30); Button b1 = new Button ("SUBMIT");

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

f.setLayout(new
FlowLayout(FlowLayout.CENTER, 30 ,20));
f.setSize (400, 250);
f.setVisible (true);
f.setBackground(Color.white);
}
8
3. java.awt.GridLayout

Constructors in GridLayout
➢ GridLayout divides the container into a grid
1. GridLayout() - Empty constructor with one column per
of cells called rows and columns.
component in a single row.
➢ It arranges the components in a rectangular grid.
2. GridLayout(int rows, int columns)-
➢ Each cell can accommodate only one
Constructor with a specified number of rows and
component, equally sized and equi-spaced with each
columns.
other.
▪ rows - the number of rows (value zero meaning
➢ According to Grid Layout Manager, the grid cannot
any number of rows).
be empty.
▪ columns - the number of columns (value zero meaning
➢ The default value of the
any number of columns).
ComponentOrientation property is that the
3. GridLayout(int rows, int columns,
orientation of the components is horizontal and
int horizontal gap, int vertical gap)
left-to-right.
▪ horizontal gap- between each of the columns
▪ vertical gap- between each of the rows
9
GridLayout Example-1
public class GridLayoutDemo
{
public static void main(String[] args)
{
Frame frame = new Frame("Grid Layout for CSE-A");
frame.setVisible(true);
frame.setSize(200,200);

Panel panel = new Panel();


panel.setBackground(Color.MAGENTA);
panel.setLayout(new GridLayout(2,2,5,10));
Button button1 = new Button("1");
Button button2 = new Button("2");
Button button3 = new Button("3");
Button button4 = new Button("4");

panel.setComponentOrientation(ComponentOrientation.LEFT
_TO_RIGHT);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);

frame.add(panel);
}} 10
GridLayout Example-2
public class GridLayoutDemo Panel p3 = new Panel ();
{ p3.setBackground(Color.blue);
GridLayoutDemo() f1.add (p3);
{
Frame f1 = new Frame("Grid of Different panel"); f1.setSize Label l2 = new Label ("Welcome to Java");
(250, 250); f1.add (l2);
f1.setVisible (true);
GridLayout ob = new GridLayout (2, 2); }
f1.setLayout (ob); public static void main (String[]args)
{
Panel p1 = new Panel (); new GridLayoutDemo();
p1.setBackground(Color.MAGENTA); }
}
Label l1 = new Label ("Enter name");
TextField tf = new TextField (10);
Button b1 = new Button ("Submit");

p1.add (l1);
p1.add (tf);
p1.add (b1);
f1.add (p1);

Panel p2 = new Panel ();


p2.setBackground(Color.green);
f1.add (p2); 11
4. java.awt.GridBagLayout

➢ In GridLayout manager there is not grid control i.e., inside a grid we cannot align the component in a specific
position.

➢ To overcome this problem, we have an advanced Layout Manager i.e., Grid Bag Layout Manager.
➢ This layout is the most efficient layout that can be used for displaying components. In this layout, we can specify
the location, size, of the components inside of the Grid.

➢ In this Layout manager, for each grid, we need to define grid properties or constraints.
➢ Based on grid properties, the layout manager aligns a component on the grid, and we can span multiple grids also
as per the requirement.
➢ Grid properties are defined using GridBagConstraints class. Each component in a GridBagLayout has its own
set of constraints, so you must associate an object of type.
➢ GridBagConstraints with each component before adding component to the container.

Creation of GridBagLayout:
GridBagLayout gbl = new GridBagLayout();

12
4. java.awt.GridBagLayout

In GridBagLayout, specify the location (or) the size with the help of GridBagConstraints.
Properties of GridBagConstraints:
Variable Role
These contain the coordinates of the origin of the grid i.e., specifying grid location.
gridx and gridy

For defining the number of grids to span a document. Define how many cells will
gridwidth, gridheight
occupy component (height and width). by The default is 1.

Defines the fate of a component smaller than the grid cell. GridBagConstraints.NONE
retains the original size: Default GridBagConstraints.HORIZONTAL expanded
horizontally GridBagConstraints.VERTICAL
fill GridBagConstraints.BOTH expanded vertically expanded to the dimensions of the cell

Used to define the horizontal and vertical expansion


ipadx, ipady of components. not works if expansion is
required by fill. The default value is (0,0).
weightx, weighty Used to define the distribution of space in case of change of dimension.
13
GridBagLayout Example-1
class GridBagLayoutExample extends Frame
class GridBagLayoutJavaExample
{
{
GridBagLayoutExample() {
public static void main(String args[])
Label lblName = new Label("Name");
{
TextField txtName =new TextField(10);
GridBagLayoutExample frame = new
Label lblcomments = new Label("Comments"); TextArea
GridBagLayoutExample();
TAreaComments=new TextArea(6,15); Button btnSubmit = new
frame.setTitle("GridBagLayout in Java Example");
Button("Submit");
frame.setSize(300,200);
setLayout(new GridBagLayout()); GridBagConstraints gc =new
frame.setVisible(true);
GridBagConstraints();
}
add(lblName,gc,0,0,1,1,0,0);
}
add(txtName,gc,1,0,1,1,0,20);
add(lblcomments,gc,0,1,1,1,0,0);
add(TAreaComments,gc,1,1,1,1,0,60);
add(btnSubmit,gc,0,2,2,1,0,20);
}
void add(Component comp,GridBagConstraints gc,int x,int
y,int w,int h,int wx,int wy) {
gc.gridx = x; gc.gridy =
y; gc.gridwidth = w;
gc.gridheight= h;
gc.weightx = wx;
gc.weighty = wy;
add(comp,gc); }
}
14
GridBagLayout Example-2
import java.awt.*; gc.gridx = 2;
public class GridBagLayoutDemo gc.gridy = 0; f1.add (b3, gc);
{
public static void main (String[]args) Button b4 = new Button ("Button4"); gc.gridx = 0;
{ gc.gridy = 1;
Frame f1 = new Frame (); f1.setSize (250, 250); gc.gridwidth = 3; f1.add(b4, gc);
GridBagLayout gb = new GridBagLayout (); f1.setLayout
(gb); Button b5 = new Button ("Button5"); gc.gridx = 2;
GridBagConstraints gc = new GridBagConstraints (); gc.gridy = 3;
gc.insets = new Insets (10, 0, 10, 0); f1.add (b5, gc);
f1.pack (); f1.setVisible (true);
Button b1 = new Button ("Button1"); Button b2 }
= new Button ("Button2"); Button b3 = new }
Button ("Button3");
gc.fill = GridBagConstraints.HORIZONTAL;

gc.weightx = 0.5;
gc.weighty = 0.5;
gc.gridx = 0; 15
gc.gridy = 0; f1.add
(b1, gc);

gc.gridx = 1;
gc.gridy = 0;
f1.add (b2, gc);
5. java.awt.CardLayout

➢ Unlike other layouts, the card layout will display the components of a container one at a time.
➢ Card Layout, as the name indicates, works like a deck of playing cards with only one card, i.e.,
the topmost card visible at a single time.
➢ It treats every component in a container as a Card, and the container acting as a Stack of cards.
➢ The ordering of the cards in a container is defined internally. When the container is displayed for the first time, it
is the first component present in the container that is visible at that time.

Constructors of CardLayout in Java :


1. CardLayout()
This constructor of Java class CardLayout is used to create a new CardLayout with the gaps of size
zero (0) between the different components.
2. CardLayout(int hgap, int vgap)
CardLayout with the horizontal and vertical gap between the components,
as arguments. hgap
denotes the horizontal gap, whereas vgap represents the vertical gap between the components.
16
5. java.awt.CardLayout

To add the components in CardLayout we use add method:

add(“Cardname”, Component);

Methods of CardLayout

1.first(Container): It is used to flip to the first card of the given container. 2.last(Container): It is used

to flip to the last card of the given container. 3.next(Container): It is used to flip to the next card of the

given container.

4.previous(Container): It is used to flip to the previous card of the given container.

5.show(Container, cardname): It is used to flip to the specified card with the given name.

17
CardLayout Example-1
import java.awt.*; import class CardLayoutJavaExample
java.awt.event.*; {
class CardLayoutExample extends Frame implements public static void main(String args[])
ActionListener {
{ CardLayoutExample frame = new
CardLayout card = new CardLayout(10,10); CardLayoutExample();
CardLayoutExample() frame.setTitle("CardLayout in Java Example");
{ frame.setSize(220,150);
setLayout(card); frame.setResizable(false);
Button Btnfirst = new Button("first "); Button frame.setVisible(true);
BtnSecond = new Button ("Second"); Button }
BtnThird = new Button("Third"); }

add(Btnfirst,"Card1");
add(BtnSecond,"Card2");
add(BtnThird,"Card3");

Btnfirst.addActionListener(this);
BtnSecond.addActionListener (this);
BtnThird.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
card.next(this);
} }
18
Unit- 5 – Event Handling
Event Classification of Events :
➢ An event can be defined as changing the state 1. Foreground Events
of an object or behavior by performing actions. ➢ Events that require user interaction to
➢ Activities that cause events to be generated generate, i.e., events are generated due to
are pressing a button, entering a character via interaction by the user on components in
the keyboard, selecting an item in a list, and GUI.
clicking the mouse. ➢ Interactions are nothing but clicking on a
➢ The java.awt.event package can be used to button, scrolling the scroll bar, cursor
provide various event classes. moments, etc.
2. Background Events
➢ Events that don’t require interactions of
users to generate are known as background
events. Examples of these events are
operating system failures/interrupts,
operation completion, etc. 1
Event Handling

➢ It is a mechanism to control the events and to decide what should happen after an
event occur.
➢ To handle the events, Java follows the Delegation Event model.

Delegation Event model


➢ It has Sources and Listeners.
➢ Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to
generate events.
➢ Listeners: Listeners are used for handling the events generated from the source. Each
of these listeners represents interfaces that are responsible for handling events.
➢ To perform Event Handling, it need to register the source with the listener.

2
Delegation Event model

3
Registering the Source With Listener
➢ A source must register listeners in order to receive the notifications about specific type
of event.
➢ Each type of event has its own registration method.
➢ Here is the general form:
public void addTypeListener (TypeListener el )
➢ Here, Type is the name of the event, and el is a reference to the event listener.
➢ For example, the method that registers a keyboard event listener is called
addKeyListener( ).

➢ 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 :
public void removeTypeListener(TypeListener el )
4
Event Classes and Listener Interfaces
➢ The java.awt.event package provides many event classes and Listener interfaces for event
handling.
➢ The class AWTEvent, defined within the java.awt package, is the superclass of all AWT-based
events used by the delegation event model.
➢ Its getID( ) method can be used to determine the type of the event. int getID( )
➢ The package java.awt.event defines many types of events that are generated by various user
interface elements.

Event Class Description Listener Interface


ActionEvent Generated when a button is pressed, a list item is double-
ActionListener
clicked, or a menu item is selected.
Generated when the mouse is dragged, moved, clicked,
MouseListener and
MouseEvent pressed, or released; also generated when the mouse
MouseMotionListener
enters or exits a component.
KeyEvent Generated when input is received from the keyboard. KeyListener
Generated when a window is activated, closed,
WindowEvent WindowListener
deactivated, deiconified, iconified, opened, or quit.
5
Event Classes and Listener Interfaces
➢ Listener Interfaces contains abstract methods which need to implemented by the
registered class to handle events.
➢ Different interfaces consists of different methods which are specified below.

Listener Interface Methods


ActionListener actionPerformed()
mousePressed() , mouseClicked(), mouseEntered(),
MouseListener and mouseExited(), mouseReleased()
MouseMotionListener
mouseMoved(), mouseDragged()
KeyListener keyTyped(), keyPressed(), keyReleased()
windowActivated(), windowDeactivated(), windowOpened(),
WindowListener windowClosed(), windowClosing(), windowIconified(),
windowDeiconified()

6
Flow of Event Handling

1. User Interaction with a component is required to generate an event.

2. The object of the respective event class is created automatically after

event generation, and it holds all information of the event source.

3. The newly created object is passed to the methods of the registered

listener.

4. The method executes and returns the result.

7
I. 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 (Ex.

Escape), and SHIFT_MASK.

➢ ActionEvent constructors:

ActionEvent(Object src, int type, String cmd, int modifiers)

➢ You can obtain the command name for the invoking ActionEvent object by using the

getActionCommand( ) method, shown here:

➢ String getActionCommand( ) -Returns the command string associated with this action
8
I. ActionListener Interface

➢ The Java ActionListener is notified whenever you click on the button or menu item.
➢ It is notified against ActionEvent.
➢ The ActionListener interface is found in java.awt.event package.
➢ It has only one method: actionPerformed().
➢ The actionPerformed() method is invoked automatically whenever you click on the registered
component.
How to write ActionListener :
1) Implement the ActionListener interface in the class:
public class ActionListenerExample Implements ActionListener
2) Register the component with the Listener:
component.addActionListener(instanceOfListenerclass);
3) Override the actionPerformed() method:
public void actionPerformed(ActionEvent e){
//Write the code here }
9
ActionListener Example
import java.awt.*;
//3rd step
import java.awt.event.*;
public void actionPerformed(ActionEvent e)
//1st step
{
public class ActionListenerExample
tf.setText("Welcome to LBRCE-CSE-A.");
implements ActionListener{
}
TextField tf;
public static void main(String[] args)
ActionListenerExample()
{
{
new ActionListenerExample();
Frame f=new Frame("ActionListener
}
Example");
}
tf=new TextField();
tf.setBounds(50,50, 200,30);
Button b=new Button("Click Here");
b.setBounds(50,100,60,40);
//2nd step
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setBackground(Color.MAGENTA);
}
10
ActionListener Example
f.add(b);f.add(tf);
f.setSize(400,400);
mport java.awt.*;
f.setLayout(null);
import java.awt.event.*;
f.setVisible(true);
public class ActionListenerExample
f.setBackground(Color.GRAY);
{
}
public static void main(String[] args)
}
{
Frame f=new Frame("ActionListener
Example");
final TextField tf=new TextField();
tf.setBounds(100,50, 200,20);
Button b=new Button("Click Here");
b.setBounds(100,100,60,30);
tf.setBackground(Color.green);

b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome to LBRCE-CSE-A");
}
});

11
II. MouseEvent Class

➢ There are eight types of mouse events.

➢ The MouseEvent class defines the following integer constants that can be used to

identify them:

➢ Two commonly used methods in this class are getX( ) and getY( ). These return the X

and Y coordinates of the mouse within the component when the event occurred. Their

forms are shown here: int getX( )


int getY( )
12
II. MouseListener Interface
➢ MouseListener and MouseMotionListener is an interface in java.awt.event package.
➢ Mouse events are of two types. MouseListener handles the events when the mouse is not in
motion. While MouseMotionListener handles the events when mouse is in motion.
▪ There are five types of events that MouseListener can generate.
▪ There are five abstract functions that represent these five events. They are
1. void mouseReleased(MouseEvent e) : Mouse key is released / pressed.
2. void mouseClicked(MouseEvent e) : Mouse key is pressed.
3. void mouseExited(MouseEvent e) : Mouse exited the component
4. void mouseEntered(MouseEvent e) : Mouse entered the component
5. void mousePressed(MouseEvent e) : Mouse key is pressed
▪ There are two types of events that MouseMotionListener can generate.
▪ There are two abstract functions that represent these five events. They are :
1. void mouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in the component and
dragged. Events are passed until the user releases the mouse button.
2. void mouseMoved(MouseEvent e) : Invoked when the mouse cursor is moved from one point to another
within the component, without pressing any mouse buttons.
13
MouseListener Example - 1
public void mouseEntered(MouseEvent e) {
import java.awt.*; l.setText("Mouse Entered");
import java.awt.event.*; l.setForeground(Color.gray);
public class MouseListenerExample extends }
Frame implements MouseListener public void mouseExited(MouseEvent e) {
{ l.setText("Mouse Exited");
Label l; l.setForeground(Color.red);
MouseListenerExample() }
{ public void mousePressed(MouseEvent e) {
addMouseListener(this); l.setText("Mouse Pressed");
l=new Label(); l.setForeground(Color.MAGENTA);
l.setBounds(50,50,150,50); }
add(l); public void mouseReleased(MouseEvent e) {
setSize(300,300); l.setText("Mouse Released");
setLayout(null); l.setForeground(Color.blue);
setVisible(true); }
}
public void mouseClicked(MouseEvent e) { public static void main(String[] args)
l.setText("Mouse Clicked"); {
l.setForeground(Color.PINK); new MouseListenerExample();
} }
}
14
MouseListener Example - 2
import java.awt.*; public void mouseEntered(MouseEvent e) {
import java.awt.event.*; l.setText("Mouse Entered");
public class MouseListenerExample2 extends l.setForeground(Color.gray);
Frame implements MouseListener }
{ public void mouseExited(MouseEvent e) {
Label l; l.setText("Mouse Exited");
MouseListenerExample2() l.setForeground(Color.red);
{ }
addMouseListener(this); public void mousePressed(MouseEvent e) {
setSize(300,300); l.setText("Mouse Pressed");
setLayout(null); l.setForeground(Color.MAGENTA);
setVisible(true); }
setResizable(true); public void mouseReleased(MouseEvent e) {
l=new Label(); l.setText("Mouse Released");
l.setBounds(100,20,100,50); l.setForeground(Color.blue);
add(l); }
}
public void mouseClicked(MouseEvent e) { public static void main(String[] args)
Graphics g=getGraphics(); {
g.setColor(Color.BLUE); new MouseListenerExample2();
g.fillOval(e.getX(),e.getY(),30,30); }
} }
15
III. KeyEvent Class

➢ A KeyEvent is generated when keyboard input occurs.

➢ There are three types of key events, which are identified by these integer constants:

KEY_PRESSED, KEY_RELEASED, and KEY_TYPED.

➢ The first two events are generated when any key is pressed or released.

➢ The last event occurs only when a character is generated. Remember, not all key presses

result in characters. For example, pressing shift does not generate a character.

➢ There are many other integer constants that are defined by KeyEvent.

➢ For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents

of the numbers and letters. getKeyCode() is used to get the ASCII code of letters.
16
III. KeyListener Interface

➢ The KeyEvent class should implement the KeyListener interface.

➢ The component object can be registered using the addKeyListener() method.

➢ The Java KeyListener is notified whenever you change the state of key.

➢ The KeyListener interface is found in java.awt.event package, and it has three methods.

Methods of KeyListener interface

1. public abstract void keyPressed (KeyEvent e); - It is invoked when a key has been pressed.

2. public abstract void keyReleased (KeyEvent e); - It is invoked when a key has been released.

3. public abstract void keyTyped (KeyEvent e); - It is invoked when a key has been typed.

17
KeyListener Example - 1
import java.awt.*;
import java.awt.event.*;
setSize (400, 400);
public class KeyListenerExample1 extends Frame
setLayout (null);
implements KeyListener{
setVisible (true);
}
Label l1,l2;
public void keyPressed(KeyEvent e) {}
TextArea area;
public void keyReleased (KeyEvent e)
KeyListenerExample1()
{
{
String text = area.getText();
l1=new Label("*Enter Some Text Below to Get
String words[] = text.split (" ");
Response*");
l2.setText ("Words: " + words.length + "
l1.setBounds(50,0,300,100);
Characters:" + text.length());
l2 = new Label();
}
l2.setBounds (20, 100, 200, 20);
public void keyTyped(KeyEvent e) {}
area = new TextArea();
area.setBounds (20, 120, 300, 300);
public static void main(String[] args)
{
area.addKeyListener(this);
new KeyListenerExample1();
add(l1);
}
add(l2);
}
add(area);
18
KeyListener Example - 2
Program to demonstrate the KeyListener with texts displaying on certain Key events along
with the key code.
public void keyPressed(KeyEvent ev)
import java.awt.*;
{
import java.awt.event.*;
s= "Event : Key " + ev.getKeyCode() + " is pressed ";
public class KeyListenerExample2 implements
lbl2.setText(s);
KeyListener
}
{
Label lb1, lbl2;
public void keyReleased(KeyEvent ev)
TextField tf1;
{
Frame fr;
s=s+" Event : Key Released ";
String s;
lbl2.setText(s);
KeyListenerExample2() {
fr.setVisible(true);
fr = new Frame("KeyEventListener Example");
}
lb1= new Label(" Key Events will be displayed based
on the actions", Label.CENTER);
public void keyTyped(KeyEvent ev)
lbl2= new Label();
{
tf1 = new TextField(20);
s=s+" Event : Key Typed ";
fr.setLayout(new FlowLayout());
lbl2.setText(s);
fr.add(lb1);
fr.setVisible(true);
fr.add(tf1);
}
fr.add(lbl2);
public static void main(String[] args) {
tf1.addKeyListener(this);
new KeyListenerExample2(); }
fr.setSize(460,250); fr.setVisible(true); }
}
19
IV. WindowEvent Class

➢ The WindowEvent class defines integer constants that can be used to identify different

types of events:

20
IV. WindowListener Interface

➢ Java WindowListener is notified whenever you change the state of window. It is notified against
WindowEvent.
➢ The WindowListener interface is found in java.awt.event package. It has seven methods.

Methods of WindowListener interface


1. public void windowActivated (WindowEvent e); - Called when the Window is set to be an active Window.
2. public void windowClosed (WindowEvent e); - Called when a window has been closed as the result of calling
dispose on the window.
3. public void windowClosing (WindowEvent e); - Called when the user attempts to close the window from the
system menu of the window.
4. public void windowDeactivated (WindowEvent e); - Called when a Window is not an active Window anymore.
5. public void windowDeiconified (WindowEvent e); - Called when a window is changed from a minimized to a
normal state.
6. public void windowIconified (WindowEvent e); - Called when a window is changed from a normal to a
minimized state.
7. public void windowOpened (WindowEvent e); - Called when window is made visible for the first time.
21
WindowListener Example
import java.awt.*;
import java.awt.event.*;
public void windowClosing (WindowEvent arg0) {
public class WindowExample1 extends Frame System.out.println("closing");
implements WindowListener dispose();
{ }
WindowExample1()
{ public void windowDeactivated (WindowEvent arg0) {
addWindowListener(this); System.out.println("deactivated");
setSize (400, 400); }
setLayout (null);
setVisible (true); public void windowDeiconified (WindowEvent arg0) {
} System.out.println("deiconified");
}
public static void main(String[] args) {
new WindowExample1(); public void windowIconified(WindowEvent arg0) {
} System.out.println("iconified");
}
public void windowActivated (WindowEvent arg0) {
System.out.println("activated"); public void windowOpened(WindowEvent arg0) {
} System.out.println("opened");
}
public void windowClosed (WindowEvent arg0) { }
System.out.println("closed");
} 22
Adapter Classes
➢ Adapter class provides the default implementation of all methods of a Listener interface.

➢ If user defined class inherits the adapter class, then the user defined class does not need to

modify (or overrides) all the methods of the interface, so it reduces code.

➢ As the WindowListener interface contains seven methods. Whenever we need to use this interface,

we must modify or implement all 7 methods. So, when we use the Adapter class (in other words

WindowAdapter) we don't need to modify all the methods, since all the methods are already

modified in it. We only need to implement those methods that are modified.

➢ The adapter classes are found in java.awt.event package.


Advantages of Adapter Class :
1. Assists unrelated classes to work together.
2. Provides a way to use classes in multiple ways, It makes a class highly reusable.
3. Provides a pluggable kit for developing applications.
24
Adapter Classes

Adapter classes with their corresponding listener interfaces are..

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

25
WindowAdapter Example - 1
import java.awt.*;
import java.awt.event.*;
public class WindowAdapterEx extends Frame
{
public WindowAdapterEx()
{
WindowAdapterClose clsme = new WindowAdapterClose();
addWindowListener(clsme);
Label l = new Label("*Sample Window for Demonstrate
WindowAdapter - Window Closing*");
add(l);
setTitle("WindowAdapter frame closing");
setSize(400, 400);
setVisible(true);
}
public static void main(String args[])
{
new WindowAdapterEx();
}
}
class WindowAdapterClose extends WindowAdapter {
public void windowClosing(WindowEvent e)
{
System.exit(0);
} } 26
WindowAdapter Example - 2
import java.awt.*;
import java.awt.event.*;
public class AwtAdapterDemo
{
// Components - Properties
Frame mainFrame;
headerLabel = new Label("Listener in action:
Label headerLabel;
KeyAdapter");
Label statusLabel;
headerLabel.setAlignment(Label.CENTER);
Panel controlPanel;
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
AwtAdapterDemo()
statusLabel.setSize(350,100);
{
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
// Container - Frame Properties
mainFrame = new Frame("Java AWT Examples");
// Adding of Components to Frame
mainFrame.setSize(400,400);
mainFrame.add(headerLabel);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
//WindowAdapter
mainFrame.addWindowListener(new
// Visiblity of frame
WindowAdapter() {
mainFrame.setVisible(true);
public void windowClosing(WindowEvent
}
windowEvent)
{
System.exit(0);
} }); 27
WindowAdapter Example – 2 (cont..)

private void KeyAdapterDemo()


{
TextField textField = new TextField(10);

// KeyAdapter // Adding of Components to Panel


textField.addKeyListener(new KeyAdapter() { controlPanel.add(textField);
public void keyPressed(KeyEvent e) controlPanel.add(okButton);
{ }
if(e.getKeyCode() == KeyEvent.VK_ENTER)
statusLabel.setText("Entered text: " + // Main Method
textField.getText()); public static void main(String[] args)
} }); {
AwtAdapterDemo awtobj1 = new
// ActionListener AwtAdapterDemo();
Button okButton = new Button("OK"); awtobj1.KeyAdapterDemo();
okButton.addActionListener(new ActionListener() { }
public void actionPerformed(ActionEvent e)
{ }
statusLabel.setText("Entered text: " +
textField.getText());
} });

28
WindowAdapter Example – 2 (cont..)

29
Module 7a Example

Develop a java program that creates a user interface to


perform integer divisions with possible validations (Divide
by Zero, NumberFormatException).

30
Module 7a Solution
import java.awt.*; f_window.add(p_container);
import java.awt.event.*; f_window.setSize(300, 300);
f_window.setVisible(true);
class GUI7a extends Frame implements ActionListener }
{
Frame f_window; public void actionPerformed(ActionEvent e)
Panel p_container; {
TextField txt1, txt2, txt_res; int num1, num2;
Button btn; try {
num1 = Integer.parseInt(txt1.getText());
GUI7a() { num2 = Integer.parseInt(txt2.getText());
f_window = new Frame("Experiment 7a"); txt_res.setText(num1/num2 + "");
p_container = new Panel(); }
p_container.setLayout(new FlowLayout()); catch(NumberFormatException nfe) {
txt_res.setText("Please do enter only
txt1 = new TextField(20); integers");
txt2 = new TextField(20); }
txt_res = new TextField(20); catch(ArithmeticException ae) {
btn = new Button("Divide"); txt_res.setText("Divisor can not be ZERO");
btn.addActionListener(this); }
p_container.add(txt1); }
p_container.add(txt2); public static void main(String[] args) {
p_container.add(btn); new GUI7a(); }
p_container.add(txt_res); }
31
Module 7a Output

32
Module 8b Example

Develop a java program to simulate a traffic light, user


can select any one of the three buttons with: red, yellow,
and green color. On selecting a button, an appropriate
message with “Stop” or “Ready” or “Go” should appear
with the selected button color.

33
Module 8b Solution
import java.awt.*;
addWindowListener(new WindowAdapter() {
import java.awt.event.*;
public void windowClosing(WindowEvent
public class TrafficLightDemo extends Frame
we)
implements ActionListener
{
{
System.exit(0);
Button redbt,greenbt,yellowbt;
} });
String msg="";
}
TrafficLightDemo()
{
public void actionPerformed(ActionEvent ae)
setLayout(new FlowLayout());
{
redbt=new Button("RED");
msg=ae.getActionCommand();
greenbt=new Button("GREEN");
repaint();
yellowbt=new Button("YELLOW");
}
add(redbt);
public static void main(String args[])
add(greenbt);
{
add(yellowbt);
TrafficLightDemo tf=new TrafficLightDemo();
tf.setTitle("Traffic Light Demo");
redbt.addActionListener(this);
tf.setSize(320,350);
greenbt.addActionListener(this);
tf.setVisible(true);
yellowbt.addActionListener(this);
}
34
Module 8b Solution (Cont..)
public void paint(Graphics g)
{
setBackground(Color.gray);
setForeground(Color.white);

g.setFont(new Font("Arial",Font.BOLD,25));
g.drawOval(110,80,50,50);
g.drawOval(110,180,50,50);
g.drawOval(110,280,50,50);
if(msg.equals("RED")) {
g.setColor(Color.red);
g.fillOval(110,80,50,50);
g.drawString("---->STOP",160,110);
}
else if(msg.equals("GREEN")) {
g.setColor(Color.green);
g.fillOval(110,180,50,50);
g.drawString("---->GO",160,210);
}
else if(msg.equals("YELLOW")) {
g.setColor(Color.yellow);
g.fillOval(110,280,50,50);
g.drawString("---->READY",160,310);
}
} 35
Module 8b Solution (Cont..)

36
THANK YOU

37

You might also like