0% found this document useful (0 votes)
10 views21 pages

Unit 4 Notes

The document provides an overview of Java AWT and Swing, detailing their components, containers, layout managers, and event handling mechanisms. It highlights the differences between AWT and Swing, emphasizing Swing's lightweight and platform-independent nature, as well as its advanced features like MVC architecture. Additionally, it covers various Swing components and their functionalities, including buttons, text fields, and event handling processes.

Uploaded by

jananippriya18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views21 pages

Unit 4 Notes

The document provides an overview of Java AWT and Swing, detailing their components, containers, layout managers, and event handling mechanisms. It highlights the differences between AWT and Swing, emphasizing Swing's lightweight and platform-independent nature, as well as its advanced features like MVC architecture. Additionally, it covers various Swing components and their functionalities, including buttons, text fields, and event handling processes.

Uploaded by

jananippriya18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-IV NOTES

The AWT class hierarchy - Swing: Introduction to Swing - Hierarchy of swing


components. Containers - Top level containers - JFrame - JWindow - JDialog - JPanel -
JButton - JToggleButton - JCheckBox - JRadioButton - JLabel,JTextField - JTextArea - JList -
JComboBox – JscrollPane - Event Handling: Events - Event sources - Event Listeners -
Event Delegation Model (EDM) - Handling Mouse and Keyboard Events

****************************************************************************

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 Basics

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.

Why AWT is Platform Independent?

AWT is platform independent even after the AWT components are platform dependent because of
the points mentioned below:

1. JVM (Java Virtual Machine):

As Java Virtual Machine is platform dependent

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.

Types of Containers in Java AWT

There are four types of containers in Java AWT:

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.

Difference between Java Swing and Java AWT

There are certain points from which Java Swing is different than Java AWT as mentioned below:

Java AWT Java Swing

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.

Components are platform dependent. Components are platform independent.

Execution Time is more than Swing. Execution Time is less than AWT.

Swing components requires [Link]


AWT components require [Link] package.
package.

Features Of Swing Class

 Pluggable look and feel.

 Uses MVC architecture.

 Lightweight Components

 Platform Independent

 Advanced features such as JTable, JTabbedPane, JScollPane, etc.

 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.

The MVC Connection

 In general, a visual component is a composite of three distinct aspects:

1. The way that the component looks when rendered on the screen.

2. The way such that the component reacts to the user.

3. The state information associated with the component.

 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.

 The controller determines how the component reacts to the user.

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

These are the building blocks of the user interface:


 JLabel: Displays static text or images.
 JButton: Triggers actions when clicked.
 JTextField: Allows single-line text input.
 JTextArea: Allows multi-line text input.
 JCheckBox: Allows binary selection (on/off).
 JRadioButton: Allows single selection from a group of options.
 JComboBox: Provides a drop-down list of options.

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 CLASS IN JAVA

JAVA SWING CONTROLS

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.

Components of Swing in Java

Below are the different components of swing in java:

1. ImageIcon

The ImageIcon component creates an icon sized-image from an image residing at the source URL.

Example:

ImageIcon homeIcon = new ImageIcon("src/images/[Link]");

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:

JButton okBtn = new JButton("Ok");


This constructor returns a button with text Ok on it.

JButton homeBtn = new JButton(homeIcon);

It returns a button with a homeIcon on it.

JButton btn2 = new JButton(homeIcon, "Home");

It returns a button with the home icon and text Home.

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:

JLabel textLbl = new JLabel("This is a text label.");

This constructor returns a label with text.

JLabel imgLabel = new JLabel(homeIcon);

It returns a label with a home icon.

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:

JTextField txtBox = new JTextField(20);

It renders a text box of 20 column width.

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:

JPasswordField pwdField = new JPasswordField(15);

var pwdValue = [Link]();

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:

CheckBox chkBox = new JCheckBox("Show Help", true);

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:

ButtonGroup radioGroup = new ButtonGroup();

JRadioButton rb1 = new JRadioButton("Easy", true);

JRadioButton rb2 = new JRadioButton("Medium");

JRadioButton rb3 = new JRadioButton("Hard");

