Unit 4 Notes
Unit 4 Notes
****************************************************************************
Java AWT
Java AWT or Abstract Window Toolkit is an API used for developing GUI(Graphic User Interfaces) or
Window-Based Applications in Java. Java AWT is part of the Java Foundation Classes (JFC) that
provides a way to build platform-independent graphical applications.
Java AWT (Abstract Window Toolkit) is an API used to create Graphical User Interface (GUI) or
Windows-based Java programs and Java AWT components are platform-dependent, which means
they are shown in accordance with the operating system’s view. AWT is heavyweight, which means
that its components consume resources from the underlying operating system (OS). The
[Link] package contains AWT API classes such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List, and so on.
AWT is platform independent even after the AWT components are platform dependent because of
the points mentioned below:
2. Abstract APIs:
AWT provides an abstract layer for GUI. Java applications interact with AWT through Abstract API
which are platform independent. Abstract API allows Java to isolate platform-specific details, making
code portable across different systems.
3. Platform-Independent Libraries:
The Libraries of AWT are written in Java which they are totally platform-independent. Because of
this, it ensures that AWT functionality remains consistent across different environments.
Java AWT Hierarchy
Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications.
Containers: AWT provides containers like panels, frames, and dialogues to organize and
group components in the Application.
Layout Managers: Layout Managers are responsible for arranging data in the containers
some of the layout managers are BorderLayout, FlowLayout, etc.
Event Handling: AWT allows the user to handle the events like mouse clicks, key presses, etc.
using event listeners and adapters.
Graphics and Drawing: It is the feature of AWT that helps to draw shapes, insert images and
write text in the components of a Java Application.
1. Window: Window is a top-level container that represents a graphical window or dialog box.
The Window class extends the Container class, which means it can contain other
components, such as buttons, labels, and text fields.
2. Panel: Panel is a container class in Java. It is a lightweight container that can be used for
grouping other components together within a window or a frame.
3. Frame: The Frame is the container that contains the title bar and border and can have menu
bars.
4. Dialog: A dialog box is a temporary window an application creates to retrieve user input.
Introduction to Java Swing
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window
Toolkit [AWT]. Java Swing offers much-improved functionality over AWT, new components,
expanded components features, and excellent event handling with drag-and-drop support.
There are certain points from which Java Swing is different than Java AWT as mentioned below:
Java AWT is an API to develop GUI applications Swing is a part of Java Foundation Classes and
in Java. is used to create various applications.
Components of AWT are heavy weighted. The components of Java Swing are lightweight.
Execution Time is more than Swing. Execution Time is less than AWT.
Lightweight Components
Platform Independent
Java is a platform-independent language and runs on any client machine, the GUI look and
feel, owned and delivered by a platform-specific O/S, simply does not affect an application’s
GUI constructed using Swing components.
Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight
component development. For a component to qualify as lightweight, it must not depend on
any non-Java [O/s based) system classes. Swing components have their own view supported
by Java’s look and feel classes.
Pluggable Look and Feel: This feature enable the user to switch the look and feel of Swing
components without restarting an application. The Swing library supports components’ look
and feels that remain the same across all platforms wherever the program runs. The Swing
library provides an API that gives real flexibility in determining the look and feel of the GUI of
an application
Highly customizable – Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane, slider,
colorpicker, and table controls.
1. The way that the component looks when rendered on the screen.
Over the years, one component architecture has proven itself to be exceptionally effective:
– Model-View-Controller or MVC for short.
In MVC terminology, the model corresponds to the state information associated with the
Component.
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.
Java JComponent
Here is the information about top-level and intermediate containers, basic components,
layout managers, event handling, and MVC in Java.
Top-Level Containers
These are the main windows of an application. They include:
JFrame: For creating the main application window.
JDialog: For creating dialog boxes.
JApplet: For creating applets that run in a web browser (deprecated).
Intermediate Containers
These containers hold other components and help organize the GUI. They include:
JPanel: A general-purpose container.
JScrollPane: Provides scrollbars for components that exceed the display area.
JSplitPane: Allows dividing the window into resizable panels.
Basic Components
Layout Managers
Layout managers control the arrangement of components within a container:
FlowLayout: Arranges components in a row, wrapping to the next row if necessary
(default for JPanel).
BorderLayout: Arranges components in five regions: North, South, East, West, and
Center (default for JFrame).
GridLayout: Arranges components in a grid of rows and columns.
CardLayout: Allows switching between different components in the same space.
GridBagLayout: Provides a flexible grid-based layout with advanced customization
options.
Event Handling
Event handling is the process of responding to user interactions, such as button clicks
or mouse movements. The delegation event model is commonly used, where event
listeners are attached to components to handle specific events.
Model-View-Controller (MVC)
MVC is an architectural pattern for separating the application logic into three interconnected
parts:
Model: Represents the data and business logic.
View: Displays the data to the user.
Controller: Handles user input and updates the model and view.
Swing components are often used in the view part of an MVC architecture, while event
handling mechanisms facilitate the interaction between the controller and the other parts.
Swing components are the basic building blocks of an application. We know that Swing is a GUI
widget toolkit for Java. Every application has some basic interactive interface for the user. For
example, a button, check-box, radio-button, text-field, etc. These together form the components in
Swing.
1. ImageIcon
The ImageIcon component creates an icon sized-image from an image residing at the source URL.
Example:
This returns an icon of a home button. The string parameter is the path at which the source image is
present.
2. JButton
JButton class is used to create a push-button on the UI. The button can contain some display text or
image. It generates an event when clicked and double-clicked. A JButton can be implemented in the
application by calling one of its constructors.
Example:
3. JLabel
JLabel class is used to render a read-only text label or images on the UI. It does not generate any
event.
Example:
4. JTextField
JTextField renders an editable single-line text box. A user can input non-formatted text in the box. To
initialize the text field, call its constructor and pass an optional integer parameter to it. This
parameter sets the width of the box measured by the number of columns. It does not limit the
number of characters that can be input in the box.
Example:
5. JTextArea
JTextArea class renders a multi-line text box. Similar to the JTextField, a user can input non-formatted
text in the field. The constructor for JTextArea also expects two integer parameters which define the
height and width of the text-area in columns. It does not restrict the number of characters that the
user can input in the text-area.
Example:
JTextArea txtArea = new JTextArea("This text is default text for text area.", 5, 20);
The above code renders a multi-line text-area of height 5 rows and width 20 columns, with default
text initialized in the text-area.
6. JPasswordField
JPasswordField is a subclass of JTextField class. It renders a text-box that masks the user input text
with bullet points. This is used for inserting passwords into the application.
Example:
It returns a password field of 15 column width. The getPassword method gets the value entered by
the user.
7. JCheckBox
JCheckBox renders a check-box with a label. The check-box has two states – on/off. When selected,
the state is on and a small tick is displayed in the box.
Example:
It returns a checkbox with the label Show Help. Notice the second parameter in the constructor. It is
a boolean value that indicates the default state of the check-box. True means the check-box is
defaulted to on state.
8. JRadioButton
JRadioButton is used to render a group of radio buttons in the UI. A user can select one choice from
the group.
Example:
[Link](rb1);
[Link](rb2);
[Link](rb3);
The above code creates a button group and three radio button elements. All three elements are then
added to the group. This ensures that only one option out of the available options in the group can
be selected at a time. The default selected option is set to Easy.
9. JList
JList component renders a scrollable list of elements. A user can select a value or multiple values
from the list. This select behavior is defined in the code by the developer.
Example:
[Link]("Mumbai"):
[Link]("London"):
[Link]("New York"):
[Link]("Sydney"):
[Link]("Tokyo"):
[Link](ListSelectionModel.SINGLE_SELECTION);
The above code renders a list of cities with 5 items in the list. The selection restriction is set to
SINGLE_SELECTION. If multiple selections is to be allowed, set the behavior to
MULTIPLE_INTERVAL_SELECTION.
10. JComboBox
Example:
[Link](3);
The default selected option can be specified through the setSelectedIndex method. The above code
sets Sydney as the default selected option.
11. JFileChooser
JFileChooser class renders a file selection utility. This component lets a user select a file from the
local system.
Example:
[Link](new ActionListner(){
[Link]();
})
The above code creates a file chooser dialog and attaches it to the button. The button click would
open the file chooser dialog. The selected file is returned through the getSelectedFile method.
12. JTabbedPane
JTabbedPane is another very useful component that lets the user switch between tabs in an
application. This is a highly useful utility as it lets the user browse more content without navigating to
different pages.
Example:
The above code creates a two tabbed panel with headings Tab 1 and Tab 2.
13. JSlider
JSlider component displays a slider which the user can drag to change its value. The constructor
takes three arguments – minimum value, maximum value, and initial value.
Example:
The above code creates a slider from 0 to 100 with an initial value set to 50. The value selected by
the user is returned by the getValue method.
Classification of Events
Events in Java can be broadly classified into two categories based on how they are generated:
1. Foreground Events: Foreground events are the events that require user interaction to
generate. Examples of these events include Button clicks, Scrolling the scrollbar, Moving the
cursor, 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.
Event Handling Mechanism
Event handling is a mechanism that allows programs to control events and define what should
happen when an event occurs. Java uses the Delegation Event Model to handle events. This model
consists of two main components:
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 handle events, the source must be registered with a listener. Java provides specific methods for
registering listeners based on the type of event.
Syntax:
addTypeListener()
For example,
Each listener interface contains specific methods that must be implemented to handle events. Below
table demonstrates the key methods for each interface:
ActionListener actionPerformed()
AdjustmentListener adjustmentValueChanged()
componentResized()
componentShown()
ComponentListener
componentMoved()
componentHidden()
componentAdded()
ContainerListener
componentRemoved()
focusGained()
FocusListener
focusLost()
ItemListener itemStateChanged()
KeyListener keyTyped()
Listener Interface Methods
keyPressed()
keyReleased()
mousePressed()
mouseClicked()
MouseListener mouseEntered()
mouseExited()
mouseReleased()
mouseMoved()
MouseMotionListener
mouseDragged()
MouseWheelListener mouseWheelMoved()
TextListener textChanged()
windowActivated()
windowDeactivated()
windowOpened()
WindowListener windowClosed()
windowClosing()
windowIconified()
windowDeiconified()
import [Link].*;
import [Link].*;
TextField textField;
GFGTop()
// Component Creation
[Link](this);
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
// implementing method of actionListener
[Link]("GFG!");
new GFGTop();
Output:
Explanation:
Firstly extend the class with the applet and implement the respective listener.
import [Link].*;
import [Link].*;
TextField textField;
GFG2()
// Component Creation
[Link](other);
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
new GFG2();
import [Link].*;
GFG2 gfgObj;
Other(GFG1 gfgObj) {
[Link] = gfgObj;
Output:
3. Event Handling By Anonymous Classes
import [Link].*;
import [Link].*;
TextField textField;
GFG3()
// Component Creation
[Link](new ActionListener() {
[Link]("Anonymous");
});
// add Components
add(textField);
add(button);
setSize(300,300);
// set visibility
setVisible(true);
new GFG3();
Output: