You are on page 1of 56

Module 1

Introduction to Event
Handling
Traditional Programming
Event driven programming
How Event-Driven Programming works.
Event Handling
1) Event Object:
Event itself an object
2) Event Source:
Event source is the object that is triggered in the event. eg: Checklist, Dropdown
box, etc
3) Event Listener:
A button listens for an event.
An example of event-driven program in
Node.js
Classification of Events

Foreground Events

Event Types

Background Events
1.2. Swing Controls and UI elements
Swing components are the basic building blocks of an application.
Button, check-box, radio-button, text-field, etc. together form the components in Swing.
1. Jbutton
It is used to create a push-button on the UI.
It generates an event when clicked and double-clicked.
• A JButton can be implemented in the application by calling one of its constructors.

Constructors:

• (i)JButton()- creates a button with no text and icon

• (ii)JButton(String s)- button with specified text

• (iii)JButton(Icon i)- button with specified icon object


Methods:

(i)getText()- return the text of the button

(ii)setText(String s)- set specified text

Example:
import javax.swing.*;    
public class ButtonExample {  
public static void main(String[] args) {  
JFrame f=new JFrame("Button Example");  
JButton b=new JButton("Click Here");  
b.setBounds(50,100,95,30);  
f.add(b);  
f.setSize(400,400);  
f.setLayout(null);  
f.setVisible(true);   
}  }
2) JLabel
• JLabel class is used to render a read-only text label or images on the UI. It does not generate any
event.

Constructors:

(i)JLabel()-creates a label without text

(ii)JLabel(String text)- with text

(iii)JLabel(Icon i)- creates a label instance with the specified image.

Methods:

(i)getText()- returns the text string that a label displays.

(ii)setText(String text)- specified text for a label.


import javax.swing.*;  

class LabelExample  

{  

public static void main(String args[])  

{  

JFrame f= new JFrame("Label Example");  

JLabel l1,l2;  

l1=new JLabel("First Label.");  

l1.setBounds(50,50, 100,30);  

l2=new JLabel("Second Label.");  

l2.setBounds(50,100, 100,30); 
f.add(l1); f.add(l2);  

f.setSize(300,300);  

f.setLayout(null);  

f.setVisible(true);  

}  

 
3)JTextField

• JTextField renders an editable single-line text box.

• A user can input non-formatted text in the box.

• To initialize the text field, call its constructor and pass an optional integer parameter to it.

• It does not limit the number of characters that can be input in the box.

Constructors:

(i)JTextField()- empty TextBox gets generated

(ii)JTextField(int col)- creates empty TextField with no. of columns.

(iii)JTextField(String str)- TextBox with specified text

(iv)JTextField(String str, int col)- creates a new TextField with specified text and columns.
Methods:

(i)void setFont(Font f)- used to set current font.

(ii)getColumns()

(iii)setColumns(int col)

Example:

import javax.swing.*;  
class TextFieldExample  
{  
public static void main(String args[])  
{  
JFrame f= new JFrame("TextField Example");  
JTextField t1,t2;  
t1=new JTextField("Welcome to Javatpoint.");  
t1.setBounds(50,100, 200,30);  
t2=new JTextField("AWT Tutorial");  
t2.setBounds(50,150, 200,30);  
f.add(t1); f.add(t2);  
f.setSize(400,400);  
f.setLayout(null);  
f.setVisible(true);  
}  
}  
4) JTextArea
• JTextArea class renders a multi-line text box.

• A user can input non-formatted text in the field.

• The constructor for JTextArea also expects two integer parameters which define the height and
width of the text-area in columns.

• It does not restrict the number of characters that the user can input in the text-area.

• Constructors:

• (i)JTextArea()- displays no text

• (ii)JTextArea(String Text)- displays specified text

• (iii)JTextArea(int rows, int cols)- creates specified number of rows and columns.

• (iv)JTextArea(String text, int rows, int cols)- creates specified number of rows and columns that
displays specified text.
Methods:

(i)setRows(int rows)- used to set specified number of rows.

(ii)setColumns(int col)- used to set specified number of columns.

(iii)void setFont(Font f)- used to set the specified font.

Example:

import javax.swing.*;  

public class TextAreaExample  

{  

     TextAreaExample(){  

        JFrame f= new JFrame();  
JTextArea area=new JTextArea("Welcome to javatpoint");  

        area.setBounds(10,30, 200,200);  

        f.add(area);  

        f.setSize(300,300);  

        f.setLayout(null);  

        f.setVisible(true);  

     }  

public static void main(String args[])  

    {  

   new TextAreaExample();  

    }}  
5)JPasswordField
• JPasswordField is a subclass of JTextField class.

• It renders a text-box that masks the user input text with bullet points.

• This is used for inserting passwords into the application.

Constructors:

(i)JPasswordField()- constructs new empty JPasswordField

