MODULE 4 – EVENT HANDLING
syllabus
Event Handling-Delegation Event Model-Event Classes-Sources of Events-
Event Listeners-Swing- architecture, components of swing- JLabel, JButton,
JCheckBox, JRadioButton, JList, JComboBox, JTextField, JText Area,
JPanel, JFrame, Layout Managers(Flow Layout, Grid Layout, Card Layout,
Border Layout, Box Layout, Null Layout ).
DELEGATION EVENT MODEL [2mark/MGU 2021, 5mark/MGU
2020]
The modern approach to handling event is called event delegation model.The
delegation event model defines standard and consistent mechanisms to generate and
process events.The concept is as follows
A source generates an event and sends it to one or more listeners.The listener
simply waits until it receives an event.Once received, the listener process the
event and then returns. In this model, the listeners must register with the source
in order to receive an event notification.The notifications are only sent to those
listeners that registers with the source.
Event delegation model contains
Events
Sources
Event Listeners
Events
An event is an object that describes a state change in a source.It can be generated as a
consequence of a person interacting with the elements of GUI. Some of the examples
are pressing a button,entering a text via keyboard, selecting an item in a list etc.
1
Event Sources
A source is an object that generates an event.Sources may generate more than one
type of event.
The sources must register with the listeners in order to receive notifications about a
specific type of event. Each type of event has its own registration method
Syntax is:
Pubic void addTypeListener(TypeListener e)
Here ‘Type’ is the name of the event.For example, to register with the keyboard we
use the listener called KeyListener.Then the registration method is
addKeyListener()
To unregister with the listener,use the method
Public void removeTypeListener(TypeListener e)
Event Listeners:
A listener is an object which is notified when an event occurs.It has two major
requirements
It must have been registered with one or more sources to receive notification
about an event
It must implement the methods to receive and process these notifications
Following Table shows the Event classes and Event Listeners Used in Event
delegation model
2
3
Following table shows the sources of events in java
SWING CLASS AND IT’S ARCHITECTURE[2mark/MGU 2020,
5mark/MGU 2019]
Initially java introduced a package called abstract window toolkit(AWT).This
package contains large number of classes and interfaces for the creation of GUI.But
AWT classes and it’s methods are dependent on the machine in which they are
executed.As a result,the appearance of the screen will be different for different
platforms
4
As the goal of java developers was to create platform independent programs.So they
introduces new classes in the new version of java.These new classes are packaged in
package called swing.Swing classes are part of JFC(Java Foundation Classes).
The swing classes are contained in java’s extension package called
javax.swing.These classes are used to create the screen’s with same look and feel in
different platforms.
Following table illustrate the diffreence between AWT and Swing classes in java
CONTEXT AWT SWING
API Package The AWT Component classes are The Swing component classes are
provided by the java.awt package. provided by the javax.swing
package.
Operating The Components used in AWT are The Components used in Swing are
System mainly dependent on the operating not dependent on the operating
system. system. It is completely scripted in
Java.
Appearance The Appearance of AWT The Swing Components are
Components is mainly not configurable and mainly support
configurable. It generally depends on pluggable look and feel.
the operating system's look and feels.
Number of The Java AWT provides a smaller Java Swing provides a greater
Components number of components in number of components than AWT,
comparison to Swing. such as list, scroll panes, tables,
color choosers, etc.
Full-Form Java AWT stands for Abstract Java Swing is mainly referred to as
Window Toolkit. Java Foundation Classes (JFC).
Memory Java AWT needs a higher amount of Java Swing needs less memory space
memory for the execution. as compared to Java AWT.
5
Speed Java AWT is slower than swing in Java Swing is faster than the AWT.
terms of performance.
Swing Architecture
Jcomponent class contains a large number of sub-classes like Jlabel,Jlist,Jpanel…etc
which are used to create the GUI
I. Creating windows using Jframe
6
JFrame is a subclass of class Frame. When Jframe window is created,it’s size will be
(0,0) and is invisible.Jframe window generate the following events
WindowClosed
WindowOpened
WindowClosing
WindowActivated
WindowDeactivated
WindowIconified
WindowDeiconified
Constructors
JFrame()- creates an invisible window without a title
JFrame(String str)- creates awindow with given title
Methods
String getTitle() – Retrieve the title of window
Void setTitle(String str) – Set the title of window
Void setVisible(Boolean b) – Used to show/hide the window
Void setSize(int width, int height) - used to set the size of window
Program
import javax.swing.*;
public class sample extends JFrame
Container con;
sample()
super(“example program”);
7
con=getContentPane();
con.setLayout(new FlowLayout());
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
});
}}
class smain
public static void main(String args[])
sample s=new sample();
s.setSize(500,800);
s.setVisible(True);
}}
II. JLabel [15mark/MGU 2021]
Jlabel is a subclass of Jcompnent. It displays a single line of read-only text.
Following constants are used to set the alignment label content
JLabel.LEFT
JLabel.RIGHT
8
JLabel.CENTER
JLabel.TOP
JLabel.BOTTOM
Constructors
JLabel() – creates an empty label
JLabel(String str) – Creates a label with specified text
JLabel(String str, int align) – Creates a label with specified text and with specified
alignment
Methods
String getText() – Retrieve the text of label
Void setText ( String str) – used to set the text of label
III. JTextField,JPasswordField and JTextArea
JTextField
It displays one line editable text. Following constants are used to set the alignment of
text field content
JTextField.LEFT
JTextField.RIGHT
JTextField.CENTER
Constructors
JTextField() – creates a new Textfield.But the number of characters in this Textfield
will be 0
JTextField(String str) – creates a new Textfield with the specified string
JTextField(int size) - creates a new Textfield with the specified number of characters
Methods
9
String getText() – Retrieves the text contained in a textfield
Void setText( String str) –set the content of textfield
String getSelectedText() – Used to get the selected text from the textfield
JPasswordField
Constructors
JPasswordField() –creates an empty passwordField.
JPasswordField(String str)- creates a passwordField with specified text
Methods
String getText() – Retrieves the text contained in a passwordfield
char getEchoChar() – retrieves the eco character set for the password field
JTextArea
It displays a text component which have multiple line of text
Constructors
JTextArea() – creates an empty text area
JTextArea(int row, int col) – creates a text area with specified number of rows and
columns
Methods
String getText() – Retrieves the text contained in a TextArea
String getSelectedText() – Used to get the selected text from the TextArea
Void append(String str) – add the specified text at the end of the Textarea
Program which shows JLabel,JtextField,JPasswordField and JTextArea
10
import javax.swing.*;
public class sample extends JFrame
Container con;
JLabel l1,l2,l3;
JTextField t1;
JPasswordField p1;
JTextArea a1;
sample()
super(“example program”);
con=getContentPane();
con.setLayout(new FlowLayout());
l1=new JLabel(“username”);
l2= new JLabel(“password”);
l3=new JLabel(“description”);
t1=new JTextField(20);
p1=new JPasswordField();
a1=new JTextArea();
con.add(l1);
con.add(t1);
con.add(l2);
con.add(p1);
11
con.add(l3);
con.add(a1);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
});
}}
class smain
public static void main(String args[])
sample s=new sample();
s.setSize(500,800);
s.setVisible(True);
}}
IV. Jbutton[15mark/MGU 2021]
JButton is the subclass of AbstractButton.It is used to create labelled button
component. When a Button is pressed ,ActionEvent is generated . To process the
ActionEvent, ActionListener is used
Constructors
12
JButton() – Create a button without label
JButton(String str) – Create a button with the specified label
Methods
String getText() – Retrieves the text contained in a buttton
Void setText( String str) –set the content of button
Program
Creates a button with the name “Click me”. When you press the button, the t ext “
hello welcome “ will be displayed on TextField
import javax.swing.*;
public class sample extends JFrame implements ActionListener
Container con;
JButton b1;
JTextField t1;
sample()
super(“example program”);
con=getContentPane();
con.setLayout(new FlowLayout());
b1=new JButton(“Click me”);
t1=new JTextField(20);
con.add(b1);
con.add(t1);
13
b1.addActionListener(this);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
});
public void actionPerformed(ActionEvent e)
if( e.getSource()==b1)
t1.setText(“hello welcome”);
}}
class smain
public static void main(String args[])
sample s=new sample();
s.setSize(500,800);
s.setVisible(True);
}}
14
V. JCheckBox
JCheckbox is the subclass of JtoggleButton. It is a two state graphical component
that will be either in selected(True) or in deselected(False) state
It generate ItemEvent when changing it’s state.ItemListener is used to handle the
ItemEvent and the method used is itemStateChanged()
Constructors
JCheckBox()- creates an empty checkbox
JCheckBox(String str)-creates a checkbox with the specified label
JCheckBox(String str, boolean b)- creates a checkbox with the specified label and
specified state
Methods
String getText() – Retrieves the text contained in a checkbox
void setText( String str) –set the content of checkbox
booelan isSelected()- Retrieves the state of the checkbox
Program
import javax.swing.*;
public class sample extends JFrame implements ItemListener
Container con;
JLabel l1;
JTextField t1;
JcheckBox c1,c2;
sample()
15
super(“example program”);
con=getContentPane();
con.setLayout(new FlowLayout());
l1=new JLabel(“your selected OS is”);
t1=new JtextField(20);
c1=new JCheckBox(“linux”);
c2=new JCheckBox(“windows”);
con.add(c1);
con.add(c2);
con.add(l1);
con.add(t1);
c1.addItemListener(this);
c2.addItemListener(this);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
});
public void itemStateChanged (ItemEvent e)
if(c1.isSelected())
16
{
t1.setText(c1.getText());
if(c2.isSelected())
t1.setText(c2.getText());
}}
class smain
public static void main(String args[])
sample s=new sample();
s.set
Size(500,800);
s.setVisible(True);
}}
VI. JRadioButton
It is generally used to represent a collection of mutually exclusive
buttons.JradioButton generates ItemEvent which is handled by ItemListener by using
the itemStateChanged() method
After creating JRadioButton , they are added to the ButtonGroup by using the add()
method
Constructors
17
JRadioButton() – creates radiobutton without label
JRadioButton(String str) - creates radiobutton with the specified label
JRadioButton(String str, boolean b) - creates radiobutton with the specified label and
with the specified state
Methods
String getText() – Retrieves the text contained in a radiobutton
void setText( String str) –set the content of radiobutton
booelan isSelected()- Retrieves the state of the radiobutton
Program
import javax.swing.*;
public class sample extends JFrame implements ItemListener
Container con;
JLabel l1;
JTextField t1;
JRadioButton r1,r2;
ButtonGroup bg;
sample()
super(“example program”);
con=getContentPane();
con.setLayout(new FlowLayout());
l1=new JLabel(“your selected OS is”);
18
bg=new ButtonGroup();
t1=new JtextField(20);
r1=new JRadioButton(“linux”);
r2=new JRadioButton (“windows”);
bg.add(r1);
bg.add(r2);
con.add(r1);
con.add(r2);
con.add(l1);
con.add(t1);
r1.addItemListener(this);
r2.addItemListener(this);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
});
public void itemStateChanged (ItemEvent e)
if(r1.isSelected())
19
{
t1.setText(r1.getText());
if(r2.isSelected())
t1.setText(r2.getText());
}}
class smain
public static void main(String args[])
sample s=new sample();
s.set
Size(500,800);
s.setVisible(True);
}}
VII. JList
It is a subclass of Jcomponent. It creates a list of items, that allow the user to select
one or more item from the list.
JList generates ListSelectionEvent which is handled by the ListSelectionListener
with the method valueChanged()
Constructor
20
JList()- creates an empty list
JList(object [] b)- creates a list with the items specified in the object array
Method
void setVisibleRowCount(int c) – set the number of rows in the list to be displayed
int getSelectedIndex()-returns the index number of the selected item
object getSelectedValue() – returns the topmost selected value from the list box
object [] getSelectedValues() – returns the array of all selected items in a list box
program
import javax.swing.*;
import java.awt.*;
import javax.swing.Jlist;
import javax.swing.event.ListselectionEvent;
import javax.swing.event.ListselectionListener;
class sample extends JFrame implements ListSelectionListener
Jlist l1;
JTextField t1;
Container con;
sample()
super(“example program”);
con=getContentPane();
con.setLayout(new FlowLayout());
21
String s[ ] = { “apple”,”orange”,”banana”};
l1=new Jlist( s );
t1 = new JTextField(20);
l1.add ListSelectionListener(this);
l1.setVisibleRowCount(3);
con.add(l1);
con.add(t1);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
});
public void valueChanged(ListSelectionEvent e)
t1.setText(l1.getSelectedValue().toString());
class smain
public static void main(String args[])
22
{
sample s=new sample();
s.set
Size(500,800);
s.setVisible(True);
}}
VIII. JComboBox
It is subclass of JComponent and it gives a pop-up list when clicked(same as drop-
down list).That is, it is a combination of JList and JTextField.In Jlist, items cannot be
edited but in JComboBox, items can be edited by setting JComboBox as editable
JcomboBox generates ActionEvent which is handled by the ActionListener by using
the actionPerformed() method
Constructors
JComboBox() – creats an empty combobox
JComboBox(object [] b) - creates a combobox with the items specified in the object
array
Methods
void addItem(object obj) – used to add the specified item in to the combobox
int getItemCount() – Returns the number of items in the combobox
object getSelectedItem() – Returns the currently selected item from the combobox
int getSelectedIndex() – Returns the index of the currently selected item from the
combobox
program
import javax.swing.*;
23
public class sample extends JFrame implements ActionListener
Container con;
JcomboBox c1;
JTextField t1 ;
sample()
super(“example program”);
con=getContentPane();
con.setLayout(new FlowLayout());
String s[ ] = { “apple”,”orange”,”banana”};
c1=new JComboBox(s); // c1=new JComBox();
c1.addItem(“apple”);
c1.addItem(“orange”);
c1.addItem(“banana”);
t1=new JTextField(20);
c1.addActionListener(this);
add(c1);
add(t1);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
24
System.exit(0);
});
public void actionPerformed(ActionEvent e)
if( e.getSource()==c1)
t1.setText(c1.getSelectedItem().toString());
}}
class smain
public static void main(String args[])
sample s=new sample();
s.setSize(500,800);
s.setVisible(True);
}}
25
Layout Managers[2mark/MGU 2021,15mark/MGU 2020,
15mark/MGU 2019]
There are 4 layout managers in java
1. Flow layout
2. Border layout
3. Grid layout
4. Card layout
Flow Layout
It is the defalut layout manager used in java.In flow layout,the components are laid
out from the upper-left corner, left to right and top to bottom. Whem no components
fit on a line, then the next component appears on the next line.A small space is left
between each component above and below as well as left and right
Constructors
FlowLayout() – default layout
FlowLayout(int how) – ‘how’ specifies the alignment of the components.It can have
the following values
FlowLayout.LEFT
FlowLayout.RIGHT
FlowLayout.CENTER
FlowLayout(int how, int horz , int vert) – this form allows to specify the
alignment,vertical and horizontal space left between the components
Example:
(write any example mentioned above)
26
Border Layout
It specifies the common layout style for the top-level windows.here, the window is
divided 5 sections and add the components in respective to these sections.They are
north,south, east, west and center
Sections are
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
BorderLayout.SOUTH
BorderLayout.CENTER
When adding components to the window, we should specify the corresponding
region of the component by using the method
add(Component,Region)
Constructors
BorderLayout() –creates default border layout
BorderLayout( int horz, int vert) - this form allows to specify the vertical and
horizontal space left between the components
Example
public class sample extends JFrame
JLabel l1,l2,l3;
Jbutton b1,b2;
Container con;
sample()
27
{
super(“border example”);
con=getContentPane();
con.setLayout(new BorderLayout());
l1=new JLabel(“hello”);
l2=new JLabel(“welcome”);
l31=new JLabel(“BCA”);
b1=new JButton(“click me”);
b2=new JButton(“ok”);
con.add(l1, BorderLayout.NORTH);
con.add(l2, BorderLayout.SOUTH);
con.add(l2, BorderLayout.CENTER);
con.add(b1, BorderLayout.EAST);
con.add(b2, BorderLayout.WEST);
}}
Using Insets() Method
When using border layout, we can leave a small amount of space between the
container that hold the component and the window that contains it. For that purpose,
we can use the Insets() method.
Insets getInsets()
The constructor for the Insets is
Insets(int top, inr left, int bottom, int right)- it specify the space left in top,
left,bottom and right regions
Example
28
public class sample extends JFrame
JLabel l1,l2,l3;
Jbutton b1,b2;
Container con;
sample()
super(“border example”);
con=getContentPane();
con.setLayout(new BorderLayout());
l1=new JLabel(“hello”);
l2=new JLabel(“welcome”);
l31=new JLabel(“BCA”);
b1=new JButton(“click me”);
b2=new JButton(“ok”);
con.add(l1, BorderLayout.NORTH);
con.add(l2, BorderLayout.SOUTH);
con.add(l2, BorderLayout.CENTER);
con.add(b1, BorderLayout.EAST);
con.add(b2, BorderLayout.WEST);
public Insets getInsets()
29
return new Insets(10,10,10,10);
}}
Grid Layout
Grid layout arranges the components in a two-dimensional grid. So that we need to
specify the number of rows and columns for the grid
Constructors
GridLayout() - It creates a single column grid layout
GridLayout(int numRows,int numColmns) – It creates a grid layout with the
specified number of rows and columns
Example
import javax.swing.*;
public class sample extends JFrame implements ActionListener
int i;
JButton b[];
JTextField t1;
Container con;
sample()
super(“example program”);
con=getContentPane();
con.setLayout(new GridLayout(3,4));
for(i=1;i<=12;i++)
30
{
b[ i]= new JButton(“ “ +i);
con.add(b[i]);
b[i].addActionListener(this);
t1=new JtextField(20);
con.add(t1);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
});
public void actionPerformed(ActionEvent e)
for(i=1;i<=12;i++)
if(e.getSource() == b[i] )
t1.setText(b[i].getText());
}}}
31
}
class smain
public static void main(String args[])
sample s=new sample();
s.setSize(500,800);
s.setVisible(True);
}}
Card layout
This layout is different from other layout managers.That is, it stores several different
layouts.Each Layout can be thought of as a separate index card in a deck
Working
The cards are held in an object of type panel.This panel must selected the
CardLayout as it’s layout manager.The cards that forms the deck are also the object
of type panel.so we must create a panel that contains the deck and a panel for each
card in a deck.Then add the appropriate panels to the components that forms each
card
Constructors
CardLayout() – default layout.
CardLayout(int horz, int vert) - this form allows to specify the vertical and
horizontal space left between the components.
32