Java Event Handling in Linux Programming
Java Event Handling in Linux Programming
4. EVENT HANDLING
Events are integral part of the java platform. It is an action or occurrence, often
generated by the user, to which the program might respond— An example of an event is
the user of a computer pressing a button on the screen. Another is the typing of any key
on the keyboard.
In traditional programming model, the application controls program flow. This flow is
predetermined by the statements and conditions that are coded.
Events do not adhere to this traditional approach because they occur outside of
program control. When an event happens, the application is notified, causing the
execution of a piece of code. Usually, this notification involves calling a predefined
procedure or function, passing it enough information to identify the event so that the
application can perform its logic.. Event-driven programming provides the means to
develop flexible applications where the user determines program flow.
In the delegation event model, listeners must register with a source in order
to receive an event notification. This provides an important benefit: notifications are
sent only to listeners that want to receive them. This is a more efficient way to handle
events.
Events
1
Module IV Java Programing using Linux
In the delegation model, 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 in a graphical
user interface. Some of the activities that cause events to be generated are pressing a button,
entering a character via the keyboard, selecting an item in a list, and clicking the mouse
Event Sources
A source is an object that generates an event. This occurs when the internal
state of that object changes in some way. Sources may generate more than one type of
event. A source must register listeners in order for the listeners to receive notifications
about a specific type of event. Each type of event has its own registration method. Here
is the general form:
Event Listeners
A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to receive
notifications about specific types of events. Second, it must implement methods to
receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces
found in [Link]. For example, the MouseMotionListener interface defines two
methods to receive notifications when the mouse is dragged or moved. Any object may
receive and process one or both of these events if it provides an implementation of this
interface.
Event Classes
The classes that represent events are at the core of Java’s event handling mechanism. At
2
Module IV Java Programing using Linux
the root of the Java event class hierarchy is EventObject, which is in [Link]. It is the superclass
for 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( ). The getSource( ) method returns the source of the
event. Its general form is shown here:
Object getSource( )
int getID( )
(Fig : 4.1)
3
Module IV Java Programing using Linux
4
Module IV Java Programing using Linux
Here, src is a reference to the object that generated this event. The type of the event is
specified by type, and its command string is cmd. The argument modifiers indicates which
modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was
generated. The when parameter specifies when the event occurred.
ComponentEvent Class
A ComponentEvent is generated when the size, position, or visibility of a
component is changed. There are four types of component events. The ComponentEvent
class defines integer constants that can be used to identify them. The constants and their
5
Module IV Java Programing using Linux
FocusEvent Class
A FocusEvent is generated when a component gains or loses input focus. These events
are identified by the integer constants FOCUS_GAINED and FOCUS_LOST. FocusEvent is a
subclass of ComponentEvent and has these constructors:
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryFlag)
Focus Event(Component src, int type, boolean temporaryFlag, Component other)
Here, src is a reference to the component that generated this event. The type of the event is
specified by type. The argument temporaryFlag is set to true if the focus event is temporary.
Otherwise, it is set to false. (A temporary focus event occurs as a result of another user interface
operation. For example, assume that the focus is in a text field. If the user moves the mouse to
adjust a scroll bar, the focus is temporarily lost.) The other component involved in the focus
change, called the opposite component, is passed in other. Therefore, if a FOCUS_GAINED event
occurred, other will refer to the component that lost focus. Conversely, if a FOCUS_LOST event
occurred, other will refer to the component that gains focus.
ItemEvent class
An ItemEvent is generated when a check box or a list item is clicked or when a checkable
menu item is selected or deselected. There are two types of item events, which are identified by the
following integer constants:
DESELECTED The user deselected an item.
SELECTED The user selected an item.
6
Module IV Java Programing using Linux
KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
Here, src is a reference to the component that generated the event. The type of the
event is specified by type. The system time at which the key was pressed is passed in when. The
modifiers argument indicates which modifiers were pressed when this key event occurred. The
virtual key code, such as VK_UP, VK_A, and so forth, is passed in code. The character
equivalent (if one exists) is passed in ch. If no valid character exists, then ch contains
CHAR_UNDEFINED. For KEY_TYPED events, code will contain VK_UNDEFINED
7
Module IV Java Programing using Linux
Control Description
ActionListener This interface is used for receiving the action events.
MouseMotionListener This interface is used for receiving the mouse motion events.
8
Module IV Java Programing using Linux
This interface defines four methods that are invoked when a component is resized,
moved, shown, or hidden. Their general forms are shown here:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
The FocusListener Interface
This interface defines two methods. When a component obtains keyboard focus,
focusGained() is invoked. When a component loses keyboard focus, focusLost( ) is called. Their
general forms are shown here:
9
Module IV Java Programing using Linux
ADAPTER CLASS
10
Module IV Java Programing using Linux
Java provides a special feature, called an adapter class, that can simplify the creation of
event handlers in certain situations. An adapter class provides an empty implementation of all
methods in an event listener interface. Adapter classes are useful when you want to receive and
process only some of the events that are handled by a particular event listener interface. You can
define a new class to act as an event listener by extending one of the adapter classes and
implementing only those events in which you are interested.
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ). The signatures of these empty methods are exactly as defined in the
MouseMotionListener interface. If you were interested in only mouse drag events, then you could
simply extend MouseMotionAdapter and implement mouseDragged().The empty implementation
of mouseMoved( ) would handle the mouse motion events for you.
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ). The signatures of these empty methods are exactly as defined in the
MouseMotionListener interface. If you were interested in only mouse drag events, then you
could simply extend MouseMotionAdapter and implement mouseDragged().The empty
implementation of mouseMoved( ) would handle the mouse motion events for you.
ContainerAdapter ContainerListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
KeyAdapter KeyListener
FocusAdapter FocusListener
Java AWT
Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components are using the resources
of OS.
11
Module IV Java Programing using Linux
The [Link] package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
12
Module IV Java Programing using Linux
Method Description
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.
Java Swing
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
The [Link] package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
There are many differences between java awt and swing that are given below.
13
Module IV Java Programing using Linux
The methods of Component class are widely used in java swing that are given below.
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int sets size of the component.
height)
public void setLayout(LayoutManager sets the layout manager for the component.
m)
public void setVisible(boolean b) sets the visibility of the component. It is by default
false.
14
Module IV Java Programing using Linux
import [Link].*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
15
Module IV Java Programing using Linux
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a user
cannot edit it directly. It inherits JComponent class.
16
Module IV Java Programing using Linux
The object of a JTextField class is a text component that allows the editing of a single
line text. It inherits JTextComponent class.
Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.
Methods Description
void addActionListener(ActionListener l) It is used to add the specified action listener to
receive action events from this textfield.
Action getAction() It returns the currently set Action for this
ActionEvent source, or null if no Action is set.
void setFont(Font f) It is used to set the current font.
void removeActionListener(ActionListener l) It is used to remove the specified action listener
so that it no longer receives action events from
this textfield.
Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class
17
Module IV Java Programing using Linux
Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text initially.
JTextArea(int row, int column) Creates a text area with the specified number of rows and
columns that displays no text initially.
JTextArea(String s, int row, int Creates a text area with the specified number of rows and
column) columns that displays specified text.
Methods Description
void setRows(int rows) It is used to set specified number of rows.
void setColumns(int cols) It is used to set specified number of columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int It is used to insert the specified text on the specified position.
position)
void append(String s) It is used to append the given text to the end of the document.
Java JCheckBox
The JCheckBox 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 ".It
inherits JToggleButton class.
Constructor Description
JJCheckBox() Creates an initially unselected check box button
with no text, no icon.
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether
or not it is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken
from the Action supplied.
Methods Description
AccessibleContext It is used to get the AccessibleContext associated with this
getAccessibleContext() JCheckBox.
protected String paramString() It returns a string representation of this JCheckBox.
Java JRadioButton
18
Module IV Java Programing using Linux
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified text.
JRadioButton(String s, boolean Creates a radio button with the specified text and selected
selected) status.
Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void It is used to add the action listener to this object.
addActionListener(ActionListener a)
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.
Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
19
Module IV Java Programing using Linux
The object of JList class represents a list of text items. The list of text items can be set up so that
the user can choose either one item or multiple items. It inherits JComponent class.
Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> Creates a JList that displays elements from the specified, non-null,
dataModel) model.
The [Link] class is a type of container which inherits the [Link] class.
JFrame works like the main window where components like labels, buttons, textfields are added
to create a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
20
Module IV Java Programing using Linux
Nested Class
Modifier and Type Class Description
protected class [Link] This class implements accessibility support
for the JFrame class.
Fields
Modifier and Type Field Description
protected accessibleContext The accessible context property.
AccessibleContext
static int EXIT_ON_CLOSE The exit application default window close
operation.
protected rootPane The JRootPane instance that manages the
JRootPane contentPane and optional menuBar for this
frame, as well as the glassPane.
protected boolean rootPaneCheckingEnab If true then calls to add and setLayout will be
led forwarded to the contentPane.
Constructors
Constructor Description
JFrame() It constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration gc) It creates a Frame in the specified
GraphicsConfiguration of a screen device and a blank
title.
JFrame(String title) It creates a new, initially invisible Frame with the
specified title.
JFrame(String title, It creates a JFrame with the specified title and the
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen device.
Java JPanel
The JPanel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the JComponents class.
21
Module IV Java Programing using Linux
a flow layout.
JPanel(boolean isDoubleBuffered) It is used to create a new JPanel with FlowLayout and the
specified buffering strategy.
JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout
manager.
Java LayoutManagers
1. BorderLayout 4. CardLayout
2. FlowLayout 5. Box Layout
3. GridLayout
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is
the default layout of applet or panel.
22
Module IV Java Programing using Linux
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.
23
Module IV Java Programing using Linux
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
import [Link].*;
import [Link].*; [Link](b1); [Link](b2); [Link](b3);
[Link](b4); [Link](b5);
public class MyGridLayout{ [Link](b6); [Link](b7); [Link](b8);
JFrame f; [Link](b9);
MyGridLayout(){
f=new JFrame(); [Link](new GridLayout(3,3));
JButton b1=new JButton("1"); //setting grid layout of 3 rows and 3 col
JButton b2=new JButton("2"); umns
JButton b3=new JButton("3"); [Link](300,300);
JButton b4=new JButton("4"); [Link](true);
JButton b5=new JButton("5"); }
JButton b6=new JButton("6"); public static void main(String[] args) {
JButton b7=new JButton("7"); new MyGridLayout();
JButton b8=new JButton("8"); }
JButton b9=new JButton("9"); }
24
Module IV Java Programing using Linux
Java BoxLayout
The BoxLayout is used to arrange the components either vertically or horizontally. For this
purpose, BoxLayout provides four constants. They are as follows:
25
Module IV Java Programing using Linux
The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.
26
Module IV Java Programing using Linux
o public void previous(Container parent): is used to flip to the previous card of the given
container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card
with the given name.
27