0% found this document useful (0 votes)
1 views61 pages

UNIT 4_Java Programming

This document provides an overview of Java programming concepts related to event handling, AWT (Abstract Window Toolkit), and layout management. It covers various types of events, event sources, listeners, and classes, as well as practical examples of handling mouse and keyboard events. Additionally, it discusses the structure and components of AWT, including containers, user interface components, and their constructors and methods.

Uploaded by

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

UNIT 4_Java Programming

This document provides an overview of Java programming concepts related to event handling, AWT (Abstract Window Toolkit), and layout management. It covers various types of events, event sources, listeners, and classes, as well as practical examples of handling mouse and keyboard events. Additionally, it discusses the structure and components of AWT, including containers, user interface components, and their constructors and methods.

Uploaded by

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

Java Programming

UNIT – IV
Event Handling, AWT &Layout
manager
Event Handling
• Events
• Event sources
• Event listners
• Event classes
• Delegation of Event model
• Handling mouse and keyboard events
• Adapter classes
Events
Events in Java represent the change in the state of any object.
Events occur when the user interacts with the interface.
• Clicking a button,
• moving the mouse,
• typing a character,
• selecting an item from a list,
• scrolling the page
Events may also occur that are not directly caused by interactions
with user interface
• when a timer expires
• a couter exceeds a value
• a software or hardware failure occures
• an operation completed
Types of Events in Java
• Foreground Events: These events necessitate the
user's direct participation. They are produced as
a result of a user interacting with graphical
components in a Graphical User Interface.
• Background Events: Background events are
those that require end-user interaction.
Operating system interrupts and hardware or
software failures are examples of background
events.
Event source
Event listeners
Event Classes
Event Classes
ActionListener:
• actionPerformed()
ComponentListener:
• componentResized()
• componentMoved()
• componentShown()
• componentHidden()
FocusListener:
• focusGained()
• focusLost()
ItemListener:
• itemStateChanged
keyListener:
• keyTyped()
• keyPressed()
• keyReleased()
TextListener:
• textChange()
WindowListener:
• windowActivated()
• windowDeactivated()
MouseListener:
• mousePressed()
• mouseClicked()
• mouseEntered()
• mouseReleased()
MouseMotionListener:
• mouseMove()
• mouseDragged()
Delegation of event model
• The modern approach to handling events is based
on the delegation event model.
• The delegation event model defines standard and
consistent mechanisms to generate and process
events.
• Its concept is quite simple: a source generates an
event and sends it to one or more listeners.
• In this scheme, the listener simply waits until it
receives an event. Once received, the listener
processes the event and then returns.
Delegation of event model
Delegation of event model
There are three participants in event delegation
model
• - Event Source – the class which broadcasts
the events
• - Event Listeners – the classes which receive
notifications of events
• - Event Object – the class object which
describes the event
Steps to handle events (Event Handling)
Step 1: Import classes from the package:
import java.awt.event.*;
Step 2: Implement the appropriate listener interfaces.
public class sample extends Applet implements listenerinterface1{
} //Several listener interfaces can be listed, separated by commas.
Step 3: Register the listener object with the appropriate event
source.
event_source_object.addevent_listenername(event_listener_objec
t);
//Normally, you use the keyword this for event_listener_object.
Step 4: Define all the methods of the implemented listener
interfaces
Handling mouse and keyboard events-
Mouse Events

• The Java MouseListener is notified whenever you


