0% found this document useful (0 votes)
2 views50 pages

Java Swing Overview and Key Features

This document provides an overview of Java AWT and Swing, detailing their key features, components, and event handling mechanisms. It explains the Model-View-Controller (MVC) architecture used in Swing applications and includes examples of creating simple GUI applications with Swing components like JFrame, JLabel, and JTextField. Additionally, it covers layout management and event handling in Swing, highlighting the Delegation Event Model and various event types.

Uploaded by

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

Java Swing Overview and Key Features

This document provides an overview of Java AWT and Swing, detailing their key features, components, and event handling mechanisms. It explains the Model-View-Controller (MVC) architecture used in Swing applications and includes examples of creating simple GUI applications with Swing components like JFrame, JLabel, and JTextField. Additionally, it covers layout management and event handling in Swing, highlighting the Delegation Event Model and various event types.

Uploaded by

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

Module 4 - Part 1

Overview of AWT, Swing v/s AWT, Swing Key Features, , Swing Packages,
Model View Controller (MVC), Swing Controls, Components and Containers
Event Handling in Swings, Swing Layout Managers
Exploring Swings–JFrame, JLabel, The Swing Buttons, JTextField.

Event Handling Mechanisms, Delegation Event Model,


Event Classes, Sources of Events,
Event Listener Interfaces, Using the Delegation Event Model.
🧰 What is AWT?
AWT is a Java API used to build Graphical User Interfaces (GUIs) and
window-based applications. It’s part of the Java Foundation Classes (JFC) and
provides a set of classes for creating user interface components like windows,
buttons, text fields, and more.

🧱 Key Components of AWT


● Component: Basic UI elements like Button, Label, TextField, etc.
● Container: Holds and organizes components (Panel, Frame, Window)
● Layout Managers: Control the positioning and sizing of components
(FlowLayout, BorderLayout, etc.)
● Event Handling: Responds to user interactions like clicks and key presses
What Is Swing?
● Swing is a set of Java libraries for creating graphical user interfaces. Unlike AWT,

Swing components are written entirely in Java and do not rely on native OS

components—making them lightweight and platform-independent.

● Java Swing is a part of Java Foundation Classes (JFC) that is used to create

window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API

and entirely written in Java.

● Swing API is a set of extensible GUI Components to ease the developer's life

to create JAVA based Front End/GUI Applications.


🌟 Key Features of Java Swing
🪶 1. Lightweight Components

● Swing components are written entirely in Java.


● They don’t rely on native OS peers, making them more efficient and consistent across platforms.

🎨 2. Pluggable Look and Feel

● You can change the appearance of your application dynamically.


● Swing supports multiple themes like Metal, Nimbus, or even mimic native OS styles.

🧱 3. Rich Set of Components

● Includes advanced UI elements like JTable, JTree, JTabbedPane, JColorChooser, and more.
● Far more versatile than AWT’s limited set.

🧭 4. MVC Architecture

● Swing follows the Model-View-Controller design pattern.


● This separation improves flexibility and maintainability of code.
🖥 5. Platform Independence

● Swing applications run consistently on any OS with Java support.


● No need to worry about platform-specific quirks.

🧩 6. Customizable UI

● Developers can create custom components or override existing ones.


● Full control over rendering and behavior.

🔄 7. Event Handling

● Robust event-handling model using listeners.


● Supports mouse, keyboard, window, and action events.

📐 8. Flexible Layout Managers

● Layout managers like BorderLayout, GridLayout, BoxLayout, and CardLayout help organize
components intuitively.

🧰 9. Integration with AWT

● Swing is built on top of AWT, so you can mix components if needed.


AWT vs Swing
MVC Architecture
(Model-View-Controller)
The Model-View-Controller (MVC) architecture is a classic design pattern used to
organize code in a clean, modular way—especially in GUI and web applications.

MVC divides an application into three interconnected components, each with a distinct role:
How It Works
1. User interacts with the View (e.g., clicks a button).
2. Controller receives the input, interprets it, and updates the Model.
3. Model changes its state based on the Controller’s instructions.
4. View updates to reflect the new state of the Model.

This separation ensures that each part of the application can evolve independently.

🧪 Example in Java Swing


Let’s say you’re building a simple calculator:

● Model: Handles the math operations.


