0% found this document useful (0 votes)
4 views

Module 4 21CS32 Notes

The document discusses event handling in Java, defining events as changes in object states triggered by user actions or system occurrences. It explains the Delegation Event Model, which includes sources and listeners, and outlines various event classes such as ActionEvent, AdjustmentEvent, and MouseEvent. Additionally, it highlights the advantages of this model, including efficient notifications and separation of application logic from user interface logic.

Uploaded by

Srisaila Nath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Module 4 21CS32 Notes

The document discusses event handling in Java, defining events as changes in object states triggered by user actions or system occurrences. It explains the Delegation Event Model, which includes sources and listeners, and outlines various event classes such as ActionEvent, AdjustmentEvent, and MouseEvent. Additionally, it highlights the advantages of this model, including efficient notifications and separation of application logic from user interface logic.

Uploaded by

Srisaila Nath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Object Oriented Programming using JAVA -21CS32

Module -5

Event Handling
An event can be defined as changing the state of an object or behavior by performing actions.
Actions can be a button click, cursor movement, keypress through keyboard or page scrolling,
etc.
The java.awt.event package can be used to provide various event classes.

Classification of Events

 Foreground Events
 Background Events

1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events
are generated due to interaction by the user on components in Graphic User Interface (GUI).
Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background events.
Examples of these events are operating system failures/interrupts, operation completion, etc.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 1


Object Oriented Programming using JAVA -21CS32

Event Handling
It is a mechanism to control the events and to decide what should happen after an event occur.
To handle the events, Java follows the Delegation Event model.

Delegation Event model

 It has Sources and Listeners.

Delegation Event Model

 Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to generate
events.
 Listeners: Listeners are used for handling the events generated from the source. Each of
these listeners represents interfaces that are responsible for handling events.
 To perform Event Handling, we need to register the source with the listener.
 Registering the Source with Listener
 Different Classes provide different registration methods.

Syntax:
addTypeListener()
where Type represents the type of event.

Example 1: For KeyEvent we use addKeyListener() to register.


Example 2:that For ActionEvent we use addActionListener() to register.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 2


Object Oriented Programming using JAVA -21CS32
Advantages of Event Delegation Model

Notifications are sent only to listeners that want to receive them which is more efficient way
to handle event.
The advantage of this design is that the application logic that processes events is cleanly
separated from the user interface logic that generates those events.
Accelerates the performance of the application which has multiple events.

Components of Delegation Event Model


It has four main components/classes
1) Event Sources
2) Event classes
3) Event Listeners
4) Event Adapters

1. EVENT SOURCES
A source is an object that generates an event.
Event sources are components, subclasses of java.awt.Component, capable to generate
events. The event source can be a button, TextField or a Frame etc.
A source must register listeners in order for the listeners to receive notifications about a
specific type of event.
2. EVENT CLASSES
The classes that are responsible for handling events in event handling mechanism are event
classes.

Java event classes are present in java.util and java.awt.event

 EventObject is a superclass of all events. [java.util]


 AWTEvent is a superclass of all AWT events that are handled by the delegation
event model. [java.awt.event]

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 3


Object Oriented Programming using JAVA -21CS32

3. 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 notificationsabout
specific types of events.
Second, it must implement methods to receive and process these notifications

4. EVENT ADAPTERS

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 4


Object Oriented Programming using JAVA -21CS32
Java adapter classes provide the default implementation of listener interfaces. If you inherit
the adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.

Adapters are abstract classes for receiving various events. The methods in these classes

are empty. These classes exists as convenience for creating listener objects.

Significance of Adapter Class

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 inwhich
you are interested.

E.g. Suppose you want to use MouseClicked Event or method from MouseListener, if you do not
use adapter class then unnecessarily you have to define all other methods fromMouse, But If you
use adapter class then you can only define MouseClicked method and don ’t worry about other
method definition because class provides an empty implementation of allmethods in an event

listener interfaceseListener such as MouseReleased, MousePressed etc.

ActionEvent Class
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a
menu item is selected.
ActionEvent has these three constructors:

ActionEvent(Object src, int type, String cmd)


ActionEvent(Object src, int type, String cmd, int modifiers)
ActionEvent(Object src, int type, String cmd, long when, int
modifiers)

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 5