(ii)JPasswordField(int col)- with specified no. of columns

(iii)JPasswordField(String str)- initialized with specified text.

(iv)JPasswordField(String str, int col)- initialized with specified text and columns.
Methods:

(i)void setFont(Font f)

(ii)getColumns()

(iii)setColumns(int col)

Example:

import javax.swing.*;    

public class PasswordFieldExample {  

    public static void main(String[] args) {    

    JFrame f=new JFrame("Password Field Example");    

     JPasswordField value = new JPasswordField();   
JLabel l1=new JLabel("Password:");    

        l1.setBounds(20,100, 80,30);    

         value.setBounds(100,100,100,30);    

            f.add(value);  f.add(l1);  

            f.setSize(300,300);    

            f.setLayout(null);    

            f.setVisible(true);     

}  

}  
6) JCheckBox
• JCheckBox renders a check-box with a label.

• The check-box has two states – on/off.

• When selected, the state is on and a small tick is displayed in the box.

Constructors:

• (i)JCheckBox()-Creates an initially unselected check box button with no text, no icon.

• (ii)JCheckBox(String str)-creates an initially unselected check box with text.

• (iii)JCheckBox(String str,Boolean on)- Creates a check box with text and specifies whether or
not it is initially selected.
Methods:

• (i)getState()

• (ii)setState(boolean on)

• (iii)getLabel()

• (iv)setLabel(String str)

Example:

import javax.swing.*;  

public class CheckBoxExample  

{  

     CheckBoxExample(){  

        JFrame f= new JFrame("CheckBox Example");  
 JCheckBox checkBox1 = new JCheckBox("C++");  

 checkBox1.setBounds(100,100, 50,50);  

    JCheckBox checkBox2 = new JCheckBox("Java", 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 CheckBoxExample();  
    }
}  
7) JRadioButton
• JRadioButton is used to render a group of radio buttons in the UI.

• A user can select one choice from the group.

Constructors:

(i)JRadioButton()-Creates an unselected radio button with no text.

(ii)JRadioButton(String str)- Creates an unselected radio button with specified text.

(iii)JRadioButton(String s, Boolean on)- Creates a radio button with the specified text and selected
status.
Methods:

(i)getText()- used to return the text of the button

(ii)setText(String s)-used to set specified text on button.

(iii)setEnabled(Boolean on)- used to enable the button

Example:

import javax.swing.*;    
public class RadioButtonExample {    
JFrame f;    
RadioButtonExample(){    
f=new JFrame();     
JRadioButton r1=new JRadioButton("A) Male");    
JRadioButton r2=new JRadioButton("B) Female");    
r1.setBounds(75,50,100,30);    
r2.setBounds(75,100,100,30);    
ButtonGroup bg=new ButtonGroup();    
bg.add(r1);bg.add(r2);    
f.add(r1);f.add(r2);      
f.setSize(300,300);    
f.setLayout(null);    
f.setVisible(true);    
}    
public static void main(String[] args) {    
    new RadioButtonExample();    
}    
}    
8) JList
• JList component renders a scrollable list of elements.

• A user can select a value or multiple values from the list.

• This select behavior is defined in the code by the developer.

Constructors:

(i)JList()- Creates a JList with an empty, read-only, model.

(ii)JList(Array list[])- creates a JList that displays the elements in the specified array.

Methods:
(i)addItem()
(ii)getSelectedIndex()
(iii)getSelectedValue()
Example:

import javax.swing.*;  

public class ListExample  

{  

     ListExample(){  

        JFrame f= new JFrame();  

        DefaultListModel<String> l1 = new DefaultListModel<>();  

          l1.addElement("Item1");  

          l1.addElement("Item2");  

          l1.addElement("Item3");  

          l1.addElement("Item4");  

      
 JList<String> list = new JList<>(l1);  
 list.setBounds(100,100, 75,75); 
f.add(list);  
          f.setSize(400,400);  
          f.setLayout(null);  
          f.setVisible(true);  
     }  
public static void main(String args[])  
    {  
   new ListExample();  
    }}  
 
9) JComboBox
• JComboBox class is used to render a dropdown of the list of options.

Constructors:

(i)JComboBox()-Creates a JComboBox with a default data model.

(ii)JComboBox(Array items[])-creates a JComboBox that contains the elements in the array.

Methods:

(i)addItem()- add an item to the item list

(ii)removeItem()-used to delete an item to the item list.

(iii)removeAllItems()-It is used to remove all the items from the list.


Example:

import javax.swing.*;    

public class ComboBoxExample {    

JFrame f;    

ComboBoxExample(){    

    f=new JFrame("ComboBox Example");    

    String country[]={"India","Aus","U.S.A","England","Newzealand"};        

    JComboBox cb=new JComboBox(country);    

    cb.setBounds(50, 50,90,20);    

f.add(cb);        

    f.setLayout(null);    

    f.setSize(400,500);    
f.setVisible(true);         

}    

public static void main(String[] args) {    

    new ComboBoxExample();         

}    

}   
10) JFileChooser
• File choosers provide a GUI for navigating the file system, and then either
choosing a file or directory from a list, or entering the name of a file or
directory.
• To display a file chooser, we usually use the JFileChooser API to show a modal
dialog containing the file chooser.
• Another way to present a file chooser is to add an instance of JFileChooser to a
container.
Constructors:
(i)JFileChooser()- constructs a JFileChooser pointing to the user’s default
directory.
(ii)JFileChooser(File)- constructs a JFileChooser using the given file as the path.
(iii)JFileChooser(String)- constructs a JFileChooser using the given path.
Methods:
setSelectedFile(File)-sets the currently selected file or directory
getSelectedFile()-obtain the currently selected file or directory
setSelectedFiles(File[])-set the currently selected file from multiple
selection.
getSelectedFiles()-obtains the currently selected file from multiple
selection.
setFileSelectionMode(int)- sets the file selection mode
getFileSelectionMode()- obtain the file selection mode
1.3.Event-Handling Process
• Java application written for windows- event driven programs.
• Cannot write these programs without event handling.
• Events supported by number of packages- java.util, java.awt, java.awt.event
• Events are created when user interacts with GUI based programs.
• Types of events- generated by the mouse, keyboard and various controls such as
push button, scroll bar, checkbox.
• Old version of java- 1.0
• Modern version of java- 1.1
1.4.The Delegation Model of Event Handling
•Listeners must register with a source inorder to receive an event notification.
•So, notifications are sent only to listeners who want to receive them.
•Efficient way to handle events than the design used by java 1.0 approach.
•This model eliminates the overhead.
Roles of a) Events,
b) Sources,
c) Listeners.
Events:
• It is an object that describes a state change in a source.
• Generated- when people interacting with the elements in GUI.
• Activities- events generated when pressing a button, entering a character via
keyboard.
• Also generated- when people not directly interacting with GUI.
• Activities- events generated when timer expires, s/w or h/w failure occurs.
Event Sources

• Source – an object that generates an event.

• Occurs- when internal state of object changes.

• Generates- more than one type of event.

• Listeners must register with source – to receive the notifications.

• Each type of event- have own registration method.

• General form:

public void addTypeListener(Type Listener el)

• Type-name of the event

• el-reference to the event listener


• method that registers keyboard event listener- addKeyListener()

• method that registers mouse motion listener- addMouseMotionListener()

• When event occurs- all registered listeners notified and receive a copy of event object.

• This is called multicasting the event.

• Some sources allow only one listener to register.

• General form:

public void addTypeListener(Type Listener el) throws java.util.TooManyListenersException

• This is known as Unicasting the event.


• Source- provide a method to unregister listener – for specific type of event.

Public void removeTypeListener(TypeListener el)

• To remove keyboard listener – removeKeyListener()

Event Listeners:

• Listener- object that is notified when an event occurs.

• It has 2 major requirements.

• 1st : It must have registered with one or more sources to receive notifications.

• 2nd : It must implement methods to receive and process these notifications.

• methods to receive and process these notifications- defined in set of interfaces found in
java.awt.event.
1.5. Swing Event Classes
• The most widely used events are those defined by the AWT and
those defined by Swing.
• At the root of the Java event class hierarchy is EventObject which is
in java.util.
• EventObject is a superclass of all events.
• Its one constructor is shown here: EventObject(Object src). Here, src
is the object that generates this event.
• EventObject contains two methods: getSource() and toString().
• getSource- returns the source of the event.
• toString()- returns the string equivalent of the event.
• The class AWT Event, defined within the java.awt package is a
subclass of event object.
• Its getID() method can be used to determine the type of the event.
• The signature of this method is given as: intgetID()
• AWT Event is a superclass of all AWT events that are handled by the
delegation event model.
1.6.Event Sources
1.7.Event Listener
• Event listeners represent the interfaces responsible to handle events. 

• Every method of an event listener method has a single argument as an object which is the
subclass of EventObject class.

• For example, mouse event listener methods will accept instance of MouseEvent, where
MouseEvent derives from EventObject.

• EventListner Interface
• It is a marker interface which every listener interface has to extend. This class is defined
in java.util package.
• Class Declaration
• Following is the declaration for java.util.EventListener interface
• public interface EventListener
1.7Event Listeners
1.8.Adapter Classes as Helper Classes in Event Handling
• It is used to simplify the process of event handling.
• Provide empty implementation of all methods in an event listener
interface.
• Define a new class to act as event listener by extending one of the
adapter classes and implementing only those methods that you
want to use in your code.
• The adapter classes are found in java.awt.event, javax.swing.event
packages

You might also like