● View: Displays buttons and results.
● Controller: Listens for button clicks and tells the Model what to compute.
MVC in Swing: The Core Idea
Swing components are designed with separable models, meaning the data (Model) is kept
distinct from the UI (View). However, unlike traditional MVC, View and Controller are often
combined into the component itself.
How Swing Implements MVC

Example: JTable
● Model: TableModel stores the data.
● View: JTable renders the data in a grid.
● Controller: JTable also handles user actions like clicks and edits.
A Simple Swing Application

● two types of Java programs in which Swing is typically used.

○ desktop application
○ applet
SWING - Controls
Every user interface considers the following three main aspects −
● UI Elements − These are the core visual elements the user eventually sees
and interacts with. GWT provides a huge list of widely used and common
elements varying from basic to complex.

● Layouts − They define how UI elements should be organized on the screen


and provide a final look and feel to the GUI (Graphical User Interface).

● Behavior − These are the events which occur when the user interacts with UI
elements.
SWING - Component class
Every SWING controls inherits properties from the following Component class hierarchy.

● Component : A Component is the abstract base class for the non menu
user-interface controls of SWING. Component represents an object with
graphical representation.

● Container : A Container is a component that can contain other SWING


components

● JComponent : A JComponent is a base class for all SWING UI components.


In order to use a SWING component that inherits from JComponent, the
component must be in a containment hierarchy whose root is a top-level
SWING container
Hierarchy of Java Swing classes
Common Swing Controls

Here’s a categorized list of frequently used Swing controls:

🔹 Basic Controls
Core Swing Classes & Their Roles
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
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.
What is Event Handling?
Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs. This mechanism has a code which is known as an event
handler, that is executed when an event occurs.

Java uses the Delegation Event Model to handle the events. This model defines the
standard mechanism to generate and handle the events.

The Delegation Event Model has the following key participants.

Source − The source is an object on which the event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide us with
classes for the source object.

Listener − It is also known as event handler. The listener is responsible for


generating a response to an event. From the point of view of Java implementation, the
listener is also an object. The listener waits till it receives an event. Once the event is
received, the listener processes the event and then returns.
Core Swing Event Classes
SWING - KeyEvent Class
On entering the character the Key event is [Link] are three
types of key events which are represented by the integer constants.
KEY_PRESSED
KEY_RELASED
KEY_TYPED
KeyEventClass Methods
[Link]. Method & Description

char getKeyChar()
1
Returns the character associated with the key in this event.

int getKeyCode()
2
Returns the integer keyCode associated with the key in this event.

int getKeyLocation()
3
Returns the location of the key that originated this key event.

static String getKeyModifiersText(int modifiers)


4
Returns a String describing the modifier key(s), such as "Shift", or "Ctrl+Shift".

static String getKeyText(int keyCode)


5
Returns a String describing the keyCode, such as "HOME", "F1" or "A".
SWING - MouseEvent Class
This event indicates that a mouse action occurred in a component. This
low-level event is generated by a component object for Mouse Events and
Mouse motion events. This event is generated when −

A mouse button is pressed.


A mouse button is released.
A mouse button is clicked (pressed and released).
A mouse cursor enters the unobscured part of component's geometry.
A mouse cursor exits the unobscured part of component's geometry.
A mouse is moved.
A mouse is dragged.
[Link]. Method & Description

int getButton()
1
Returns which, if any, of the mouse buttons has changed state.

int getClickCount()
2
Returns the number of mouse clicks associated with this event.

Point getLocationOnScreen()
3
Returns the absolute x, y position of the event.

static String getMouseModifiersText(int modifiers)


4 Returns a String describing the modifier keys and mouse buttons that were down during the event,
such as "Shift", or "Ctrl+Shift".

Point getPoint()
5
Returns the x,y position of the event relative to the source component.

int getX()
6
Returns the horizontal x position of the event relative to the source component.

int getXOnScreen()
7
Returns the absolute horizontal x position of the event.

int getY()
8
Returns the vertical y position of the event relative to the source component.
SWING - Event Listeners
● 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.
SWING - Layouts
● Layout refers to the arrangement of components within the container.
● In another way, it could be said that layout is placing the components at a
particular position within the container.
● The task of laying out the controls is done automatically by the Layout
Manager.

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

● Defines five locations where a component or components