Object Oriented Programming using JAVA -21CS32
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 indicate which modifier keys
(ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. The when
parameter specifies when the event occurred.
You can obtain the command name for the invoking ActionEvent object by using the
getActionCommand( ) method, shown here:

String getActionCommand( )
The getModifiers( ) method returns a value that indicates which modifier keys (ALT,
CTRL, META, and/or SHIFT) were pressed when the event was generated. Its form is shown
here:
int getModifiers( )
The method getWhen( ) returns the time at which the event took place. This is called the
event’s timestamp. The getWhen( ) method is shown here:
long getWhen( )

AdjustmentEvent Class
An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment
events.
AdjustmentEvent constructor:

AdjustmentEvent(Adjustable src, int id, int type, int data)

Here, src is a reference to the object that generated this event. The id specifies the event. The type
of the adjustment is specified by type, and its associated data is data.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 6


Object Oriented Programming using JAVA -21CS32
ComponentEvent Class
A ComponentEvent is generated when the size, position, or visibility of a component is
changed.
There are four types of component events.

ComponentEvent has this constructor:


ComponentEvent(Component src, int type)
Here, src is a reference to the object that generated this event. The type of the event is specified by
type.
ComponentEvent is the superclass either directly or indirectly of ContainerEvent, FocusEvent,
KeyEvent, MouseEvent, and WindowEvent.
The getComponent( ) method returns the component that generated the event. It is shown
here:
Component getComponent( )

ContainerEvent Class
A ContainerEvent is generated when a component is added to or removed from a
container.
There are two types of container events. The ContainerEvent class defines int constants that
can be used to identify them: COMPONENT_ADDED and COMPONENT_REMOVED.
ContainerEvent is a subclass of ComponentEvent and has this constructor:
ContainerEvent(Component src, int type, Component comp)

Here, src is a reference to the container that generated this event. The type of the event is specified
by type, and the component that has been added to or removed from the container is comp.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 7


Object Oriented Programming using JAVA -21CS32
You can obtain a reference to the container that generated this event by using the getContainer(
) method, shown here:
Container getContainer( )

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)
FocusEvent(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.
You can determine the other component by calling getOppositeComponent( ), shown here:
Component getOppositeComponent( ) The opposite component is returned.

InputEvent Class
It is the superclass for component input events.
Its subclasses are KeyEvent and MouseEvent.
InputEvent defines several integer constants that represent any modifiers, such as the control
key being pressed, that might be associated with the event.

To test if a modifier was pressed at the time an event is generated, use the isAltDown( ),
isAltGraphDown( ), isControlDown( ), isMetaDown( ), and isShiftDown( ) methods.
The forms of these methods are shown here:
boolean isAltDown( )

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 8


Object Oriented Programming using JAVA -21CS32
boolean isAltGraphDown( )
boolean isControlDown( )
boolean isMetaDown( )
boolean isShiftDown( )
You can obtain a value that contains all of the original modifier flags by calling the
getModifiers( ) method. It is shown here:
int getModifiers( )

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:

ItemEvent has this constructor:


ItemEvent(ItemSelectable src, int type, Object entry, int state)
Here, src is a reference to the component that generated this event. For example, this might be a
list or choice element. The type of the event is specified by type. The specific item that generated
the item event is passed in entry. The current state of that item is in state.
The getItem( ) method can be used to obtain a reference to the item that generated an event. Its
signature is shown here:
Object getItem( )
The getItemSelectable( ) method can be used to obtain a reference to the
ItemSelectable object that generated an event. Its general form is shown here: ItemSelectable
getItemSelectable( )

KeyEvent Class
A KeyEvent is generated when keyboard input occurs. There are three types of key events,
which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and
KEY_TYPED.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 9


Object Oriented Programming using JAVA -21CS32
There are many other integer constants that are defined by KeyEvent. For example, VK_0
through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and
letters. Here are some others:

The VK constants specify virtual key codes


KeyEvent is a subclass of InputEvent. Here is one of its constructors:
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
getKeyChar( ), which returns the character that was entered, and getKeyCode( ), which returns
the key code. Their general forms are shown here:
char getKeyChar( )
int getKeyCode( )

The MouseEvent Class


There are eight types of mouse events. The MouseEvent class defines the following integer
constants that can be used to identify them:

MouseEvent is a subclass of InputEvent.


Here is one of its constructors:

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 10


Object Oriented Programming using JAVA -21CS32
MouseEvent(Component src, int type, long when, int modifiers, int
x, int y, int clicks, boolean triggersPopup)
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 mouse event occurred is passed in when. The modifiers
argument indicates which modifiers were pressed when a mouse event occurred. The coordinates
of the mouse are passed in x and y. The click count is passed in clicks. The triggersPopup flag
indicates if this event causes a pop-up menu to appear on this platform.
getX( ) and getY( ): These return the X and Y coordinates of the mouse within the component
when the event occurred. Their forms are shown here:
int getX( ) int getY( )
getPoint( ) method to obtain the coordinates of the mouse.
Point getPoint( )
The translatePoint( ) method changes the location of the event. Its form is shown here:
void translatePoint(int x, int y)
Here, the arguments x and y are added to the coordinates of the event.
The getClickCount( ) method obtains the number of mouse clicks for this event.
Its signature is shown here:
int getClickCount( )
The isPopupTrigger( ) method tests if this event causes a pop-up menu to appear on this
platform. Its form is shown here:
boolean isPopupTrigger( )
getButton( ) method, shown here:
int getButton( )
It returns a value that represents the button that caused the event. The return value will be one
of these constants defined by MouseEvent:

MouseWheelEvent Class
The MouseWheelEvent class encapsulates a mouse wheel event. It is a subclass of
MouseEvent.
MouseWheelEvent defines these two integer constants:

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 11


Object Oriented Programming using JAVA -21CS32

Here is one of the constructors defined by MouseWheelEvent:

MouseWheelEvent(Component src, int type, long when, int


modifiers, int x, int y, int clicks, boolean triggersPopup, int
scrollHow, int amount, int count)
Here, src is a reference to the object that generated the event. The type of the event is specified by
type. The system time at which the mouse event occurred is passed in when. The modifiers
argument indicates which modifiers were pressed when the event occurred.
To obtain the number of rotational units, call getWheelRotation( ), shown here:
int getWheelRotation( )

TextEvent Class
These are generated by text fields and text areas when characters are entered by a user or
program. TextEvent defines the integer constant TEXT_VALUE_CHANGED.
The one constructor for this class is shown here:
TextEvent(Object src, int type)
Here, src is a reference to the object that generated this event. The type of the event is specified by
type.

WindowEvent Class
There are ten types of window events.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 12


Object Oriented Programming using JAVA -21CS32
WindowEvent is a subclass of ComponentEvent.
It defines several constructors.
WindowEvent(Window src, int type)
WindowEvent(Window src, int type, Window other)
WindowEvent(Window src, int type, int fromState, int toState)
WindowEvent(Window src, int type, Window other, int fromState, int
toState)
other specifies the opposite window when a focus or activation event occurs. The fromState
specifies the prior state of the window, and toState specifies the new state that the window will
have when a window state change occurs.

getWindow( ). It returns the Window object that generated the event. Its general form is
shown here:
Window getWindow( )

Sources of Events

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 13


Object Oriented Programming using JAVA -21CS32

Event Listener Interfaces


As explained, the delegation event model has two parts: sources and listeners. Listeners are
created by implementing one or more of the interfaces defined by the java.awt.event
package.

The ActionListener Interface


This interface defines the actionPerformed( ) method that is invoked when an action event
occurs. Its general form is shown here:
void actionPerformed(ActionEvent ae)

ActionListener Interface
This interface defines the actionPerformed( ) method that is invoked when an action event occurs.
Its general form is shown here:

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 14


Object Oriented Programming using JAVA -21CS32
void actionPerformed(ActionEvent ae)
AdjustmentListener Interface
This interface defines the adjustmentValueChanged( ) method that is invoked when an
adjustment event occurs.
Its general form is shown here:
void adjustmentValueChanged(AdjustmentEvent ae)

The ComponentListener Interface

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 ContainerListener Interface
This interface contains two methods. When a component is added to a container,
componentAdded( ) is invoked. When a component is removed from a container,
componentRemoved( ) is invoked.
Their general forms are shown here:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent 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:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
The ItemListener Interface

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 15


Object Oriented Programming using JAVA -21CS32
This interface defines the itemStateChanged( ) method that is invoked when the state of an item
changes.
Its general form is shown here:
void itemStateChanged(ItemEvent ie)

The KeyListener Interface


This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked
when a key is pressed and released, respectively. The keyTyped( ) method is invoked when a
character has been entered.
The general forms of these methods are shown here:
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

The MouseListener Interface


This interface defines five methods.
The general forms of these methods are shown here:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

The MouseMotionListener Interface


This interface defines two methods.
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 16


Object Oriented Programming using JAVA -21CS32
The MouseWheelListener Interface
This interface defines the mouseWheelMoved( ) method that is invoked when the mouse wheel is
moved.
Its general form is shown here:
void mouseWheelMoved(MouseWheelEvent mwe)

The TextListener Interface


This interface defines the textChanged( ) method that is invoked when a change occurs in a text
area or text field.
Its general form is shown here:
void textChanged(TextEvent te)

The WindowFocusListener Interface


This interface defines two methods:
windowGainedFocus( ) and windowLostFocus( ).
These are called when a window gains or loses input focus.
Their general forms are shown here:
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)

