Unit Iv
Unit Iv
Event Handling: Events, Event sources, Event classes, Event Listeners, Event Delegation model,
handling mouse and key board events, Adapter classes, inner classes.
AWT: Class hierarchy, user- interface components- labels, button, canvas, scrollbars, text
components, checkbox, checkbox groups, choices, list panes-scroll pane, dialogs, menu bar,
graphics, layout manager- layout manager types- boarder, grid, flow, card and grid bag.
EventSource Description
java.awt.event package:
the java.awt.event package provide interfaces and classes for dealing
with different types of events fired by AWT components. This package
includes the definition of events classes, listeners interface and adapters
classes, which form the basics of event handling.
Event classes:
The package java.awt.event defines several types of events that are
generated by various user interface elements.
Event class Description
ActionEvent Generated when a button is pressed, a list item is
double-clicked, or a menu item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved,
resized, or becomes visible.
ContainerEvent Generated when a component is added or removed
from a container
FocusEvent Generated when a component gains or loses
keyboard focus
InputEvent Abstract superclass for all component input event
classes
ItemEvent Generated when a check box or list item is clicked;
also occurs when a choice selection is made or a
checkable menu item is selected or deselected.
KeyEvent Generated when input is received from the
keyboard.
MouseEvent Generated when the mouse is dragged or moved,
clicked, pressed, or released ; also generated when
the mouse enter or exits a component
TextEvent Generated when the value of a text area or text
field is changed.
WindowEvent Generated when a window is activated, closed,
deactivated, deiconified, iconified,opened or quit.
Event listeners :
Event listeners are created by implementing one or more interfaces
defined by the java.awt.event package. whenever a source generates an
event, it basically invokes the appropriate method defined in the listener
interface. The method has an event object passed as an argument to it.
Some of the frequently used listeners are :
Interface Description
ActionListener This interface has only one method having this
signature
void keyPressed(KeyEvent e)
void keyReleased(KeyEvent e)
void keyTyped(KeyEvent e)
Void itemStateChanged(ItemEvent e)
TextListener Defines one method to recognize change in text or text
area
Void textChanged(TextEvent e)
MouseListener Defines 5 methods to recognize when the mouse is
clicked, enters a component, exits a component, is
pressed or is released.
void mouseClicked(MouseEvent e)
void mouseEntered(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)
void mouseExited(MouseEvent e)
MouseMotionListener Defines two methods to recognize when the mouse is
dragged or moved.
void mouseMoved(MouseEvent e)
void mouseDragged(MouseEvent e)
WindowListener Defines seven methodsto recognize when a window is
activated, closed, deactivated, iconified, deiconified,
opened or quit.
void windowOpened(WindowEvent e)
void windowActivated(WindowEvent e)
void windowClosed(WindowEvent e)
void windowClosing(WindowEvent e)
void windowDeactivated(WindowEvent e)
void windowIconified(WindowEvent e)
void windowDeiconified(WindowEvent e)
AdjustmentListener Defines one method to recognize adjustment event
void adjustmentValueChanged(AdjustmentEvent e)
}
save : MouseApplet.java
compile : javac MouseApplet.java
run : appletviewer MouseApplet.java
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages. The
Adapter classes with their corresponding listener interfaces are given below.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
Additionally, it can access all the members of the outer class, including private data
members and methods.
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
AWT:
Java AWT (Abstract Window Toolkit) is an API( Application Program
Interface) to develop GUI or window-based applications in java.
why AWT?
Each application developed in a programming languages must have a user
interface, which is actually that part of the application that is responsible for
directly interacting with the user.
These user interfaces can either be
1. command line interface
2. graphical user interface
The awt is a well – designed object-oriented interface between the application
and the low level resources. So that programmers need not worry about tracking
the mouse movements or reading the keyboard characters or writing to the
screen.
The hierarchy of Java AWT classes are given below.
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.
Window
The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have
other components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can
have other components like button, textfield etc.
Useful Methods of Component class
Method Description
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default false.
Component class :
component class is sub class of object class and super class of various
classes such as Button, Label , CheckBox etc.
Ex :
add(l);
Button:
The button class is used to create a labeled button that has platform
independent implementation. The application result in some action when
the button is pushed.
constructors for creating a Button:
add(buttonname);
add(b);
implements ActionListener
{
String s="";
public void init()
{
Button b1 =new Button("red");
Button b2 =new Button("Green");
Button b3 =new Button("Yellow");
add(b1);
add(b2);
add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
s=a.getActionCommand();
repaint();
}
public void paint(Graphics g)
{
if(s.equals("red"))
setBackground(Color.red);
if(s.equals("Green"))
setBackground(Color.green);
if(s.equals("Yellow"))
setBackground(Color.yellow);
}
}
Label :
Labels consist of a text String for display only and they never call an action
method.
The Constructors responsible for creating labels are:
Label() : creates an empty label
Label(String label):creates a new label with the specified string of text, left
justified
Label(String label,int alignment) : constructs a new label that presents the
specified string of text with the specified alignment.
syntax :
Label labelname = new Label(str);
Ex :
Label l = new Label(“Rollno”);
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <Applet code=MyLabel.class height=600
width=600>
</Applet>
*/
public class MyLabel extends Applet
{
public void init()
{
Label l1=new Label("RollNo");
Label l2=new Label("Name");
Label l3=new Label("Marks");
add(l1);
add(l2);
add(l3);
}
}
Checkbox():
checkboxes are used as on-off (or) yes –no switches since every time you
click on one, you toggle to the opposite selection, i.e, if you click on an unchecked
checkbox, it will get checked and if you click on the checked box, it will get
unchecked.
The checkboxes are the objects of Checkbox class, which support the
following constructors.
Checkbox()
Checkbox(String s)
Checkbox(String s, boolean b)
Checkbox(String s,CheckBoxGroup cbg, Boolean b)
Ex :
Checkbox c= new Checkbox(“Names”, null,false)
false indicates it is unchecked. once after creating the checkbox, add it to
the applet as
add(c);
Ex:write java program to create check boxes
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code="MyCheckbox" height=600 width=600>
</Applet>
*/
public class MyCheckbox extends Applet implements ActionListener
{
Button b;
Checkbox c1;
Checkbox c2;
Checkbox c3;
Font f;
public void init()
{
c1=new Checkbox("rama");
c2=new Checkbox("sita");
c3=new Checkbox("laxman");
Button b = new Button("SUBMIT");
f=new Font("Arial" , Font.ITALIC,20);
add(c1);
add(c2);
add(c3);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
String s= a.getActionCommand();
if(s.equals("SUBMIT"))
repaint();
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.setFont(f);
if(c1.getState())
g.drawString("Rama",50,50);
if(c2.getState())
g.drawString("Sita",50,90);
if(c3.getState())
g.drawString("Laxman",50,120);
}}
Radio Butons :
Radio buttons, which are also called checkboxgroups, are a special
kind ofcheckboxes, where within a particular group, only one box can be selected
at a time.
CheckboxGroup class is used to group together a set of checkboxes and
there after only a single selection is allowed among them i.e, they behave as radio
buttons. There is only one constructor which creates an empty group. The
following line will create a checkbox group named fruits.
CheckboxGroup fruits=new CheckboxGroup();
once you create the checkbox group, add the individual checkboxes to that
group as
add(new Checkbox(“mango”,fruits,false));
add(new Checkbox(“papaya”,fruits,false));
add(new Checkbox(“apple”,fruits,false));etc
Ex : write java program to create radio buttons
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<Applet code=MyRadio.class height=800 width=800>
</Applet>
*/
public class MyRadio extends Applet implements ItemListener
{
Checkbox c1;
Checkbox c2;
CheckboxGroup cbg;
String s="";
List boxes:
list class provides a compact, multiple choice scrolling selection list. List object can
be constructed to show any no of choices in the visible window.
constructors used for creating list are
List()
List(int norows)
List(int norows,boolean multiselection);
to add a selection to the list call add
void add(String name);
void add(String, int index);
for lists that allow only single selection we use
String getSelectionItem()
int getSelectedIndex()
for lists that allow multiple selection we use
String[] getSelectedItem();
int[] getSelectedIndexes();
choice boxes :
The choice class is lot like a list, but it allows you to conserve space , since
it provides a pop up menu of text string choices. The current choice is displayed on
top.Inorder to work with a choice box, an instance of choice class must be created
as
c.add(“India”);
c.add(“America”) etc.
Container class :
containers allow us to organize components into manageable
groups which are extremely important in order to create a good user
interface. The AWT provides 4 container classes.
1.Panels
2.Window
3.Dialog
4.Frame
1.Panel :
It is a generic container for holding components. An instance of the
panel class provides a container to which components can be added.
The definition of Panel class is
public class Panel extends Container implements Accessible
constructors of Panel class:
Panel() -> creates a new panel using the default layout manager.
Panel(LayoutManager layout)-> creates a new panel with specified
layout.
How to use Panels:
Steps to follow while creating a panel are:
1. Create the panel by writing the following piece of code.
Panel panel = new Panel();
2. Add components to Panel by using add() method.
Panel.add(componenet) ;etc
2.Window:
This class creates a top-level window. Top-level window means
that it is not contained within any other object. It has the following
signature.
public class Window extends Container implements Accessible
3.Frame:
If you are not creating an applet, then you will be most likely
creating a Frame window.
The constructors responsible for creating a Frame are
1. Frame() -> creates a frame without title.
2. Frame(String title) -> creates a frame with title.
steps to create a Frame are
1. create an instance of the main frame
2. set the frame width and height
3. display the frame
Example of flowlayout
2.BorderLayout:
Here the components can be arranged and resized to fit in five
different regions : north, east, south, west and center. There can be only
one component in each region and the regions are identified as constants
NORTH, SOUTH,EAST,WEST and CENTER.
Any of these five constant names can be used while adding a component
to a container.
constructors :
BorderLayout()
BorderLayout(int horz, int ver)
3. GridLayout():
The GridLayout class is a layout manager which can be used to
arrange controls in a container component in a rectangular grid. It has
specified number of rows and columns , where the container is divided
into equal sized rectangles and one component is placed in each
rectangle.
constructors:
1.GridLayout()->creates single column layout
2. GridLayout(int rows, int cols) ->creates a layout with no of rows
and columns.
Example of gridlayout:
4.CardLayout:
It stores several different layouts. Each layout can be thought of as
being on a separate index card in a deck that can be shuffled so that any
card is on top at a given time.
constructors
CardLayout()
CardLayout(int horz,int ver)
5.GridBagLayout:
using GridBagLayout class, we can arrange components in a
more controlled way on horizontal as well in vertical direction.
Ex:java program to illustrate FlowLayout.
import java.awt.*;
public class MyFlow extends Frame
{
MyFlow()
{
Button b1=new Button("NORTH");
Button b2=new Button("SOUTH");
Button b3=new Button("EAST");
Button b4=new Button("WEST");
Button b5=new Button("CENTER");
setLayout(new FlowLayout());
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
setSize(500,500);
setVisible(true);
}
public static void main(String args[])
{
new MyFlow();
}}
Ex: java program to illustrate Borderlayout
import java.awt.*;
public class MyBorder extends Frame
{
MyBorder()
{
Button b1=new Button("NORTH");
Button b2=new Button("SOUTH");
Button b3=new Button("EAST");
Button b4=new Button("WEST");
Button b5=new Button("CENTER");
//setLayout(new FlowLayout());
setLayout(new BorderLayout());
add(b1,BorderLayout.NORTH);
add(b2,BorderLayout.SOUTH);
add(b3,BorderLayout.EAST);
add(b4,BorderLayout.WEST);
add(b5,BorderLayout.CENTER);
setSize(500,500);
setVisible(true);
}
public static void main(String args[])
{
new MyBorder();
}
}
Ex: java program to illustrat Grid Layout
import java.awt.*;
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.setLayout(new GridLayout(2,3));
//setting grid layout of 2 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyGridLayout();
}
}
Menubar:
Java AWT 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 or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on
the menu bar. It inherits the MenuItem class.
Example
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MyMenu
{
Frame f;
MyMenu()
{
f=new Frame("Testing Menus");
}
public void createmenu()
{
MenuBar mb=new MenuBar();
f.setMenuBar(mb);
Menu m1=new Menu("File");
Menu m2=new Menu("Edit");
MenuItem mt1=new MenuItem("New");
MenuItem mt2=new MenuItem("Open");
MenuItem mt3=new MenuItem("cut");
MenuItem mt4=new MenuItem("copy");
m1.add(mt1);
m1.add(mt2);
m2.add(mt3);
m2.add(mt4);
mb.add(m1);
mb.add(m2);
f.setVisible(true);
f.setSize(500,500);
}
public static void main(String a[])
{
MyMenu m = new MyMenu();
m.createmenu();
}
}
output:
Scrollbar:
The object of Scrollbar class is used to add horizontal and vertical
scrollbar.Scrollbar is a GUI component allows us to see invisible
number of rows and columns.
AWT Scrollbar class declaration:
public class Scrollbar extends Component implements djustable,Accessible
Example:
import java.awt.*;
class ScrollbarExample
{
ScrollbarExample()
{
Frame f=new Frame(“Scrollbar Example”);
Scrollbar s = new Scrollbar();
s.setBounds(100,100,50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ScrollbarExample();
}
}
output: