Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

OOP Through Java Unit-5

java

Uploaded by

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

OOP Through Java Unit-5

java

Uploaded by

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

UNIT V

Event handling: event delegation model, sources of event, Event Listeners, adapter
classes, inner classes. AWT: introduction, components and containers, Button, Label, Checkbox,
Radio Buttons, List Boxes, Choice Boxes, Container class, Layouts, Menu and Scrollbar.
Event Delegation Model
Q.Explain about Event Delegation Model.
Event handling:
The Change in state of an object is called as an event i.e., the event describes a particular change in the
state of a source. The Events are generated as a result of the user interactionwith Graphical User
Interface (GUI) components.

For example- Clicking on a button, movement of the mouse, inserting a character throughthe keyboard,
selection of an item from the given list, scrolling of the page are all of the activities which causes an
event to be happen.

Types of Event:
The events can be generally classified into following two categories:

1) The Foreground Events:-


 The event which requires the direct interaction of the user are called as the Foreground events.
They are generated as a consequence of a user interacting with the graphical components in GUI. For
example- Clicking on a button, movement of the mouse, inserting a character through the keyboard,
selection of an item from the given list, scrolling of the page.
2) The Background Events :-
 The event that requires the interaction of an end user is called as the Background events. For
Example:- an Operating system interrupts, failure of hardware or software, a timer expires, an
operation completion etc. are the examples of Background events.

The Java uses a Delegation Event Model to handle all the events which defines the standard mechanism
to generate & handle the events.

The Delegation Event Model has following key participants as:


Source – The source is an object on which an event occurs and the Source is responsible for providing
information of the event which has occurred to its handler.
Listener – It is also called as event handler. The Listener is responsible for generating a response to an
event.

1
Event Listeners
Q. Explain about the various Event Listeners in Java with an example.
Event Listeners: A listener is an object that is notified when an event occurs. It has two major
requirements.
1. It must have been registered with one or more sources to receive
notifications about specific types of events.
2. It must implement methods to receive and process these notifications.

The methods that receive and process events are defined in a set of interfaces found in
java.awt.event package.
Sources of Events:
Event Source Description
Button Generates action events when the button is pressed.
Check box Generates item events when the check box is selected or deselected.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked;
Generates action events when a menu item is selected; generates item
Menu item
events when a checkable menu item is selected or deselected.
Scroll bar Generates adjustment events when the scroll bar is manipulated.
Text components Generates text events when the user enters a character.
Generates window events when a window is activated, closed,
Window
deactivated, deiconified, iconified, opened, or quit.

Event Classes and Listener Interfaces:


The package java.awt.event defines many types of events that are generated by various user interface elements
Event Class Description Listener Interface
Generated when a button is pressed, a
ActionEvent list item is double-clicked, or a menu ActionListener
item is
selected.
AdjustmentEvent Generated when a scroll bar is manipulated. AdjustmentListener
Generated when a component is hidden,
ComponentEvent ComponentListener
moved, resized, or becomes visible.
Generated when a component is added to or
ContainerEvent ContainerListener
removed from a container.
Generated when a component gains or
FocusEvent FocusListener
losses keyboard focus.
Abstract super class for all component input
InputEvent
event classes.
Generated when a check box or list item is
ItemEvent ItemListener
Clicked

Generated when input is received from the


KeyEvent KeyListener
keyboard.
Generated when the mouse is dragged,
moved, clicked, pressed, or released; MouseListener and
2
MouseEvent also generated when the mouse enters MouseMotionListener
or
exits a component.
Generated when the value of a text area or
TextEvent TextListener
text field is changed.
Generated when a window is activated,
WindowEvent closed, deactivated, deiconified, iconified, WindowListener
opened, or quit.

Useful Methods of Component class:

Method Description
add(Component) Inserts a component.
sets the size (width and height) of the
setSize(width,height)
component.
setLayout(layoutmanager) Defines the layout manager for the component.
changes the visibility of the component, by
setVisible(status)
default false.

3
Adapter Classes
Q. Explain about the Adapter classes available in JAVA.
Adapter Class:
 Java provides a special feature, called an adapter class, that can simplify the creation of event handlers
in certain situations.
 An adapter class provides an empty implementation of all methods in an event listener interface.
 Adapter classes are useful when you want to receive and process only some of the events that are