The WindowListener Interface This interface defines seven methods


void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 17


Object Oriented Programming using JAVA -21CS32

Using the Delegation Event Model


Now that you have learned the theory behind the delegation event model and have had an overview
of its various components, it is time to see it in practice. Using the delegation event model is
actually quite easy. Just follow these two steps:
1. Implement the appropriate interface in the listener so that it will receive the type of event
desired.
2. Implement code to register and unregister (if necessary) the listener as a recipient for the
event notifications.
Remember that a source may generate several types of events. Each event must be registered
separately. Also, an object may register to receive several types of events, but it must implement
all of the interfaces that are required to receive these events.
To see how the delegation model works in practice, we will look at examples that handle
two commonly used event generators: the mouse and keyboard.

Handling Mouse Events


To handle mouse events, you must implement the MouseListener interfaces.
import java.awt.*;
import java.awt.event.*;
class MEx extends Frame implements MouseListener
{
Label l;
MEx()
{
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 18


Object Oriented Programming using JAVA -21CS32
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
l.setText("Mouse Released");
}
}
public class mouse
{
public static void main(String[] args)
{
new MEx();
}
}

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 19


Object Oriented Programming using JAVA -21CS32
Handling Keyboard Events

import java.awt.*;
import java.awt.event.*;
class KeyListenerExample extends Frame implements KeyListener
{
Label l;
TextArea area;
KeyListenerExample()
{
l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}

public void keyPressed(KeyEvent e)

{
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e)
{
l.setText("Key Released");
}
public void keyTyped(KeyEvent e)
{
l.setText("Key Typed");
}
}
public class keyboard{
public static void main(String[] args)

{
new KeyListenerExample();
}
}

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 20


