Professional Documents
Culture Documents
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:
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:
Methods:
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
• 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:
(iv)JTextField(String str, int col)- creates a new TextField with specified text and columns.
Methods:
(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.
• 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:
• (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:
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.
Constructors:
(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.
• When selected, the state is on and a small tick is displayed in the box.
Constructors:
• (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.
Constructors:
(iii)JRadioButton(String s, Boolean on)- Creates a radio button with the specified text and selected
status.
Methods:
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.
Constructors:
(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:
Methods:
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
• General form:
• When event occurs- all registered listeners notified and receive a copy of event object.
• General form:
Event Listeners:
• 1st : It must have registered with one or more sources to receive 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