Unit 3
Building Components using
Swing and JavaFX
Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop GUI or
window-based applications in java.
Java AWT components are platform-dependent i.e. components are
displayed according to the view of operating system.
The Abstract Window Toolkit (AWT) was Java’s first GUI framework,
and it has been part of Java since version 1.0.
It contains numerous classes and methods that allow you to create
windows and simple controls.
AWT contains large number of classes and methods that allows us to
create and manage graphical user interface ( GUI ) applications, such as
windows, buttons, scroll bars, etc.
AWT is heavyweight, consuming more resource
Java AWT Classes
The AWT classes are contained in the java.awt package. It is one of
Java’s largest packages.
The AWT package contains different classes :
a. GUI Component classes, such as Button, TextField, and Label.
b. GUI Container classes, such as Frame and Panel.
c. Layout Managers, such as FlowLayout, BorderLayout and
GridLayout.
d. Event Handling Classes, such as AWTEvent, AWTEventMultiCaster
e. Custom graphics classes, such as Graphics, Color and Font
Java AWT Class Hierarchy
First Java AWT Program
Note: The close button of the frame will not work as
we have not handled this event (which can be done).To
close the frame we can do
Java Swing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is
used to create window-based applications.
The Java Foundation Classes (JFC) are a set of GUI components
which simplify the development of desktop applications.
It is built on the top of AWT API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and
lightweight components
We need to import javax.swing.*;
AWT Vs Swing
Java Swing Hierarchy
Java Swing
Swing Is Built on the AWT
Although Swing eliminates a number of the limitations inherent in the
AWT, Swing does not replace it.
Instead, Swing is built on the foundation of the AWT.
This is why the AWT is still a crucial part of Java. Swing also uses the
same event handling mechanism as the AWT.
Therefore, a basic understanding of the AWT and of event handling is
required to use Swing.
Components and Containers
A Swing GUI consists of two key items: components and containers.
However, this distinction is mostly conceptual because all containers
are also components.
The difference between the two is found in their intended purpose: As
the term is commonly used, a 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.
All Swing GUIs will have at least one container. Because containers
are components, a container can also hold other containers.
Swing Containers
Swing defines two types of containers:
• Heavyweight container(top-level containers)
• Lightweight container
The top-level containers: JFrame, JApplet, JWindow, and JDialog.
These containers do not inherit JComponent. They do, however, inherit
the AWT classes Component and Container.
As the name implies, a top-level container must be at the top of a
containment hierarchy. A top-level container is not contained within any
other container.
Furthermore, every containment hierarchy must begin with a top-level
container. The one most commonly used for applications is JFrame. The
one used for applets is JApplet
Swing Containers
The second type of containers supported by Swing are lightweight
containers.
Lightweight containers do inherit JComponent. An example of a
lightweight container is JPanel, which is a general-purpose container.
The second type of containers supported by Swing are lightweight
containers. Lightweight containers do inherit JComponent.
An example of a lightweight container is JPanel, which is a general-
purpose container.
Top-Level Container Pane
Top-Level Container Pane
1. Root Pane: At the top of the hierarchy is an instance of JRootPane.
JRootPane is a lightweight container whose purpose is to manage
the other panes. It also helps manage the optional menu bar. The
panes that comprise the root pane are called the glass pane, the
content pane, and the layered pane.
2. Glass Pane: The glass pane is the top-level pane. It sits above and
completely covers all other panes. By default, it is a transparent
instance of JPanel. The glass pane enables us to manage mouse
events that affect the entire container (rather than an individual
control) or to paint over any other component.
Top-Level Container Pane
3. Layered Pane: The layered pane allows components to be given a
depth value. This value determines which component overlays
another. (Thus, the layered pane lets you specify a Z-order for a
component. The layered pane holds the content pane and the
(optional) menu bar. Menus and dialogue boxes are opened in this
pane.
4. Content Pane: It holds all visible components of the root pane,
except the menu bar. It covers the visible section of the JFrame or
JWindow and we use it to add components to the display area.
Jframe-Content Pane
Jframe-Setting Background color
JFrame-Changing Icon on the top
Icon Changed
Swing Components
In general, Swing components are derived from the JComponent
class. ( except the four top-level containers)
JComponent provides the functionality that is common to all
components.
For example, JComponent supports the pluggable look and feel.
JComponent inherits the AWT classes Container and Component.
Thus, a Swing component is built on and compatible with an AWT
component.
All of Swing’s components are represented by classes defined within
the package javax.swing. The following table shows the class names
for Swing components (including those used as containers).
Swing Components
All component classes begin with the letter J.
JApplet JButton JCheckBoxMenuItem JCheckBox JColorChooser JComboBox
JComponent JDesktopPane JDialog JEditorPane JFileChooser JFormattedTextField
Jframe JInternalFrame JLabel JLayer JLayeredPane JList
JMenuBar JMenu JMenuItem JOptionPane JPasswordField JPopUpMenu
JProgressBar JRadioButton JRadioButtonMenuItem JRootPane JScrollBar JScrollPane
JSeparator JSlider JSpinner JSplitPane JTabbedPane JTable
jTextArea JTextField JTextPane JTextField JTextPane JToggablebutton
JToolBar JToolTip JTree JViewport JWindow
Swing Components-JLabel
It is used to display a single line of read only text.
We define a JLabel and add it to our frame.
Swing Components-JTextField
The object of a JTextField class is a text component that allows the
editing of a single line text.
It inherits JTextComponent class.
The constructor of the class are :
a. JTextField() : constructor that creates a new TextField
b. JTextField(int columns) : constructor that creates a new empty TextField
with specified number of columns.
c. JTextField(String text) : constructor that creates a new empty text field
initialized with the given string.
d. JTextField(String text, int columns) : constructor that creates a new empty
textField with the given string and a specified number of columns .
e. JTextField(Document doc, String text, int columns) : constructor that
creates a textfield that uses the given text storage model and the given
number of columns.
Swing Components-JTextField Example
Swing Components-JTextField Example
The same thing can also be done using constructor as below:
Swing Components-JTextArea
It represents a multi line area that displays text. It is used to edit the
text .
JTextArea inherits JComponent class.
Constructors of JTextArea are:
• JTextArea() : constructs a new blank text area .
• JTextArea(String s) : constructs a new text area with a given initial
text.
• JTextArea(int row, int column) : constructs a new text area with a
given number of rows and columns.
• JTextArea(String s, int row, int column) : constructs a new text area
with a given number of rows and columns and a given initial text.
Swing Components-JTextArea Methods
Swing Components-JTextArea Example
Swing Components-JButton
The JButton class is used to create a labeled button that has platform
independent implementation.
Swing Components-Jbutton Example with Event Handling
Swing Components-JCheckBox
The JCheckBox class is used to create a checkbox.
It is used to turn an option on (true) or off (false).
public boolean isSelected(): This method is used to check whether
specific checkbox is selected/checked or not
Swing Components- JRadioButton
The JRadioButton class is used to create a radio button.
It is used to choose one option from multiple options.
It should be added in ButtonGroup to select one radio button only
public boolean isSelected(): This method is used to check whether specific radio
button is selected/checked or not
Swing Components- JComboBox
JComboBox shows a popup menu that shows a list and the user can
select a option from that specified list .
JComboBox can be editable or read- only depending on the choice of the
programmer .
Constructor of the JComboBox are:
• JComboBox() : creates a new empty JComboBox .
• JComboBox(ComboBoxModel M) : creates a new JComboBox with items
from specified ComboBoxModel
• JComboBox(E [ ] i) : creates a new JComboBox with items from specified
array.
• JComboBox(Vector items) : creates a new JComboBox with items from
the specified vector
Swing Components- JComboBox
Swing Components- JComboBox Example
Swing Components-JComboBox Example
Swing Components-JMenuBar, JMenu and JMenuItem
The JMenuBar class is used to display menubar on the window or
frame. It may have several menus.
The object of JMenu class is a pull down menu component which is
displayed from the menu bar. It inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The
items used in a menu must belong to the JMenuItem or any of its
subclass.
In order to set the JMenuBar on frame we can use setJMenuBar()
method.
Swing Components-JMenuBar and JMenu Example
Swing Components-JMenuBar, JMenu and JMenuItem Example
Swing Components-JMenuBar, JMenu and JMenuItem Example
• Note: Same example with another methods
Swing Components-JMenuBar, JMenu and JMenuItem Example
Swing Components-JMenuBar, JMenu and JMenuItem Example
Swing Components-JOptionPane
The JOptionPane class is used to provide standard dialog boxes such
as message dialog box, confirm dialog box and input dialog box.
These dialog boxes are used to display information or get input from
the user.
Syntax for show message dialog:
JOptionPane.showMessageDialog(parentComponent, message, title, messageType, icon);
where parentComponent is generally set null which represents the parent component
on which the dialog message is to be displayed, message contains a string value that is
displayed on the dialog body, title contains a string value that appears as the title of the
dialog box, messageType defines the type of message that the dialog defines, icon
contains the icon to be displayed in the dialog that helps the user identify the kind of
message that is being displayed
Swing Components-JOptionPane Example
Swing Components-JOptionPane Example
Swing Components-JOptionPane
Syntax for confirm dialog:
JOptionPane.showConfirmDialog(parentComponent, message, title, messageType, icon);
This function returns value 0 on yes, 1 on no, 2 on cancel and -1 on close
Swing Components-JOptionPane
Input Dialog
For input dialog, we use showinputDialog(). This method returns the
value entered on the input dialog box.
Swing Components-JPanel
The JPanel is a simplest container class.
It provides space in which an application can attach any other component.
Swing Components-JScrollPane Example
A JScrollPane is used to make scrollable view of a component.
When screen size is limited, we use a scroll pane to display a large
component or a component whose size can change dynamically.
Constructor Purpose
JScrollPane() It creates a scroll pane. The Component parameter,
when present, sets the scroll pane's client. The two int
JScrollPane(Component)
parameters, when present, set the vertical and
JScrollPane(int, int) horizontal scroll bar policies (respectively).
JScrollPane(Component, int, int)
Swing Components-JTable
The JTable class is a part of Java Swing Package and is generally used
to display or edit two-dimensional data that is having both rows and
columns.
It is similar to a spreadsheet.
Constructors in JTable:
• JTable(): A table is created with empty cells.
• JTable(int rows, int cols): Creates a table of size rows * cols.
• JTable(Object[][] data, Object []Column): A table is created with the
specified name where []Column defines the column names.
Swing Components-JTable
JTabbedPane
The JTabbedPane class is used to switch between a group of components
by clicking on a tab with a given title or icon.
It inherits JComponent class.
Commonly used constructors are:
JTabbedPane()
//Creates an empty TabbedPane with a default tab placement of JTabbedPane.Top
JTabbedPane(int tabPlacement)
//Creates an empty TabbedPane with a specified tab placement
JTabbedPane(int tabPlacement, int tabLayoutPolicy)
//Creates an empty TabbedPane with a specified tab placement and tab layout policy.
JTabbedPane
After creating the object of JTabbedPane, we add components on the
pane as:
tabbedPaneObject.add(String tabName, Component comp);
Layout Managers
The Layout Managers are used to arrange components in a particular manner
LayoutManager is an interface that is implemented by all the classes of layout
managers.
There are following classes that represents the layout managers:
a. java.awt.BorderLayout
b. java.awt.FlowLayout
c. java.awt.GridLayout
d. java.awt.CardLayout
e. java.awt.GridBagLayout
f. javax.swing.BoxLayout
g. javax.swing.GroupLayout
h. javax.swing.ScrollPaneLayout
i. javax.swing.SpringLayout
Layout Managers-BorderLayout
The BorderLayout class implements a common layout style for top-
level windows.
It has four narrow, fixed-width components at the edges and one large
area in the center.
The four sides are referred to as north, south, east, and west. The
middle area is called the center.
Here are the constructors defined by BorderLayout:
BorderLayout( )
BorderLayout(int horz, int vert)
The first form creates a default border layout.
The second allows us to specify the horizontal and vertical space left
between components in horz and vert, respectively.
Layout Managers-BorderLayout
Layout Managers-BorderLayout- Using Insets
Sometimes you will want to leave a small amount of space between
the container that holds your components and the window that
contains it.
To do this, override the getInsets( ) method that is defined by
Container. This method returns an Insets object that contains the top,
bottom, left, and right inset to be used when the container is displayed.
These values are used by the layout manager to inset the components
when it lays out the window.
Insets(int top, int left, int bottom, int right)
The values passed in top, left, bottom, and right specify the amount of
space between the container and its enclosing window.
Flow Layout
The FlowLayout is used to arrange the components in a row, one aȇer
another (in a flow). It is the default layout of applet or panel
FlowLayout provides five constants for each region: LEFT, RIGHT,
CENTER, LEADING, TRAILING
Constructors of FlowLayout class
a. FlowLayout(): creates a flow layout with centered alignment and a default 5
unit horizontal and vertical gap.
b. FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
c. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
Flow Layout-Example
Flow Layout-Example
Grid Layout
The GridLayout is used to arrange the components in rectangular
grid. One component is displayed in each rectangle.
Constructors of GridLayout class
a. GridLayout(): creates a grid layout with one column per
component in a row.
b. GridLayout(int rows, int columns): creates a grid layout with the
given rows and columns but no gaps between the components.
c. GridLayout(int rows, int columns, int hgap, int vgap): creates a
grid layout with the given rows and columns along with given
horizontal and vertical gaps.
Grid Layout-Example
Create the following using Grid Layout.
Grid Layout-Example
Box Layout
The BoxLayout class is used to arrange the components either
vertically (along Y-axis) or horizontally (along X-axis).
In BoxLayout class, the components are put either in a single row or a
single column.
Constructor for Box layout:
BoxLayout(Container c, int axis): Creates a BoxLayout class that
arranges the components with the X-axis or Y-axis.
Note: In Swing, a BoxLayout cannot be shared between multiple
containers. This is a key limitation of BoxLayout
Box Layout-Example
Box Layout-Example
Card Layout
The Java 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.
CardLayout provides these two constructors:
CardLayout( ) //creates a card layout with zero horizontal and vertical
gap.
CardLayout(int horz, int vert) //creates a card layout with the given
horizontal and vertical gap
Card Layout
Commonly used methods of CardLayout are:
1. public void next(Container parent): is used to flip to the next card
of the given container.
2. public void previous(Container parent): is used to flip to the
previous card of the given container.
3. public void first(Container parent): is used to flip to the first card of
the given container.
4. public void last(Container parent): is used to flip to the last card of
the given container.
5. public void show(Container parent, String name): is used to flip to
the specified card with the given name.
Card Layout-Example
Note: Each time we click the
button, the button instance gets
changed.
GridBag Layout
The Java GridBagLayout class is used to align components vertically,
horizontally or along their baseline.
GridBagLayout components are also arranged in the rectangular grid but
can have many different sizes and can occupy multiple rows or
columns.
The components may not be of the same size. Each GridBagLayout
object maintains a dynamic, rectangular grid of cells.
Each component occupies one or more cells known as its display area.
Each component associates an instance of GridBagConstraints. With the
help of the constraints object, we arrange the component's display
area on the grid.
The GridBagLayout manages each component's minimum and preferred
sizes in order to determine the component's size.
GridBag Layout-Methods
Event Handling in Java Swing
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.
Event Handling in Java Swing
1. Event: An event is a signal to the program that something has happened. It
can be triggered by typing in a text field, selecting an item from the menu
etc.
2. Event handler: The code that performs a task in response to an event. is
called event handler.
3. Event handling: It is process of responding to events that can occur at any
time during execution of a program.
4. Event Source: It is an object that generates the event(s). Usually the event
source is a button or the other component that the user can click but any
Swing component can be an event source.
5. Event Listener: It is an object that watch for (i.e. listen for) events and
handles them when they occur.
6. Listener interface: It is an interface which contains methods that the listener
must implement and the source of the event invokes when the event occurs.
Java Event classes and Listener interfaces
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
ActionEvent Example
ActionEvent Example
Mouse Event Handling
The class which processes the MouseEvent should implement
MouseListener Interface.
The Java MouseListener is notified whenever you change the state of
mouse. It is notified against MouseEvent.
The MouseListener interface is found in java.awt.event package. It
has five methods.
Methods:
a. public abstract void mouseClicked(MouseEvent e);
b. public abstract void mouseEntered(MouseEvent e);
c. public abstract void mouseExited(MouseEvent e);
d. public abstract void mousePressed(MouseEvent e);
MouseEvent Example
MouseWheelEvent Example
Key Event Handling
The Java KeyListener is notified whenever you change the state of key.
It is notified against KeyEvent.
The KeyListener interface is found in java.awt.event package, and it has three
methods.
Window Event
For Window Event, we use WindowListener Interface.
The Java WindowListener is notified whenever you change the state
of window. It is notified against WindowEvent.
Constructor Description
WindowEvent(Window source, int id) Constructs a WindowEvent object.
WindowEvent(Window source, int id, int Constructs a WindowEvent object with the specified previous and new
oldState, int newState) window states.
WindowEvent(Window source, int id, Constructs a WindowEvent object with the specified opposite Window.
Window opposite)
WindowEvent(Window source, int id, Constructs a WindowEvent object.
Window opposite, int oldState, int
newState)
Window Event
Java Adapter Classes
Java adapter classes provide the Adapter class Listener interface
default implementation of
WindowAdapter WindowListener
listener interfaces.
KeyAdapter KeyListener
If we inherit the adapter class, you MouseAdapter MouseListener
will not be forced to provide the MouseMotionAdapter MouseMotionListener
implementation of all the methods of FocusAdapter FocusListener
listener interfaces. So it saves code. ComponentAdapter ComponentListener
The adapter classes are found in ContainerAdapter ContainerListener
java.awt.event, HierarchyBoundsAdapter HierarchyBoundsListener
java.awt.dnd and javax.swing.event
packages.
Java Adapter Classes
java.awt.dnd Adapter classes
Adapter class Listener interface
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
javax.swing.event Adapter classes
Adapter class Listener interface
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
Java Adapter Classes-Example