Object Oriented Programming using JAVA -21CS32

Adapter Classes
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( ), which are the methods defined by the MouseMotionListener interface. If you
were interested in only mouse drag events, then you could simply extend MouseMotionAdapter
and override mouseDragged( ). The empty implementation of mouseMoved( ) would handle the
mouse motion events for you.

Commonly Used Listener Interfaces Implemented by Adapter Classes

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 21


Object Oriented Programming using JAVA -21CS32

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class AdapterDemo extends Applet {


public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
AdapterDemo a;
public MyMouseAdapter(AdapterDemo a) {
this.a = a;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
a.showStatus("Mouse clicked");
}
}

Inner Classes
An inner class is a class defined within another class, or even within an expression.

import java.applet.*;
import java.awt.event.*;

public class Inner extends Applet


{
public void init()
{
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
}
}
}

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 22


Object Oriented Programming using JAVA -21CS32

Swings
Swing contains a set of classes that provides more powerful and flexible GUI components than
those of AWT. Swing provides the look and feel of modern Java GUI. Swing library is an official
Java GUI tool kit released by Sun Microsystems. It is used to create graphical user interface with
Java.
Swing is a set of program component s for Java programmers that provide the ability to create
graphical user interface ( GUI ) components, such as buttons and scroll bars, that are independent
of the windowing system for specific operating system.

The Origins of Swing


 The original Java GUI subsystem was the Abstract Window Toolkit (AWT).
 AWT translates it visual components into platform-specific equivalents (peers).
 Under AWT, the look and feel of a component was defined by the platform.
 AWT components are referred to as heavyweight.
 Swing was introduced in 1997 to fix the problems with AWT.