[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:

DefaultListItem cityList = new DefaultListItem();

[Link]("Mumbai"):
[Link]("London"):

[Link]("New York"):

[Link]("Sydney"):

[Link]("Tokyo"):

JList cities = new JList(cityList);

[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

JComboBox class is used to render a dropdown of the list of options.

Example:

String[] cityStrings = { "Mumbai", "London", "New York", "Sydney", "Tokyo" };

JComboBox cities = new JComboBox(cityList);

[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:

JFileChooser fileChooser = new JFileChooser();

JButton fileDialogBtn = new JButton("Select File");

[Link](new ActionListner(){

[Link]();

})

var selectedFile = [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:

JTabbedPane tabbedPane = new JTabbedPane();

[Link]("Tab 1", new JPanel());

[Link]("Tab 2", new JPanel());

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:

JSlider volumeSlider = new JSlider(0, 100, 50);

var volumeLevel = [Link]();

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.

Event Handling in Java


An event is a change in the state of an object triggered by some action such as Clicking a button,
Moving the cursor, Pressing a key on the keyboard, Scrolling a page, etc. In Java,
the [Link] package provides various event classes to handle these actions.

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.

Registering the Source With Listener

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,

 addKeyListener() for KeyEvent

 addActionListener() for ActionEvent

Event Classes and Listener Interfaces


Java provides a variety of event classes and corresponding
listener interfaces. Below table demonstrates the most
commonly used event classes and their associated listener
interfaces:
Event Class Listener Interface Description

An event that indicates that a


component-defined action occurred like
ActionEvent ActionListener
a button click or selecting an item from
the menu-item list.

The adjustment event is emitted by an


AdjustmentEvent AdjustmentListener
Adjustable object like Scrollbar.

An event that indicates that a


ComponentEvent ComponentListener component moved, the size changed or
changed its visibility.

When a component is added to a


container (or) removed from it, then
ContainerEvent ContainerListener
this event is generated by a container
object.

These are focus-related events, which


FocusEvent FocusListener include focus, focusin, focusout, and
blur.

An event that indicates whether an


ItemEvent ItemListener
item was selected or not.

An event that occurs due to a sequence


KeyEvent KeyListener
of keypresses on the keyboard.

The events that occur due to the user


MouseListener &
MouseEvent interaction with the mouse (Pointing
MouseMotionListener
Device).

An event that specifies that the mouse


MouseWheelEvent MouseWheelListener
wheel was rotated in a component.
Event Class Listener Interface Description

An event that occurs when an object’s


TextEvent TextListener
text changes.

An event which indicates whether a


WindowEvent WindowListener
window has changed its status or not.

Methods in Listener Interfaces

Each listener interface contains specific methods that must be implemented to handle events. Below
table demonstrates the key methods for each interface:

Listener Interface Methods

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()

Approaches For Event Handling

Java provides three main approaches to implement event handling

1. Event Handling Within the Class


// Java program to demonstrate the

// event handling within the class

import [Link].*;

import [Link].*;

class GFGTop extends Frame implements ActionListener {

TextField textField;

GFGTop()

// Component Creation

textField = new TextField();

// setBounds method is used to provide

// position and size of the component

[Link](60, 50, 180, 25);

Button button = new Button("click Here");

[Link](100, 120, 80, 30);

// Registering component with listener

// this refers to current instance

[Link](this);

// add Components

add(textField);

add(button);

// set visibility

setVisible(true);

}
// implementing method of actionListener

public void actionPerformed(ActionEvent e)

// Setting text to field

[Link]("GFG!");

public static void main(String[] args)

new GFGTop();

Output:

Explanation:

 Firstly extend the class with the applet and implement the respective listener.

 Create Text-Field and Button components.

 Registered the button component with respective event. i.e. ActionEvent by


addActionListener().

 In the end, implement the abstract method.


2. Event Handling by Another Class

// Java program to demonstrate the

// event handling by the other class

import [Link].*;

import [Link].*;

class GFG1 extends Frame {

TextField textField;

GFG2()

// Component Creation

textField = new TextField();

// setBounds method is used to provide

// position and size of component

[Link](60, 50, 180, 25);

Button button = new Button("click Here");

[Link](100, 120, 80, 30);

Other other = new Other(this);

// Registering component with listener

// Passing other class as reference

[Link](other);

// add Components

add(textField);

add(button);
// set visibility

setVisible(true);

public static void main(String[] args)

new GFG2();

Separate class implementing ActionListener to handle events:

/// import necessary packages

import [Link].*;

// implements the listener interface

class Other implements ActionListener {

GFG2 gfgObj;

Other(GFG1 gfgObj) {

[Link] = gfgObj;

public void actionPerformed(ActionEvent e)

// setting text from different class

[Link]("Using Different Classes");

Output:
3. Event Handling By Anonymous Classes

// Java program to demonstrate the

// event handling by the anonymous class

import [Link].*;

import [Link].*;

class GFG3 extends Frame {

TextField textField;

GFG3()

// Component Creation

textField = new TextField();

// setBounds method is used to provide


// position and size of component

[Link](60, 50, 180, 25);

Button button = new Button("click Here");

[Link](100, 120, 80, 30);

// Registering component with listener anonymously

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e)

// Setting text to field

[Link]("Anonymous");

});

// add Components

add(textField);

add(button);

//make size viewable

setSize(300,300);

// set visibility

setVisible(true);

public static void main(String[] args)

new GFG3();

Output:

You might also like