can be added:
● North, South, East, West, and Center
● The programmer specifies the area in which a component
should appear.
● The relative dimensions of the areas are governed by the
size of the components added to them.
GridLayout
● Components are placed in a grid with a user-specified number of
columns and rows.
● Each component occupies exactly one grid cell.
● Grid cells are filled left to right and top to bottom.
● All cells in the grid are the same size.
● Specifying zero for either rows or columns means any number of
items can be placed in that row or column.
CardLayout
● Components governed by a card layout are "stacked" such
that only one component is displayed on the screen at any
one time.
● Components are ordered according to the order in which they
were added to the container.
● Methods control which component is currently visible in the
container.
● CardLayouts might be appropriate for wizards (with the Next
>> buttons).
Swing Programs
Java Swing Example
import [Link].*;
public class Main extends [Link]{
public static void main(String args[]){
JFrame frame = new JFrame("Frame Title");
[Link](400,400);
[Link](true);
}
}
import [Link].*;
public class Main extends [Link]{
public static void main(String args[]){
JFrame frame = new JFrame("My Swing JLabel");
[Link](400,400);
JPanel panel = new JPanel();
JLabel heyImageLabel = new JLabel();
ImageIcon heyimageIcon = new
ImageIcon("C:\\Users\\Data\\Downloads\\hey_design.png");
[Link](heyimageIcon);
[Link](heyImageLabel);
[Link](panel);
[Link](true);
}
}
import [Link].*;
public class Main extends [Link]{
public static void main(String args[]){
JFrame frame = new JFrame("My Swing JTextField");
[Link](400,400);
JPanel panel = new JPanel();
JTextField textfield = new JTextField("Hey I am TextField, You can
edit me!");
[Link](textfield);
[Link](panel);
[Link](true);
}
}
write a program to illustrate the use of JFrame, JTextField and Jl-abel'

import [Link].*;
public class SwingExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Example - JFrame, JTextField, JLabel");
JLabel label = new JLabel("Enter your name:");
[Link](50, 50, 150, 30); // x, y, width, height
JTextField textField = new JTextField();
[Link](200, 50, 150, 30);
[Link](label);
[Link](textField);
[Link](400, 200);
[Link](null); // Using no layout manager, absolute positioning
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Question:

Write a Javaprogram that uses textfields and button. The first


textfield accept temperature in Celsius. When the 'Convert' button is
called the same textfield displays the tem@rture in Fahrenheit. Use
appropriate. Swing components and event handling techniques.
F{C*9 /5)+32
import [Link].*;
import [Link].*;

public class SimpleConverter


{
public static void main(String[] args)
{
JFrame frame = new JFrame("Temp Converter");
JLabel cLabel = new JLabel("Celsius:");
[Link](30, 30, 60, 25);
JTextField cField = new JTextField();
[Link](100, 30, 100, 25);

JLabel fLabel = new JLabel("Fahrenheit:");


[Link](30, 70, 80, 25);
JTextField fField = new JTextField();
[Link](100, 70, 100, 25);
[Link](false);
JButton button = new JButton("Convert");
[Link](80, 110, 100, 30);

// Simple ActionListener
[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
double c = [Link]([Link]());
double f = (c * 9 / 5) + 32;
[Link](f + "");
[Link]("Error"));
}
[Link](cLabel);
[Link](cField);
[Link](fLabel);
[Link](fField);
[Link](button);
[Link](250, 200);
[Link](null);
[Link](JFrame.EXIT_ON_CLO
SE);
[Link](true);
}
}
create a login page

import [Link].*;

public class LoginPage {


public static void main(String[] args) {
JFrame frame = new JFrame("Login Page");

// Labels
JLabel userLabel = new JLabel("Username:");
[Link](50, 50, 100, 30);
JLabel passLabel = new JLabel("Password:");
[Link](50, 100, 100, 30);

// Text fields
JTextField userField = new JTextField();
[Link](150, 50, 150, 30);
JPasswordField passField = new JPasswordField();
[Link](150, 100, 150, 30);
// Button
JButton loginButton = new JButton("Login");
[Link](150, 150, 100, 30);

// Add components to frame


[Link](userLabel);
[Link](userField);
[Link](passLabel);
[Link](passField);
[Link](loginButton);

// Frame settings
[Link](400, 250);
[Link](null); // Absolute positioning
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Add action to the button
// Action Listener for button
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = [Link]();
String password = new String([Link]());

// Simple check (username=admin, password=1234)


if ([Link]("admin") && [Link]("1234")) {
[Link](frame, "Login Successful!");
} else {
[Link](frame, "Invalid Username or Password",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
});

Note: before adding components

You might also like