Swing offers following key features:


1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight

Model-View-Controller
One component architecture is MVC - Model-View-Controller.
The model corresponds to the state information associated with the component. The view
determines how the component is displayed on the screen. The controller determines how the
component responds to the user. Swing uses a modified version of MVC called "Model-Delegate".
In this model the view (look) and controller (feel) are combined into a "delegate".

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 23


Object Oriented Programming using JAVA -21CS32
Because of the Model-Delegate architecture, the look and feel can be changed without affecting
how the component is used in a program.

Components and Containers


A component is an independent visual control: a button, a slider, a label, ...
A container holds a group of components.
In order to display a component, it must be placed in a container.
A container is also a component and can be contained in other containers.
Swing applications create a containment-hierarchy with a single top-level container.

Components
Swing components are derived from the JComponent class.
The only exceptions are the four top-level containers:
JFrame, JApplet, JWindow, and JDialog.
JComponent inherits AWT classes Container and Component.
All the Swing components are represented by classes in the javax.swing package.
All the component classes start with J: JLabel, JButton, JScrollbar, ...

Containers
There are two types of containers:

1. Top-level which do not inherit JComponent, and

2. Lightweight containers that do inherit JComponent.

Lightweight components are often used to organize groups of components.


Containers can contain other containers.
All the component classes start with J: JLabel, JButton, JScrollbar, ...

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 24


Object Oriented Programming using JAVA -21CS32

Two Key Swing Features


1) Swing Components Are Lightweight
 With very few exceptions, Swing components are lightweight.
 They are written entirely in Java and do not map directly to platform-specific
peers.
 Thus, lightweight components are more efficient and more flexible.

2) Swing Supports a Pluggable Look and Feel


 Swing supports a pluggable look and feel (PLAF).
 Because each Swing component is rendered by Java code rather than by
native peers, the look and feel of a component is under the control of Swing.
 This fact means that it is possible to separate the look and feel of a component
from the logic of the component, and this is what Swing does.
 SWING based GUI Application look and feel can be changed at run-time,
based on available values.

The Swing Packages


Swing is a very large subsystem and makes use of many packages. These are the packages used
by Swing that are defined by Java SE 6.
The main package is javax.swing. This package must be imported into any program that uses
Swing. It contains the classes that implement the basic Swing components, such as push buttons,
labels, and check boxes.
Some of the Swing Packages are:

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 25


Object Oriented Programming using JAVA -21CS32
Packages Description
javax.swing Provides a set of "lightweight" (all-Java language) components to
themaximum degree possible, work the same on all platforms.
javax.swing.border Provides classes and interface for drawing specialized borders
around aSwing component.
javax.swi Contains classes and interfaces used by the JcolorChooser
ng.colorchooser component.
javax.swing.event Provides for events fired by Swing components
javax.swing.filechooser Contains classes and interfaces used by the JfileChooser
component.
javax.swing.plaf Provides one interface and many abstract classes that Swing uses
to provideits pluggable look-and-feel capabilities.
javax.swing.plaf.basic Provides user interface objects built according to the Basic look
and feel.
javax.swing.plaf.metal Provides user interface objects built according to the Java look and
feel (once codenamed Metal), which is the default look and feel.
javax.swi ng.plaf.mult Provides user interface objects that combine two or more look and
feels.
javax.swing.table Provides classes and interfaces for dealing with javax.swing.jtable
javax.swing.text Provides classes and interfaces that deal with editable and non
editable textcomponents
javax.swing.text.html Provides the class HTML Editor Kit and supporting classes
for creatingHTML text editors.
javax.swing.text.rtf Provides a class RTF Editor Kit for creating Rich- Text-
Format texteditors.
javax.swing.tree Provides classes and interfaces for dealing with javax.swing.jtree
javax.swing.undo Allows developers to provide support for undo/redo in
applications such astext editors.
There are 2 ways of creating Java Swing Programs
1) Creating Swing Application 2) Creating Swing Applet

A simple Swing Application


