JAVA SWINGS
INTRODUCTION
In earlier days of Java AWT classes were used to create Graphical User
Interface(GUI’s).
Now no longer AWT Classes are used to develop GUI.
Today, most programmers use Swing for this purpose because “Swing
is a set of classes that provides more powerful and
flexible GUI components than does the AWT”
Earlier to swing, Java programmer uses AWT classes to develop GUI’s but
AWT classes contains limited graphical interface.
This is one of reason that programmer wants to develop different
component, that has more flexible and rich in graphical interface.
Because of the limited graphical interface AWT translate its various visual
components into their corresponding, platform-specific equivalents, or
peers. That means look and feel of the component is decided by platform,
not by JAVA.
Because the AWT components use native code resources, they are referred
to as heavyweight.
Contd…
The usage of native resources of platform led to following problems
1) Because of variations between operating systems, a component might
look, or even act, differently on different platforms which also
threaten the philosophy of java “write once, run anywhere”.
2) Second, the look and feel of each component was fixed and could not
be (easily) changed.
3) The use of heavyweight components caused some frustrating
restrictions.
This Restriction and limitation of AWT classes create serious
issues for programmer so SWINGS came into picture.
Introduced in 1997, Swing was included as part of the Java
Foundation Classes (JFC).
Java Swing component is completely incorporated in JDK 1.2.
SWING is Bulit on AWT
There is one important point to be remembered that
Although SWING eliminates number of limitations of AWT
classes, but SWING doesn't replace it.
Swing is built on the foundation of the AWT.
Two Key Features of SWING
1) Swing component are lightweight component.
2) Swing Support pluggable look and feel.
Swing components are lightweight components: In
Swing, components like buttons, text fields, panels, etc.,
are considered lightweight because they are drawn by Java
code rather than relying on the operating system's native
widgets. This approach makes Swing components more
portable across different platforms and allows for greater
control over their appearance and behavior.
Swing supports pluggable look and feel: Swing
provides a mechanism called "pluggable look and feel"
(PLAF) that allows developers to change the appearance of
their Swing applications dynamically. This means you can
change the overall look and feel of your application without
modifying its code by simply switching between different
look and feel themes provided by Swing or by creating
custom ones.
MVC Connection
In general, a visual component is a composite of three distinct aspects:
• The way that the component looks when rendered on the screen
• The way that the component reacts to the user
• The state information associated with the component
the model corresponds to the state information associated with the
component. For example, in the case of a check box, the model
contains a field that indicates if the box is checked or unchecked.
The view determines how the component is displayed on the screen,
including any aspects of the view that are affected by the current state
of the model.
The controller determines how the component reacts to the user. For
example, when the user clicks a check box, the controller reacts by
changing the model to reflect the user’s choice (checked or unchecked).
However MVC architecture is Conceptually good and sound. But there
is high level of separation between view and controller which is not
beneficial for SWINGS.
Contd..
Hence swing uses a modified version of MVC that combines the view
and the controller into a single logical entity.
For this reason, Swing’s approach is called either the Model-Delegate
architecture or the Separable Model architecture.
Swing’s pluggable look and feel is made possible by its Model-
Delegate architecture.
Because the view (look) and controller (feel) are separate from the
model, the look and feel can be changed without affecting how the
component is used within a program.
Conversely, it is possible to customize the model without affecting the
way that the component appears on the screen or responds to user
input.
To support the Model-Delegate architecture, most Swing components
contain two objects.
1) model
2) UI Delegate
Class Hierarchy of Swing
A Swing GUI consists of two key items: components and containers.
Component and Container
Component is an independent visual control,
such as a push button or slider.
A container holds a group of components
Thus, a container is a special type of
component that is designed to hold other
components.
Furthermore, in order for a component to be
displayed, it must be held within a container.
Thus, all Swing GUIs will have at least one
container.
Container can also hold another container.
Components
In general, Swing components are derived from
the JComponent class.
JComponent provides the functionality that is
common to all components. For example,
JComponent supports for the pluggable look
and feel.
JComponent inherits the AWT classes Container
and Component.
All Swing components are present in the
package
Javax.swing
JComponents
Container
Swing defines two types of containers.
The first are top-level containers: JFrame, JApplet, JWindow,
and JDialog.
The second type of containers supported by Swing are
lightweight containers.
Top-level containers are heavyweight containers.
Top-level containers do not inherit JComponent.
Lightweight containers do inherit JComponent.
An example of a lightweight container is JPanel, which is a
general-purpose container.
The Top-Level Container Panes
Each top-level container defines a set of panes.
At the top of the hierarchy is an instance of JRootPane.
JRootPane is a lightweight container whose purpose is to manage the
other panes.
The panes that comprise the root pane are called the glass pane, the
content pane, and the layered pane.
The glass pane is the top-level pane. It sits above and completely
covers all other panes.
The glass pane enables you to manage mouse events that affect the
entire container (rather than an individual control) or to paint over any
other component.
The layered pane is an instance of JLayeredPane.
The layered pane allows components to be given a
depth value.
This value determines which component overlays
another.
Top level Panes
SWING Packages
These are the packages used by Swing that
are defined by Java SE 6.
The main package is javax.swing.
A Simple Swing Application
Swing programs differ from both the console-based programs and the AWT-
based programs.
In the following program we are using two swing component:JFrame and
JLabel.
JFrame is the top-level container that is commonly used for Swing
applications.
JLabel is the Swing component that creates a label, which is a component that
displays information.
A simple Swing application.
import javax.swing.*;
class SwingDemo {
SwingDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("A Simple Swing Application");
// Give the frame an initial size.
jfrm.setSize(275, 100);
// Terminate the program when the user closes the
application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a text-based label.
JLabel jlab = new JLabel(" Swing means powerful GUIs.");
// Add the label to the content pane.
jfrm.add(jlab);
// Display the frame.
jfrm.setVisible(true);
}
public static void main(String[] args) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SwingDemo();
}
});
•javax.swing defines classes that implement labels, buttons, text
controls, and menus. It will be included in all programs that use
Swing.
•This creates a container called jfrm 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.
•The setSize( ) method (which is inherited by JFrame from the
AWT class Component) sets the dimensions of the window,
which are specified in pixels. Its general form is shown here:
void setSize(int width, int height)
•After this call executes, closing the window causes the entire
application to terminate. The general form of
setDefaultCloseOperation( ) is shown here: void
setDefaultCloseOperation(int what)
•The value passed in what determines what happens when the
window is closed. There are several other options in addition to
JFrame.EXIT_ON_CLOSE. They are shown here:
DISPOSE_ON_CLOSE HIDE_ON_CLOSE
DO_NOTHING_ON_CLOSE
•JLabel is the simplest and easiest-to-use component because it
Event Handling in Swings
When swing component do respond to user input and the events
are generated by those interactions.
An event need to b handled by using event handlers.
The event handling mechanism used by Swing is the same as that
used by the AWT.
In many cases, Swing uses the same events as does the AWT, and
these events are packaged in java.awt.event.
Events specific to Swing are stored in javax.swing.event.
Consider the example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventDemo {
JLabel jlab;
EventDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("An Event
Example");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(new FlowLayout());
// Give the frame an initial size.
Whenjfrm.setSize(220, 90); it generates an ActionEvent.
a push button is pressed,
Thus, JButton provides
the addActionListener( ) method, which is used to add an
action listener.
As explained in Chapter 25, the ActionListener interface
defines only one method: actionPerformed( ).
jbtnBeta. The ActionListener interface listens for
action events, such as button clicks.
addActionListener is a method of the JButton class
that takes an ActionListener as a parameter.
Here, an anonymous inner class is created that
implements the ActionListener interface. The
ActionListener interface requires the implementation
of the actionPerformed method, which will be called
whenever an action event (like a button click) occurs.
The parameter ae is an instance of ActionEvent,
which provides information about the event.
An anonymous inner class in Java is a type of inner
class that is declared and instantiated in a single
expression, typically used when you need to override
or extend a class or interface for a short period of
time, often within a method. These classes do not
have a name and are used primarily for concise
LAYOUT MANAGER
In Java, layout managers are used to define
the layout of components within a container,
such as a JFrame, JPanel, or any other
container class. They help in arranging the
components in a visually pleasing and
organized manner, taking into account factors
like resizing, platform differences
FlowLayout: Components are arranged in a
left-to-right flow, wrapping to the next line if
necessary.
BorderLayout: Components are arranged in
the five regions: North, South, East, West, and
Center.
GridLayout: Components are arranged in a
Painting in Swing
Although the Swing component set is quite powerful, you are not limited to
using it because Swing also lets you write directly into the display area of a
frame, panel, or one of Swing’s other components, such as JLabel.
To write output directly to the surface of a component, you will use one or
more drawing methods defined by the AWT, such as drawLine( ) or
drawRect( ).
The AWT class Component defines a method called paint( ) that is used to
draw output directly to the surface of a component.
In most of the time paint( ) method is not directly called by your program.
Rather, paint( ) is called by the run-time system.
Because JComponent inherits Component, all Swing’s lightweight
components inherit the paint( ) method.
Swing uses a bit more sophisticated approach to painting that involves three
distinct methods: paintComponent( ), paintBorder( ), and paintChildren( ).
The paintComponent( ) method is shown here:
protected void paintComponent(Graphics g)
The parameter g is the graphics context to which output is written.
Compute the Paintable Area
When drawing to the surface of a component, you must be careful to restrict
your output to the area that is inside the border.
Although Swing automatically clips any output that will exceed the
boundaries of a component.
To obtain the border width, call getInsets( ), shown here:
Insets getInsets( )
This method is defined by Container and overridden by JComponent.
The inset values can be obtained by using these fields:
int top;
int bottom;
int left;
int right;
These values are then used to compute the drawing area given the width and
the height of the component.
You can obtain the width and height of the component by calling getWidth( )
and getHeight( ) on the component.
Exploring Swing
Here in this topic we are going to discuss about Swing components that
provide rich functionality and allow a high level of customization.
Ex: buttons, check boxes, trees, and tables
These components are all lightweight, which means that they are all derived
from JComponent.
JLabel and ImageIcon
JLabel is Swing’s easiest-to-use component. It creates a label.
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.
The Following are three forms of Jlabel (Constructor) .
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
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, LEADING, or TRAILING.
One of the easiest way to obtain an icon is to use the ImageIcon class.
ImageIcon implements Icon and encapsulates an image. General Form is
ImageIcon(String filename)
Contd
Filename is the name of the image if it is present in same folder, otherwise you
should add URL.
The icon and text associated with the label can be obtained by the following
methods:
void setIcon(Icon icon): To set the icon associated with label.
void setText(String str): To set the text associated with label.
Icon getIcon( ) : To obtain already set icon associated with label.
String getText( ): To obtain already set text associated with label.
Consider the example
JTextField
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.
Three of JTextField’s constructors are shown here:
JTextField(int cols)
JTextField(String str, int cols)
JtextField(String str)
Here, str is the string to be initially presented, and cols is the number of
columns in the text field.
If the number of columns is not specified, the text field is sized to fit the
specified string.
JTextField generates events in response to user interaction. For example,
an ActionEvent is fired when the user presses ENTER.
To obtain the current text use getText( ).
PROGRAMMING EXAMPLE.
The Swing Buttons
Swing defines four types of buttons: JButton, JToggleButton, JCheckBox,
and JRadioButton.
All are subclasses of the AbstractButton class, which extends JComponent.
AbstractButton contains many methods that allow you to control the
behavior of buttons.
For example, you can define different icons that are displayed for the button
when it is disabled, pressed, or selected.
void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)
Here, di, pi, si, and ri are the icons to be used for the indicated purpose.
The text associated with a button can be read and written via the following
methods:
String getText( ): Read
void setText(String str): Written
Contd..
JButton
The JButton class provides the functionality of a push button.
JButton allows an icon, a string, or both to be associated with the push button.
Three of its constructors are shown here:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the button.
When the button is pressed, an ActionEvent is generated. Using the
ActionEvent object passed to the actionPerformed( ) method of the
registered ActionListener, you can obtain the action command string
associated with the button.
In the preceding chapter, you saw an example of a text-based button. The
following demonstrates an icon-based button. It displays four push buttons and
a label. Each button displays an icon that represents the flag of a country.
getActionCommand( ): This method is used to display the result of
action taken when an event is generated.
JToggleButton
A useful variation on the push button is called a toggle button.
A toggle button looks just like a push button, but it acts differently because it has two
states: pushed and released.
When you press toggle button first time, it stays pressed(pushed). When you press the
button second time, it will be released(pops up).
Toggle buttons are objects of the JToggleButton class. JToggleButton implements
AbstractButton.
JToggleButton defines several constructors. The one used by the example in this
section is shown here:
JToggleButton(String str)
This creates a toggle button that contains the text passed in str.
Like JButton, JToggleButton generates an action event each time it is
pressed.
however, JToggleButton also generates an item event.
To handle item events, you must implement the ItemListener interface.
Easiest way to determine the state of the button is by using this method:
isSelected( );
It returns the Boolean value : true or false
Check Boxes
The JCheckBox class provides the functionality of a check box.
which provides support for two-state buttons.
JCheckBox defines several constructors. The one used here is
JCheckBox(String str);
It creates a check box that has the text specified by str as a label.
When the user selects or deselects a check box, an ItemEvent is generated.
ItemEvent passed to the itemStateChanged( ) method defined by ItemListener.
The easiest way to determine the selected state of a check box is to call
isSelected( ) method.
In addition to supporting the normal check box operation, JCheckBox lets
you specify the icons that indicate when a check box is selected, cleared, and
rolled-over.
Radio Buttons
Radio buttons are a group of mutually exclusive buttons, in which only one
button can be selected at any one time.
They are supported by the JRadioButton class, which extends
JToggleButton. JRadioButton provides several constructors.
JRadioButton(String str)
Here, str is the label for the button.
Only one of the buttons in the group can be selected at any time.
For example, if a user presses a radio button that is in a group, any previously
selected button in that group is automatically deselected.
A JRadioButton generates action events, item events, and change events
each time the button selection changes.
Most often, it is the action event that is handled, which means that you will
normally implement the ActionListener interface.
Inside this method, you can use a number of different ways to determine
which button was selected.
getActionCommand( ): This method is used to display the result of
action taken when an event is generated.
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.
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.
Tabs are added by calling addTab( ). 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.
The general procedure to use a tabbed pane is outlined here:
1.Create an instance of JTabbedPane.
2. Add each tab by calling addTab( ).
3. Add the tabbed pane to the content pane.
JScrollPane
JScrollPane is a lightweight container that automatically handles the scrolling
of another component.
If the object being scrolled is larger than the viewable area, horizontal and/or
vertical scroll bars are automatically provided, and the component can be
scrolled through the pane.
Because JScrollPane automates scrolling, it usually eliminates the need to
manage individual scroll bars.
The viewable area of a scroll pane is called the viewport. It is a window in
which the component being scrolled is displayed.
Thus, the viewport displays the visible portion of the component being
scrolled.
The scroll bars scroll the component through the viewport. 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.
Contd..
JScrollPane defines several constructors. The one used in this chapter is
shown here:
JScrollPane(Component comp)
The component to be scrolled is specified by comp.
Here are the steps to follow to use a scroll pane:
1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.
3. Add the scroll pane to the content pane.
Consider the example of JScrollPane, where first panel is created by using
Jpanel.
400 buttons are added to It, arranged into 20 columns.
JList
In Swing, the basic list class is called JList. It supports the selection of one
or more items from a list.
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 ------- The second model is the ListSelectionModel
interface.
This defines how to access list of data This determine what list item
is selected
Although a JList will work properly by itself, most of the time you will
wrap a Jlist inside a JScrollPane.
Contd…
A JList generates a ListSelectionEvent when the user makes or changes a selection.
This event is also generated when the user deselects an item.
It is handled by implementing ListSelectionListener.
This listener specifies only one method, called valueChanged( ), which is shown here:
void valueChanged(ListSelectionEvent le)
Here, le is a reference to the object that generated the event.
Both ListSelectionEvent and ListSelectionListener are packaged in
javax.swing.event.
By default, a JList allows the user to select multiple ranges of items within the list,
but you can change this behavior by calling setSelectionMode( ).
This method is defined by JList. It is shown here:
void setSelectionMode(int mode)
Here, mode specifies the selection mode. It must be one of these values defined by
ListSelectionModel:
1) SINGLE_SELECTION
2) SINGLE_INTERVAL_SELECTION
3) MULTIPLE_INTERVAL_SELECTION
Contd…
The default, multiple-interval selection, lets the user select multiple ranges of
items within a list.
With single selection, the user can select only a single item.
With single-interval selection, the user can select one range of items
You can obtain the index of the first item selected using the method
getSelectedIndex( ).
int getSelectedIndex( );
Indexing begins at zero. So, if the first item is selected, this method will return
0. If no item is selected, –1 is returned.
Instead of obtaining the index of a selection, you can obtain the value
associated with the selection by calling getSelectedValue( ):
Object getSelectedValue( )
It returns a reference to the first selected value. If no value has been selected, it
returns null.
JComboBox
Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class.
A combo box normally displays one entry, but it will also display a drop-down list
that allows a user to select a different entry.
The JComboBox constructor used by the example is shown
here:
JComboBox(Object[ ] items)
Here, items is an array that initializes the combo box.
JComboBox uses the ComboBoxModel. Mutable combo boxes (those whose
entries can be changed) use the MutableComboBoxModel.
Items can be dynamically added to the list of choices via the addItem( ) method
void addItem(Object obj)
Here, obj is the object to be added to the combo box.
JComboBox generates an action event when the user selects an item from the list.
JComboBox also generates an item event when the state of selection changes,
which occurs when an item is selected or deselected.
Here two events will occur, one for selected item, another for deselected item.
One way to obtain the item selected in the list is to call getSelectedItem( ) on
the combo box.
Object getSelectedItem( )
JTree
A tree is a component that presents a hierarchical view of data. The user has
the ability to expand or collapse individual subtrees in this display.
Trees are implemented in Swing by the JTree class. A sampling of its
constructors is shown here:
JTree(Object obj[ ])
JTree(Vector<?> v)
JTree(TreeNode tn)
In the first form, the tree is constructed from the elements in the array obj. The
second form constructs the tree from the elements of vector v. In the third
form, the tree whose root node is specified by tn specifies the tree.
Although JTree is packaged in javax.swing
JTree relies on two models: TreeModel and TreeSelectionModel.
3 Events are generated by JTreecomponent 1) TreeExpansionEvent
2) TreeSelectionEvent
3) TreeModelEvent.
Contd….
TreeExpansionEvent events occur when a node is expanded or collapsed.
A TreeSelectionEvent is generated when the user selects or deselects a node
within the tree.
ATreeModelEvent is fired when the data or structure of the tree changes.
The listeners for these events are TreeExpansionListener,
TreeSelectionListener, and TreeModelListener, respectively.
The tree event classes and listener interfaces are packaged in
javax.swing.event.
In the example shown, we are using TreeSelectionEvent and the listener for
this event is TreeSelectionListener.
It defines only one method, called valueChanged( ), which receives the
TreeSelectionEvent object.
You can obtain the path to the selected object by calling getPath( )
TreePath getPath( ): This returns a TreePath object that describes the
path to the changed node.
The MutableTreeNode interface extends TreeNode
Contd…
It declares methods that can insert and remove child nodes or change the parent
node.
One of its constructors is shown here:
DefaultMutableTreeNode(Object obj)
Here, obj is the object to be enclosed in this tree node. The new tree node doesn’t
have a parent or children.
To add the child nodes to tree we have add( ) method.
void add(MutableTreeNode child)
Here, child is a mutable tree node that is to be added as a child to the current node.
JTree does not provide any scrolling capabilities of its own. So, a JTree is
typically placed within a JScrollPane.
Here are the steps to follow to use a tree:
1. Create an instance of JTree.
2. Create a JScrollPane and specify the tree as the object to be scrolled.
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane.
JTable
JTable is a component that displays rows and columns of data.
You can drag the cursor on column boundaries to resize columns.
Depending on its configuration, it is also possible to select a row, column, or
cell within the table, and to change the data within a cell.
JTable is a sophisticated component that offers many more options and
features than can be discussed here.
JTable is easy to use—especially if you simply want to use the table to
present data in a tabular format.
Like JTree, JTable has many classes and interfaces associated with it. These
are packaged in javax.swing.table.
JTable is conceptually simple. It is a component that consists of one or
more columns of information.
At the top of each column is a heading.
In addition to describing the data in a column, the heading also provides the
mechanism by which the user can change the size of a column or change the
location of a column within the table.
Contd…
JTable does not provide any scrolling capabilities of its own. Instead, you will
normally wrap a Jtable inside a JScrollPane.
JTable supplies several constructors. The one used here is
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be presented, and
colHeads is a one-dimensional array with the column headings.
JTable relies on three models.
1) TableModel: This model defines those things related to displaying data in a
two-dimensional format.
2) TableColumnModel: specifies the characteristics of a column.
3) ListSelectionModel: This model determines how items are selected.
A JTable can generate several different events. The two most fundamental to a
table’s operation are ListSelectionEvent and TableModelEvent.
By default, JTable allows you to select one or more complete rows, but you
can change this behavior to allow one or more columns, or one or more
individual cells to be selected.
Contd..
Here are the steps required to set up a simple JTable that can be used to
display data:
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.