handled by a particular event listener interface.

 For example,
MouseListener MouseAdapter
void mouseClicked(MouseEvent me) void mouseClicked(MouseEvent me){ }
void mouseEntered(MouseEvent me) void mouseEntered(MouseEvent me) { }
void mouseExited(MouseEvent me) void void mouseExited(MouseEvent me) { } void
mousePressed(MouseEvent me) mousePressed(MouseEvent me) { }
void mouseReleased(MouseEvent me) void mouseReleased(MouseEvent me) { }

Table: Commonly used Listener Interfaces implemented by Adapter Classes


Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener

Example Program

import java.awt.*;
import java.awt.event.*;
class WindowEx1 extends Frame
{
String msg;
WindowEx1(){
addWindowListener(new WA());
}
}
class WA extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);

}
}
4
class WindowAdapterEx
{
public static void main(String[] args)
{
WindowEx1 w=new WindowEx1();
w.setSize(400,400);
w.setLayout(null);
w.setVisible(true);
}
}

Inner Classes
Q. Explain about inner classes available in JAVA.
Inner class is a class defined within another class, or even within an expression.

Example:
import java.awt.*;
import java.awt.event.*;
class WindowEx1 extends Frame
{
String msg; WindowEx1(){
addWindowListener(new WA());
}
class WA extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
}
class WindowAdapterInner
{
public static void main(String[] args) { WindowEx1 w=new
WindowEx1(); w.setSize(400,400);
w.setLayout(null);
w.setVisible(true);}
}

Mouse Handling Events


Q. Explain various Mouse handling events in JAVA.
Handling Mouse Events
 To handle mouse events, you must implement the MouseListener and the
MouseMotionListener interfaces.

 The MouseListener interface defines five methods.

 If a mouse button is clicked,mouseClicked( ) is invoked. When the mouse enters a


component, the mouseEntered( ) method is called.
5
 When it leaves, mouseExited( ) is called.

 The mousePressed( ) and mouseReleased( ) methods are invoked when a mouse button is
pressed and released, respectively.

The general forms of these methods are shown here:


1. void mouseClicked(MouseEvent e)
2. void mouseEntered(MouseEvent e)
3. void mouseExited(MouseEvent e)
4. void mousePressed(MouseEvent e)
5. void mouseReleased(MouseEvent me)

Example: Refer Mouse handling events program (Record program)

6
AWT
Q. Explain the hierarchy of AWT with a neat diagram with examples?
AWT:

 The Abstract Window Toolkit (AWT) is class library provides a user interface toolkit called the
Abstract Windowing Toolkit, or the AWT.
 The AWT is both powerful and flexible.
 The AWT was designed to provide a common set of tools for graphical user interface design
that work on a variety of platforms.
 The AWT classes are contained in the java.awt package. It is one of Java’s largest packages.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below

We will list some of the AWT classes:


Component: AWT provides various components such as buttons, labels, text fields, checkboxes, etc
used for creating GUI elements for Java Applications.

Container: AWT provides containers like panels, frames, and dialogues to organize and group
components in the Application.

Panel: Panel class is a subclass of Container and is a super class of Applet.

Frame: The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc

7
Useful Methods of Component class
Method Description
add(Component) inserts a component on this component.
setSize(width,height) sets the size (width and height) of the
component.
setLayout(LayoutManager) defines the layout manager
for the component.
setVisible(status) changes the visibility of the component, by
default false.
Java AWT Example
To create simple AWT example, we need a frame. There are two ways to create a frame in AWT.
Type 1: By extending Frame class (inheritance)
Type 2: By creating the object of Frame class (association)

ESimple example of AWT by inheritance-Example:1

import java.awt.*;
class First extends Frame{
public static void main(String[]args)
{
Button b=new Button("click me");
b.setBounds(30,100,80,30); // setting button position add(b);
//adding button into frame setSize(300,300); //300
width and 300 height setLayout(null); //no layout
manager setVisible(true); //now frame will be
visible
}}

OUTPUT:

8
Simple example of AWT by association-Example:2
import java.awt.*;
class First2{
public static void main()
{
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30); f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}}

Output:

9
BUTTONS
Q. Explain how to implement buttons in AWT?
Buttons:
 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 class.
 To perform an action on a button being pressed and released,