By creating the object of Frame class
import javax.swing.*;
public class FirstSwing
{
public static void main(String[] args)

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 26


Object Oriented Programming using JAVA -21CS32
{
JFrame f=new JFrame(" MyApp");
//creating instance of JFrame and title of the frame is MyApp.
JButton b=new JButton("click");
//creating instance of JButton and name of the button is click.
b.setBounds(130,100,100, 40);
//x axis, y axis, width, height
f.add(b);
//adding button in JFrame
f.setSize(400,500);
//400 width and 500 height
f.setLayout(null);
//using no layout managers
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
//making the frame visible
}
}

Explanation:
The program begins by importing javax.swing. As mentioned, this package contains the
components and models defined by Swing.
 For example, javax.swing defines classes that implement labels, buttons, text controls, and
menus. It will be included in all programs that use Swing. Next,
 the program declares the FirstSwing class
 It begins by creating a JFrame, using this line of code:

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 27


Object Oriented Programming using JAVA -21CS32
JFrame f = new JFrame("My App");
This creates a container called f that defines a rectangular window complete with a title bar;
close, minimize, maximize, and restore buttons; and a system menu. Thus, it creates a standard,
top-level window. The title of the window is passed to the constructor.
Next, the window is sized using this statement:
f.setSize(400,500);

 The setSize( ) method (which is inherited by JFrame from the AWT class Component) sets the
dimensions of the window, which are specified in pixels. in this example, the width of the window is
set to 400 and the height is set to 500.
 By default, when a top-level window is closed (such as when the user clicks the close box), the window
is removed from the screen, but the application is not terminated.
 If want the entire application to terminate when its top-level window is closed. There are a couple of
ways to achieve this. The easiest way is to call setDefaultCloseOperation( ), as the program does:
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Swing Applet
A Swing applet extends JApplet rather than Applet. JApplet is derived from Applet. Thus, JApplet
includes all of the functionality found in Applet and adds support for Swing. JApplet is a top-level
Swing container, which means that it is not derived from JComponent. Because JApplet is a
toplevel container, it includes the various panes described earlier. This means thatall components
are added to JApplet’s content pane in the same way that components are added to JFrame’s
content pane.

Example program on Applets along with Event handling (ActionListner)


import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements
ActionListener
{

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 28


Object Oriented Programming using JAVA -21CS32
JButton b;
JTextField tf;
public void init()
{
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);
add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome");
}
}
/*giri.html*/
<html>
<title> Applet Swing</title>
<applet code="EventJApplet.class" width=400 height=400>
</applet> </html>

Jlabel, JTextField and JPassword

JLabel can be used to display text and/or an icon. It is a passive component in that it does not
respond to user input. JLabel defines several constructors. Here are three of them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 29


Object Oriented Programming using JAVA -21CS32
JTextField is the simplest Swing text component. It is also probably its most widely used text
component. JTextField allows you to edit one line of text. It is derived from JTextComponent,
which provides the basic functionality common to Swing text components.
Three of JTextField’s constructors are shown here:
JTextField(int cols)
JTextField(String str, int columns)
JTextField(String str)

Here, str is the string to be initially presented, and cols is the number of columns in the text field.
If no string is specified, the text field is initially empty. If the number of columns is not specified,
the text field is sized to fit the specified string.

JPasswordField is a lightweight component that allows the editing of a single line of text
where the view indicates something was typed, but does not show the original characters.
import javax.swing.*;
public class JTextFieldPgm
{
public static void main(String[] args)
{
JFrame f=new JFrame("My App");
JLabel namelabel= new JLabel("User ID: ");
namelabel.setBounds(10, 20, 70, 10);
JLabel passwordLabel = new JLabel("Password: ");
passwordLabel.setBounds(10, 50, 70, 10);

JTextField userText = new JTextField();


userText.setBounds(80, 20, 100, 20);

JPasswordField passwordText = new JPasswordField();


passwordText.setBounds(80, 50, 100, 20);

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 30


Object Oriented Programming using JAVA -21CS32

f.add(namelabel);
f.add(passwordLabel);

f.add(userText);
f.add(passwordText);

f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
}
}

ImageIcon with JLabel


JLabel can be used to display text and/or an icon. It is a passive component in that it does not
respond to user input. JLabel defines several constructors. Here are three of them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 31


Object Oriented Programming using JAVA -21CS32
Here, str and icon are the text and icon used for the label.