change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in
java.awt.event package. It has five methods.
Methods of MouseListener interface
• public abstract void mouseClicked(MouseEvent e);
• public abstract void mouseEntered(MouseEvent e);
• public abstract void mouseExited(MouseEvent e);
• public abstract void mousePressed(MouseEvent e);
• public abstract void mouseReleased(MouseEvent e);
Four steps:
Step 1: Include the following import statement:
import java.awt.event.*;
Step 2: Include Implements MouseListener :
public class W2 extends Applet implements MouseListener { }
Step 3: Register addMouseListener method in the applet.
this.addMouseListener (this);
Step 4: Define the five MouseListener methods:
public void mouseClicked(MouseEvent event){
}
public void mouseEntered(MouseEvent event){
}
public void mouseexited(MouseEvent event){
}
public void mousePressed(MouseEvent event){
}
public void mouseReleased(MouseEvent event){
}
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MouseEvent1 extends Applet implements MouseListener{
public void init() {
this.addMouseListener(this);
}public void mouseClicked(MouseEvent e){
setBackground(Color.blue);
}
public void mouseEntered(MouseEvent e){
setBackground(Color.cyan);}
public void mouseExited(MouseEvent e){
setBackground(Color.green);
}
public void mousePressed(MouseEvent e){
setBackground(Color.magenta);
}
public void mouseReleased(MouseEvent e){
setBackground(Color.yellow);
}
MouseMotionListener Interface
• The Java MouseMotionListener is notified
whenever you move or drag mouse.
• It is notified against MouseEvent. The
MouseMotionListener interface is found in
java.awt.event package. It has two methods.
Methods of MouseMotionListener interface
• public abstract void mouseDragged(MouseEvent
e);
• public abstract void mouseMoved(MouseEvent e);
Key Events
• KeyListener Interface
The KeyListener is notified whenever you
change the state of key. It is notified against
KeyEvent. It has three methods.
• public abstract void keyPressed(KeyEvent e);
• public abstract void keyReleased(KeyEvent e);
• public abstract void keyTyped(KeyEvent e);
import java.awt.*;
import java.awt.event.*;
class Keydemo extends Frame implements KeyListener
{
Keydemo()
{
addKeyListener(this);
setTitle("Keyeventdemo");
setLayout(null);
setVisible(true);
setSize(400,400);
}
public void keyReleased(KeyEvent ke)
{
setBackground(Color.orange);
}
public void keyPressed(KeyEvent ke)
{
setBackground(Color.cyan);
}
public void keyTyped(KeyEvent ke)
{
Adapter classes
Adapter classes provide the default implementation of listener interfaces. If you inherit
the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.
• 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.

Adapter class -- Listener interface


WindowAdapter -- WindowListener
KeyAdapter -- KeyListener
MouseAdapter -- MouseListener
MouseMotionAdapter -- MouseMotionListener
FocusAdapter -- FocusListener
ComponentAdapter -- ComponentListener
ContainerAdapter -- ContainerListener
HierarchyBoundsAdapter -- HierarchyBoundsListener
import java.awt.*;
import java.awt.event.*;
public class AdapterExample{
Frame f;
AdapterExample(){
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose();
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
}
}
AWT

• AWT stands for Abstract Window Toolkit. It is a platform


dependent API for creating Graphical User Interface (GUI) for
java programs.
• AWT calls native platform (Operating systems) subroutine for
creating components such as textbox, checkbox, button etc.
• AWT components are considered heavy weight because they
are being generated by underlying operating system (OS).
AWT Hierarchy
Components
• All the elements like buttons, text fields, scrollbars etc are
known as components.
• In AWT we have classes for each component

Methods of Component class


• public void add(Component c): inserts a component on
this component.
• 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.
Containers

To have everything placed on a screen
.

to a particular position, we have to add


them to a container.
• A container is like a screen wherein we
are placing components like buttons,
text fields, checkbox etc.
• In short a container contains and
controls the layout of components.
Types of containers
There are four types of containers available in AWT: Window,
Frame, Dialog and Panel.
• Frame and Dialog are subclasses of Window class.
• Window: An instance of the Window class has no border and no
title
• Dialog: Dialog class has border and title. An instance of the
Dialog class cannot exist without an associated instance of the
Frame class.
• Panel: Panel does not contain title bar, menu bar or border. It is a
generic container for holding components. An instance of the
Panel class provides a container to which to add components.
• Frame: A frame has title, border and menu bars. It can contain
several components like buttons, text fields, scrollbars etc. This is
most widely used container while developing an application in
AWT.
To create simple awt example, you need a frame. There are two ways to create
a frame in AWT.
• By extending Frame class (inheritance)
• By creating the object of Frame class (association)

import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
import java.awt.*;
class First2{
First2(){
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);
}
public static void main(String args[]){
First2 f=new First2();
}}
User interfaces components
• Labels
• Buttons
• Canvas
• Scrollbars
• Text Components
• Checkbox
• Checkbox Groups
• Choices
• Menu
• Lists and etc
Labels
• java.awt.Label
Label provides a descriptive text string. Take
note that System.out.println() prints to the
system console, not to the graphics screen. It
could use a Label to label another component
(such as text field) to provide a text description.
Constructors
// Construct a Label with the given text String, of the text alignment
public Label(String strLabel, int alignment);

// Construct a Label with the given text String


public Label(String strLabel);

public Label(); // Construct an initially empty Label

Methods in Lable
public String getText();
public void setText(String strLabel);
public int getAlignment();
public void setAlignment(int alignment); // Label.LEFT, Label.RIGHT,
Label.CENTER
Button
• java.awt.Button
Button is a GUI component that triggers a certain
programmed action upon clicking.
Constructors
public Button(String btnLabel);
// Construct a Button with the given label
public Button();
// Construct a Button with empty label
Public Methods
public String getLabel();
// Get the label of this Button instance
public void setLabel(String btnLabel);
// Set the label of this Button instance
public void setEnable(boolean enable);
// Enable or disable this Button. Disabled Button cannot be clicked.
The getLabel() and setLabel() methods can be used to read the
current label and modify the label of a button, respectively
TextField
java.awt.TextField
A java.awt.TextField is single-line text box for users to enter texts
Constructors
public TextField(String initialText);
// Construct a TextField instance with the given initial text string.
public TextField(int columns);
// Construct a TextField instance with the number of columns.
public TextField(String initialText, int columns);
// Construct a TextField instance with the given initial text string with the number
of columns.
Public Methods
public String getText();
// Get the current text on this TextField instance
public void setText(String strText);
// Set the display text on this TextField instance
public void setEditable(boolean editable);
// Set this TextField to editable (read/write) or non-editable (read-only)
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".
• To find out the state of a checkbox object we
can use getState() that returns a true or false
value.
Constructors are
Checkbox()
Creates a check box with an empty string for its
label.
Checkbox(String label)
Creates a check box with the specified label.
Checkbox(String label, boolean state)
Creates a check box with the specified label and
sets the specified state.
CheckboxGroup

• CheckboxGroup class is used to group


together a set of Checkbox.
• At a time only one check box button is allowed
to be in "on" state and remaining check box
button in "off" state.
Constructor
CheckboxGroup()
Creates a new instance of CheckboxGroup.
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
List
• java.awt.List
• List components objects are useful for holding a
large number of data items.
• They are quite similar to the Choice component,
however they can allow for the multiple selection of
items.
• The list automatically adds a scrollbar if it is
required.
• The list constructor takes two arguments, the int
number of items to be displayed and a boolean to
allow/disallow multiple item selection.
Java List panels
List provides these constructors:
• List( )
• List(int numRows)
• List(int numRows, boolean multipleSelect)
• To add a selection to the list, call add( ).
• It has the following two forms: void add(String name) void
add(String name, int index)
import java.awt.*;
public class ListExample
{
ListExample(){
Frame f= new Frame();
List l1=new List(5);
l1.setBounds(100,100, 75,75);
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
f.add(l1);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}
Choice
• Choice class is used to show popup menu of
choices.
• Choice selected by user is shown on the top of
a menu. It inherits Component class.
Constructor
• Choice() :Creates a new choice menu.
import java.awt.*;
public class ChoiceExample
{
ChoiceExample(){
Frame f= new Frame();
Choice c=new Choice();
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);
}
public static void main(String args[])
{
new ChoiceExample();
}
}
Scroll Bars
• Scroll bars are used to select continuous values between a specified minimum
and maximum. Scroll bars may be oriented horizontally or vertically.
• A scroll bar is actually a composite of several individual parts. Each end has an
arrow that you can click to move the current value of the scroll bar one unit in
the direction of the arrow.
• The current value of the scroll bar relative to its minimum and maximum
values is indicated by the slider box (or thumb) for the scroll bar
• Scrollbar defines the following constructors:
• Scrollbar( ) throws HeadlessException
• Scrollbar(int style) throws HeadlessException
• Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
• The first form creates a vertical scroll bar. The second and third forms allow
you to specify the orientation of the scroll bar. If style is Scrollbar.VERTICAL, a
vertical scroll bar is created.
• If style is Scrollbar.HORIZONTAL, the scroll bar is horizontal. In the third form of
the constructor, the initial value of the scroll bar is passed in initialValue
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();
}
}
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.
import java.awt.*;
class MenuExample
{

MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
Canva
• 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. Canvas class
inherits the Component class.
Constructor of the Canvas class are :

• Canvas(): Creates a new blank canvas.


• Canvas(GraphicsConfiguration c): Creates a new
canvas with a specified graphics configuration.
Methods in Canvas Class

addNotify()
Commonly used Methods in Canvas Class

createBufferStrategy(int n)

createBufferStrategy(int n, BufferCapabilities c)

getBufferStrategy()

paint(Graphics g)

update(Graphics g)
Layout Manager
• All of the components that we have shown so far
have been positioned by the default layout manager.
• Each Container object has a layout manager
associated with it. A layout manager is an instance of
any class that implements the LayoutManager
interface.
• The layout manager is set by the setLayout( )
method. If no call to setLayout( ) is made, then the
default layout manager is used
SYNTAX
• void setLayout(LayoutManager layoutObj)
Layout Types
• FlowLayout
• BorderLayout
• GridLayout
• CardLayout
• GridBagLayout
FlowLayout
• FlowLayout is the default layout manager.
• This is the layout manager that the preceding examples have used.
• FlowLayout implements a simple layout style, which is similar to
how words flow in a text editor.
• The direction of the layout is governed by the container’s
component orientation property, which, by default, is left to right,
top to bottom.
• Here are the constructors for FlowLayout:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)

FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
BorderLayout

The BorderLayout class implements a common layout style for top-level windows. It has four
narrow, fixed_x0002_width components at the edges and one large area in the center. The four
sides are referred to as north, south,
east, and west. The middle area is called the center.
• Here are the constructors defined by BorderLayout:
BorderLayout( )
BorderLayout(int horz, int vert)
 The first form creates a default border layout.
 The second allows you to specify the horizontal and vertical space left between components
in horz
and vert, respectively.
• BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
When adding components, you will use these constants with the following form of add( ),
which is defined by
Container:
import java.awt.*;
class BorderLayoutExample extends Frame
{
BorderLayoutExample()
{
setLayout(new BorderLayout());
add(new Button("NORTH"),BorderLayout.NORTH);
add(new Button("SOUTH"),BorderLayout.SOUTH);
add(new Button("EAST"),BorderLayout.EAST);
add(new Button("WEST"),BorderLayout.WEST);
add(new Button("CENTER"),BorderLayout.CENTER);
}}
class BorderLayoutJavaExample
{
public static void main(String args[])
{
BorderLayoutExample frame = new BorderLayoutExample();
frame.setTitle("BorderLayout in Java Example");
frame.setSize(400,150);
frame.setVisible(true);
}}
GridLayout
• GridLayout lays out components in a two-dimensional grid.
• When you instantiate a GridLayout, you define the number of
rows and columns.
• The constructors supported by GridLayout are shown here:
• GridLayout( )
• GridLayout(int numRows, int numColumns)
• GridLayout(int numRows, int numColumns, int horz, int vert)
•  The first form creates a single-column grid layout.
•  The second form creates a grid layout with the specified
number of rows and columns.
•  The third form allows you to specify the horizontal and vertical
space left between components in horz and vert, respectively.
Either numRows or numColumns can be zero. Specifying
numRows as zero allows for unlimited-length columns.
import java.awt.*;
class GridLayoutExample extends Frame
{
GridLayoutExample()
{
Button[] button =new Button[12];
setLayout(new GridLayout(4,3));
for(int i=0; i<button.length;i++)
{
button[i]=new Button("Button "+(i+i));
add(button[i]);
}
}}
class GridLayoutJavaExample
{
public static void main(String args[])
{
GridLayoutExample frame = new GridLayoutExample();
frame.setTitle("GridLayout in Java Example");
frame.setSize(400,150);
frame.setVisible(true);
}}
CardLayout
• The CardLayout class is unique among the other layout managers in that 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.
•  This can be useful for user interfaces with optional components that can
be dynamically enabled and disabled upon user input. You can prepare the
other layouts and have them hidden, ready to be activated when needed.
•  CardLayout provides these two constructors:
•  CardLayout( )
•  CardLayout(int horz, int vert)
•  The first form creates a default card layout.
•  The second form allows you to specify the horizontal and vertical space
left between components in horz and vert, respectively
• void add(Component panelObj, Object name)
import java.awt.*;
import java.awt.event.*;
class CardLayoutExample extends Frame implements ActionListener
{
CardLayout card = new CardLayout(20,20);
CardLayoutExample()
{
setLayout(card);
Button Btnfirst = new Button("first ");
Button 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);
}}
class CardLayoutJavaExample
{
public static void main(String args[])
{
CardLayoutExample frame = new CardLayoutExample();
frame.setTitle("CardLayout in Java Example");
frame.setSize(220,150);
frame.setResizable(false);
frame.setVisible(true);
}
}
GridBagLayout
• What makes the grid bag useful is that you can specify
the relative placement of components by specifying
• their positions within cells inside a grid. The key to the
grid bag is that each component can be a different size,
• and each row in the grid can have a different number
of columns. This is why the layout is called a grid bag.
• It’s a collection of small grids joined together.
• GridBagLayout defines only one constructor, which is
shown here:
• GridBagLayout( )

You might also like