the ActionListener interface needs to be implemented.
Java AWT Button Example
ButtonExample.java
import java.awt.*;
class ButtonExample {
public static void main (String[] args) {
Frame f = new Frame("Button Example");
Button b = new Button("Click Here");
// set the position for the button in frame
b.setBounds(50,100,80,30);
// add button to the frame
f.add(b);
// set size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}}
OutPut:

10
LABELS
Q. Explain how to implement Labels in AWT?
Label:
 The object of the Label class is a component for placing text in a container.
 It is used to display a single line of read only text.
 The text can be changed by a programmer but a user cannot edit it directly.
Syntax: Label obj=new Label( );
Ex: Label l=new Label( );

Java AWT Label Example


In the following example, we are creating two labels l1 and l2 using the Label(String text) constructor
and adding them into the frame.
LabelExample.java
import java.awt.*;
public class LabelExample {
public static void main(String args[]){
Frame f = new Frame ("Label example");
Label l1 =new label(“First Label.”);
Label l2 = new Label ("Second Label.");
l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);

f.add(l1);
f.add(l2);

f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

11
Choice Boxes
Q. Explain how to implement Choice boxes in Java.
Choice Box:
 Choice class is part of Java Abstract Window Toolkit(AWT).
 The Choice class presents a pop- up menu for the user, the user may select an item from the popup menu.
 The selected item appears on the top.
 The Choice class inherits the Component.
Syntax: Choice obj=new Choice( );
Ex: Choice c=new Choice( );
Example:
import java.awt.*;
class ChoiceExample {
public static void main(String[]ar){
// creating a frame
Frame f = new Frame();
// creating a choice component
Choice c = new Choice();
// setting the bounds of choice menu
c.setBounds(100, 100, 75, 75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true); }}

Output:

List Boxes
Q. Explain how to implement List boxes in Java.
List Box:
 The List class provides a compact, multiple-choice, scrolling selection list.
12
 List object can be constructed to show any number of choices in the visible window.
 It can also be created to allow multiple selections.
Syntax: List obj=new List( ); (or) List obj=new List(rows);
Ex: List l=new List( ); (or) List l=new List(3);
Example:
import java.awt.*;
class ListExample {
public static void main(String[]ar){
// creating a frame
Frame f = new Frame();
// creating a List component
List l = new List();
// setting the bounds of List menu
l.setBounds(100, 100, 75, 75);
l.add("Item 1");
l.add("Item 2");
l.add("Item 3");
l.add("Item 4");
l.add("Item 5");
f.add(l);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true); }}
Output:

Checkboxes and Radiobuttons in JFrame(program)


Q.Develop a JAVA program to implement checkboxes and Radiobuttons.
import java.awt.*;
import javax.swing.*; //for importing JFrame class
class CheckRadio {
public static void main(String[]ar){
// creating a Jframe
JFrame f = new JFrame();
13
// creating a checkbox & Radiobutton
JCheckBox c=new JCheckBox("Male");
JRadioButton r=new JRadioButton("Female");
// setting the bounds of radio button and checkbox
c.setBounds(100, 100, 75, 75);
r.setBounds(100,150,75,75);

f.add(c);
f.add(r);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
} }
OutPut:

Checkboxes and Radiobuttons(Theory)


Checkbox:
 The Checkbox class is used to create a checkbox.
 It is used to turn an option on (true) or off (false).
 Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
Syntax:
Checkbox obj=new Checkbox(string);
Ex: Checkbox c=new Checkbox(“ECE”);

CheckboxGroup:

 The object of CheckboxGroup class is used to group together a set of Checkbox.

14
 At a time only one check box button is allowed to be in "on" state and remaining check box
button in "off" state.

 CheckboxGroup enables you to create radio buttons in AWT. There is no special control for
creating radio buttons in AWT.

 So we use JRadioButton class to create radiobutton using JFrame.

 JRadioButton is available in javax.swing.*.

Syntax:
CheckboxGroup obj = new CheckboxGroup();
Checkbox obj = new Checkbox(string);

Ex: CheckboxGroup c=new CheckboxGroup( );

Checkbox c1=new Checkbox(“JAVA”);

Checkbox c2=new Checkbox(“C++”);

(or)
JRadioButton r=new JRadioButton(“C”);

Layout Managers
Q. Discuss about different layout managers with neat diagrams.
Layout Managers:
 The Layout Managers are used to arrange components in a particular manner.
 The Java Layout Managers facilitates us to control the positioning and size of the
components in GUI forms.
 Layout Manager is an interface that is implemented by all the classes of layout managers

Types of LayoutManager

There are 6 layout managers in Java


1. FlowLayout
2. BorderLayout
3. GridLayout
4. GridBagLayout

15
5. BoxLayout
6. CardLayout

1. FlowLayout:
 It arranges the components in a container like the words on a page.
 It fills the top line from left to right and top to bottom.
 The components are arranged in the order as they are added i.e. first components
appears at top left.
 The components can be left, center or right aligned.

Syntax:
setLayout(new FlowLayout());

16
2. BorderLayout:
 It arranges all the components along the edges or the middle of the container i.e. top,
bottom, right and left edges of the area.
 BorderLayout arranges the components in the five regions.
 Each region can contain only one component and is identified by a corresponding
constant as NORTH, SOUTH, EAST, WEST, and CENTER.

Ex: Frame f=new Frame();


Button b=new Button(“North”);
f.add(b, BorderLayout.NORTH);

3. GridLayout:
 It arranges all the components in a grid of equally sized cells, adding them from the left to right and top
to bottom.
 Only one component can be placed in a cell and each region of the grid will have the same size.
 When the container is resized, all cells are automatically resized.

Syntax: setLayout(new GridLayout());

4. GridBagLayout:
 It is a powerful layout which arranges all the components in a grid of cells and
maintains the aspect ratio of the object whenever the container is resized.
 In this layout, cells may be different in size.

17
 It assigns a consistent horizontal and vertical gap among components.

Syntax: setLayout(new GridBagLayout());

5. BoxLayout:
 It arranges multiple components in either vertically or horizontally, but not both.
 The components are arranged from left to right or top to bottom.

Syntax: setLayout(new BoxLayout());

6. CardLayout:
 It arranges two or more components having the same size.
 The components are arranged in a deck, where all the cards of the same size and the
only top card are visible at any time.

Syntax: setLayout(new CardLayout());

18
MenuBar
Q. Explain how to implement Menubar in AWT?
Menubar:

 The MenuBar class is used to display menubar on the window or frame. It may have several
menus.

 The object of Menu class is a pull down menu component which is displayed from the menu
bar.

 The object of MenuItem class adds a simple labeled menu item. The items used in a menu
must belong to the MenuItem or any of its subclass.

Example:
import java.awt.*;
class Menubar
{
public static void main(String[]args)
{
Frame f=new Frame("Menu Example");
MenuBar mb=new MenuBar();
Menu m=new Menu("File");
MenuItem m1=new MenuItem("Open");
MenuItem m2=new MenuItem("Save");
MenuItem m3=new MenuItem("Exit");
m.add(m1);
m.add(m2);
m.add(m3);
mb.add(m);
f.setMenuBar(mb);
f.setLayout(null);
f.setVisible(true);
f.setSize(400,400);
}}
OutPut:

19
20
ScrollBar
Q. Explain how to implement Scrollbar in AWT?
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.

 It can be added to top-level container like Frame or a component like Panel.

ScrollbarExample.java

import java.awt.*;
class ScrollbarExample1 {
public static void main(String[]ar){
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);
} }

Output:

21
Container Class
Q.What are the types of containers in AWT?
A container is a component that can contain other components. There are four types of containers in AWT:
 Window: a container that has no borders and menu bars. It requires a frame, dialog, or another window to create
it.
 Panel: a container that has no title bar, border, or menu bar. It is a generic container for holding components.
 Frame: a container that has a title bar, and border, and can have menu bars. It is the most widely used container
for developing AWT applications.
 Dialog: a container that has a title bar, and border, and can have buttons. It is used to display messages or get user
input.

TextField

 The object of a TextField class is a text component that allows a user to enter a single line
text and edit it.

 When we enter a key in the text field (like key pressed, key released or key typed), the event is
sent to TextField.

Syntax: TextField t=new TextField();


Ex:
class textfield{
public static void main(String[]ar)
{
Frame f=new Frame(“textbox example”);
TextField t=new TextField();
t.setBounds(100,100,70,70);
f.add(t);
f.setLayout(null);
f.setVisible(true);
f.setSize(400,400);
}}

22

You might also like