The align argument specifies the horizontal alignment of the text and/or icon within the dimensions
of the label. It must be one of the following values: LEFT, RIGHT, CENTER.
The easiest way to obtain an icon is to use the ImageIcon class. ImageIcon implements Icon and
encapsulates an image.
Thus, an object of type ImageIcon can be passed as an argument to the Icon parameter of JLabel’s
constructor.
ImageIcon(String filename)

Example program to load image


import javax.swing.*;
import java.awt.*;
public class Image1 extends JFrame
{
public static void main(String[] args)
{
JFrame jf=new JFrame("Image Icon");
jf.setLayout(null);
Icon icon = new ImageIcon("GK.JPG");
Label label1= new JLabel("AIML ",icon,JLabel.CENTER);

label1.setBounds(200, 200, 600, 600);


jf.add(label1);
jf.setSize(600,600);
jf.setVisible(true);
}
}

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 32


Object Oriented Programming using JAVA -21CS32

The Swing Buttons


There are four types of Swing Button
1. JButton
2. JRadioButton
3. JCheckBox
4. JComboBox
JButton class provides functionality of a button. A JButton is the Swing equivalent of a Button in
AWT. It is used to provide an interface equivalent of a common button.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 33


Object Oriented Programming using JAVA -21CS32
JButton class has three constuctors,
JButton(Icon ic)
JButton(String str)
JButton(String str, Icon ic)

Example program to Create Button


import javax.swing.*;
class SwingButton
{
public static void main(String args[])
{
JFrame jf=new JFrame("My Swing App");
JButton jb=new JButton("Next");
jb.setBounds(30, 100, 100, 50);

JButton jb1=new JButton("Prev");


jb1.setBounds(30, 200, 100, 50);
jf.add(jb);
jf.add(jb1);

jf.setSize(300, 600);

jf.setLayout(null);

jf.setVisible(true);
}
}

JRadioButton

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 34


Object Oriented Programming using JAVA -21CS32
A JRadioButton is the swing equivalent of a RadioButton in AWT. It is used to represent multiple option
single selection elements in a form. This is performed by grouping the JRadio buttons using a ButtonGroup
component. The ButtonGroup class can be used to group multiple buttons so that at a time only one button
can be selected.

Example program to Create JRadioButton


