UNIT 4_Java Programming
UNIT 4_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
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);
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
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 :
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( )