Swing Event Handling
Swing Event Handling
Swing Event Handling
Swing API is a set of extensible GUI Components to ease the developer's life to
create JAVA based Front End/GUI Applications. It is build on top of AWT API and
acts as a replacement of AWT API, since it has almost every control corresponding
to AWT controls. Swing component follows a Model-View-Controller architecture to
fulfill the following criterias.
A single API is to be sufficient to support multiple look and feel.
API is to be model driven so that the highest level API is not required to have
data.
API is to use the Java Bean model so that Builder Tools and IDE can provide
better services to the developers for use.
MVC Architecture
Swing API architecture follows loosely based MVC architecture in the following
manner.
Model represents component's data.
View represents visual representation of the component's data.
Controller takes the input from the user on the view and reflects the changes
in Component's data.
Swing component has Model as a seperate element, while the View and
Controller part are clubbed in the User Interface elements. Because of which,
Swing has a pluggable look-and-feel architecture.
Swing Features
Light Weight − Swing components are independent of native Operating
System's API as Swing API controls are rendered mostly using pure JAVA
code instead of underlying operating system calls.
Rich Controls − Swing provides a rich set of advanced controls like Tree,
TabbedPane, slider, colorpicker, and table controls.
Highly Customizable − Swing controls can be customized in a very easy way
as visual apperance is independent of internal representation.
Pluggable look-and-feel − SWING based GUI Application look and feel can
be changed at run-time, based on available values.
SWING - Event Handling
What is an Event?
Change in the state of an object is known as Event, i.e., event describes the change
in the state of the source. Events are generated as a result of user interaction with
the graphical user interface components. For example, clicking on a button, moving
the mouse, entering a character through keyboard, selecting an item from the list,
and scrolling the page are the activities that causes an event to occur.
Types of Event
The events can be broadly classified into two categories −
Foreground Events − These events require direct interaction of the user.
They are generated as consequences of a person interacting with the
graphical components in the Graphical User Interface. For example, clicking
on a button, moving the mouse, entering a character through keyboard,
selecting an item from list, scrolling the page, etc.
Background Events − These events require the interaction of the end user.
Operating system interrupts, hardware or software failure, timer expiration,
and operation completion are some examples of background events.
Callback Methods
These are the methods that are provided by API provider and are defined by the
application programmer and invoked by the application developer. Here the callback
methods represent an event method. In response to an event, java jre will fire
callback method. All such callback methods are provided in listener interfaces.
If a component wants some listener to listen ot its events, the source must register
itself to the listener.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showEventDemo(){
headerLabel.setText("Control in action: Button");
okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
Layout Manager
The layout manager automatically positions all the components within the container.
Even if you do not use the layout manager, the components are still positioned by
the default layout manager. It is possible to lay out the controls by hand, however, it
becomes very difficult because of the following two reasons.
It is very tedious to handle a large number of controls within the container.
Usually, the width and height information of a component is not given when we
need to arrange them.
Java provides various layout managers to position the controls. Properties like size,
shape, and arrangement varies from one layout manager to the other. When the size
of the applet or the application window changes, the size, shape, and arrangement
of the components also changes in response, i.e. the layout managers adapt to the
dimensions of the appletviewer or the application window.
The layout manager is associated with every Container object. Each layout manager
is an object of the class that implements the LayoutManager interface.
Following are the interfaces defining the functionalities of Layout Managers.
LayoutManager
1 The LayoutManager interface declares those methods which need to be implemented by the class, w
object will act as a layout manager.
LayoutManager2
2 The LayoutManager2 is the sub-interface of the LayoutManager. This interface is for those classes
know how to layout containers based on layout constraint object.
AWT Layout Manager Classes
Following is the list of commonly used controls while designing GUI using AWT.
BorderLayout
1 The borderlayout arranges the components to fit in the five regions: east, west, north, south, and
center.
CardLayout
2 The CardLayout object treats each component in the container as a card. Only one card is
visible at a time.
FlowLayout
3
The FlowLayout is the default layout. It layout the components in a directional flow.
GridLayout
4
The GridLayout manages the components in the form of a rectangular grid.
GridBagLayout
This is the most flexible layout manager class. The object of GridBagLayout aligns the
5
component vertically, horizontally, or along their baseline without requiring the components
of the same size.
GroupLayout
6 The GroupLayout hierarchically groups the components in order to position them in a
Container.
SpringLayout
7 A SpringLayout positions the children of its associated container according to a set of
constraints.
SWING - Event Classes
Event classes represent the event. Java provides various Event classes, however,
only those which are more frequently used will be discussed.
EventObject Class
It is the root class from which all event state objects shall be derived. All Events are
constructed with a reference to the object, the source, that is logically deemed to be
the object upon which the Event in question initially occurred upon. This class is
defined in java.util package.
Class Declaration
Following is the declaration for java.util.EventObject class −
public class EventObject
extends Object
implements Serializable
Field
Following are the fields for java.util.EventObject class −
protected Object source − The object on which the Event initially occurred.
Class Constructors
EventObject(Object source)
1
Constructs a prototypical Event.
Class Methods
Object getSource()
1
The object on which the Event initially occurred.
String toString()
2
Returns a String representation of this EventObject.
Methods Inherited
This class inherits methods from the following class −
java.lang.Object
AWTEvent
1 It is the root event class for all SWING events. This class and its subclasses supercede
original java.awt.Event class.
ActionEvent
2
The ActionEvent is generated when the button is clicked or the item of a list is double-clicked.
InputEvent
3
The InputEvent class is the root event class for all component-level input events.
KeyEvent
4
On entering the character the Key event is generated.
MouseEvent
5
This event indicates a mouse action occurred in a component.
WindowEvent
6
The object of this class represents the change in the state of a window.
AdjustmentEvent
7
The object of this class represents the adjustment event emitted by Adjustable objects.
ComponentEvent
8
The object of this class represents the change in the state of a window.
ContainerEvent
9
The object of this class represents the change in the state of a window.
MouseMotionEvent
1
0 The object of this class represents the change in the state of a window.
PaintEvent
1
1 The object of this class represents the change in the state of a window.
Event listeners represent the interfaces responsible to handle events. Java provides
various Event listener classes, however, only those which are more frequently used
will be discussed. 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
ActionListener
1
This interface is used for receiving the action events.
2 ComponentListener
This interface is used for receiving the component events.
ItemListener
3
This interface is used for receiving the item events.
KeyListener
4
This interface is used for receiving the key events.
MouseListener
5
This interface is used for receiving the mouse events.
WindowListener
6
This interface is used for receiving the window events.
AdjustmentListener
7
This interface is used for receiving the adjustment events.
ContainerListener
8
This interface is used for receiving the container events.
MouseMotionListener
9
This interface is used for receiving the mouse motion events.
FocusListener
10
This interface is used for receiving the focus events.
Adapters are abstract classes for receiving various events. The methods in these
classes are empty. These classes exist as convenience for creating listener objects.
SWING Adapters
Following is the list of commonly used adapters while listening GUI events in
SWING.
Sr.No. Adapter & Description
FocusAdapter
1
An abstract adapter class for receiving focus events.
KeyAdapter
2
An abstract adapter class for receiving key events.
MouseAdapter
3
An abstract adapter class for receiving mouse events.
MouseMotionAdapter
4
An abstract adapter class for receiving mouse motion events.
WindowAdapter
5
An abstract adapter class for receiving window events.
SWING - Containers
Containers are an integral part of SWING GUI components. A container provides a
space where a component can be located. A Container in AWT is a component itself
and it provides the capability to add a component to itself. Following are certain
noticable points to be considered.
Sub classes of Container are called as Container. For example, JPanel,
JFrame and JWindow.
Container can add only a Component to itself.
A default layout is present in each container which can be overridden
using setLayout method.
SWING Containers
Following is the list of commonly used containers while designed GUI using SWING.
Panel
1 JPanel is the simplest container. It provides space in which any other component can be placed, inclu
other panels.
Frame
2
A JFrame is a top-level window with a title and a border.
Window
3
A JWindow object is a top-level window with no borders and no menubar.