import javax.swing.*;
import javax.swing.*;
public class RadioButton1
{
public static void main(String args[])
{
JFrame f=new JFrame("MyAppRadio");
JRadioButton r1=new JRadioButton("Male ");
JRadioButton r2=new JRadioButton("Female");
r1.setBounds(50, 100, 70, 30);
r2.setBounds(50,150,70,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
f.add(r1); f.add(r2);
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
}
}

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 35


Object Oriented Programming using JAVA -21CS32

JCheckBox
A JCheckBox is the Swing equivalent of the Checkbox component in AWT. This is sometimes
called a ticker box, and is used to represent multiple option selections in a form.

Example program to Create JCheckBox


import javax.swing.*;
class JCheck
{
public static void main(String args[])
{
JFrame jf=new JFrame("CheckBox");
JCheckBox jb=new JCheckBox("JAVA");
jb.setBounds(30, 100, 100, 50);
JCheckBox jb1=new JCheckBox("Python");
jb1.setBounds(30, 200, 100, 50);
jf.add(jb);
jf.add(jb1);
jf.setSize(300, 600);
jf.setLayout(null);
jf.setVisible(true);
}
}

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 36


Object Oriented Programming using JAVA -21CS32

JComboBox
The JComboBox class is used to create the combobox (drop-down list). At a time only one item
can be selected from the item list.

Example program to Create JComboBox


import java.awt.*;
import javax.swing.*;
public class JCombo
{
public static void main(String[] args)
{
JFrame f=new JFrame("Combo demo");
String Branch[]={"AIML","CSE","AI","DS"};
JComboBox jc=new JComboBox(Branch);
jc.setBounds(50,50,80,50);
f.add(jc);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
}

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 37


Object Oriented Programming using JAVA -21CS32

JTable and JScrollPane:


The JTable class is used to display the data on two dimensional tables of cells.
Commonly used Constructors of JTable class:
JTable(): creates a table with empty cells.
JTable(Object[ ][ ] rows, Object[ ] columns): creates a table with the
specified data.
JScrollPane is a lightweight container that automatically handles the scrolling of another
component.The component being scrolled can either be an individual component, such as a table,
or a group of components contained within another lightweight container, such as a JPanel.
In its default behavior, a JScrollPane will dynamically add or remove a scroll bar as needed. For
example, if the component is taller than the viewport, a vertical scroll bar is added. If the
component will completely fit within the viewport, the scroll bars are removed.

Example program to Create JTable


import javax.swing.*;
public class JTableEx
{
public static void main(String[] args)
{
JFrame f=new JFrame("Table Demo");
String data[][]={
{"100","AIML","VTU"}, {"101","ISE","VTU"}, {"102","CSE","VTU"},
{"103","ISE","VTU"}, {"105","AIML","VTU"}, {"106","ISE","VTU"}
};
String column[]={"courseID","Branch","University"};
JTable jt=new JTable(data,column);
JScrollPane js=new JScrollPane(jt);
js.setBounds(30,100,300,100);
f.add(js);
f.setSize(300,400);

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 38


Object Oriented Programming using JAVA -21CS32
f.setLayout(null);
f.setVisible(true);
}
}

JTabbedpane
JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking them with
tabs. Selecting a tab causes the component associated with that tab to come to the forefront. Tabbed
panes are very common in the modern GUI.
Given the complex nature of a tabbed pane, they are surprisingly easy to create and use.
JTabbedPane defines three constructors.
We will use its default constructor, which creates an empty control with the tabs positioned across
the top of the pane.
The other two constructors let you specify the location of the tabs, which can be along any of the
four sides. JTabbedPane uses the SingleSelectionModel model. Tabs are added by calling
addTab( ) method. Here is one of its forms:

void addTab(String name, Component comp)

Here, name is the name for the tab, and comp is the component that should be added to the tab.
Often, the component added to a tab is a JPanel that contains a group of related components. This
technique allows a tab to hold a set of components.

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 39


Object Oriented Programming using JAVA -21CS32

Example program to Create JTabbedpane


import javax.swing.*;
public class JTabPane
{
public static void main(String[] a)
{
JFrame f = new JFrame("JTab");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JTabbedPaneDemo());
f.setSize(500, 500);
f.setVisible(true);
}
}

class JTabbedPaneDemo extends JPanel


{
JTabbedPaneDemo()
{
makeGUI();
}
void makeGUI()
{
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
add(jtp);
}
}

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 40


Object Oriented Programming using JAVA -21CS32
class CitiesPanel extends JPanel
{
public CitiesPanel()
{
JButton b1 = new JButton("Ballari"); add(b1);
JButton b2 = new JButton("Belagavi"); add(b2);
JButton b3 = new JButton("Bengaluru"); add(b3);
JButton b4 = new JButton("Mysuru"); add(b4);
}
}
class ColorsPanel extends JPanel
{
public ColorsPanel()
{
JCheckBox cb1 = new JCheckBox("Red"); add(cb1);
JCheckBox cb2 = new JCheckBox("Green"); add(cb2);
JCheckBox cb3 = new JCheckBox("Blue"); add(cb3);
}
}
class FlavorsPanel extends JPanel
{
public FlavorsPanel()
{
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 41


Object Oriented Programming using JAVA -21CS32

JList
In Swing, the basic list class is called JList.
It supports the selection of one or more items from a list. Although the list often consists of strings,
it is possible to create a list of just about any object that can be displayed.
JList is so widely used in Java that it is highly unlikely that you have not seen one before.
JList provides several constructors. The one used here is
JList(Object[ ] items)
This creates a JList that contains the items in the array specified by items.

JList is based on two models. The first is ListModel. This interface defines how access to the list
data is achieved.
The second model is the ListSelectionModel interface, which defines methods that determine what
list item or items are selected.

Example program to Create JList


import java.awt.*;
import javax.swing.*;
public class JList

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 42


Object Oriented Programming using JAVA -21CS32
{
public static void main(String[] args)
{
JFrame jf = new JFrame("JList");
String[] selections = { "green", "red", "orange", "dark blue" };
JList list = new JList(selections);
list.setSelectedIndex(1);
jf.add(new JScrollPane(list));
jf.setSize(300, 400);

jf.setLayout(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}

******************************End of Module-4********************************

Dr. GIRISH KUMAR, Assoc. Prof., Dept. of AIML, BITM Page 43

You might also like