Java Notes UNIT 4
Java Notes UNIT 4
Unit-5 Chapter-1
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.
Swing is a graphical user interface (GUI) toolkit within Java, forming a key part of the Java Foundation Classes (JFC). It
provides a comprehensive set of components for building desktop applications with rich and interactive user interfaces.
Platform Independence:
Unlike its predecessor, AWT (Abstract Window Toolkit), Swing components are entirely written in Java,
making them "lightweight" and ensuring a consistent look and feel across different operating systems
(Windows, macOS, Linux).
Swing allows developers to customize the visual appearance of their applications, offering various "look and
feel" options that can emulate native platform styles or provide unique custom designs.
MVC Architecture:
Swing components often employ a Model-View-Controller (MVC) architecture, separating the data (model),
its visual representation (view), and the user interaction logic (controller), promoting modularity and
maintainability.
Event Handling:
Swing uses a delegation event model for handling user interactions. This involves event sources
(components generating events), event objects (containing information about the event), and event listeners
(objects that respond to specific events).
Swing GUIs are built using a hierarchy of containers and components. Containers (e.g., JFrame, JPanel)
hold and organize other components, while components are the individual visual controls that users interact
with.
Layout Managers:
Swing provides various layout managers (e.g., FlowLayout, BorderLayout, GridLayout) to control the
positioning and sizing of components within containers, ensuring responsive and well-organized interfaces.
In essence, Swing empowers Java developers to create sophisticated and platform-independent desktop
applications with a high degree of control over the user experience.
Program:1
import [Link];
public class SimpleFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame("My First JFrame");
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
OutPut:
MVC architecture
MVC (Model-View-Controller) is an architectural pattern widely used in Java for building applications,
particularly web applications. It separates an application into three interconnected components, each with a
distinct responsibility:
Model:
Represents the application's data and business logic.
Handles data storage, retrieval, and manipulation (e.g., interacting with a database).
Examples in Java web applications include JSP files or templating engines like Thymeleaf.
Controller:
Acts as an intermediary between the Model and View.
Interprets the input and calls the appropriate methods in the Model to update data or perform operations.
In Java web applications, controllers are typically implemented using Servlets or frameworks like Spring
MVC.
How MVC Works in Java (General Flow):
A user interacts with the View (e.g., clicks a button on a web page).
The Controller processes the input and, if necessary, interacts with the Model to retrieve or update data.
The Model performs the requested operations and returns the results to the Controller.
The Controller then selects the appropriate View to display the updated information or results.
Separation of Concerns:
Clearly separates presentation, business logic, and data, making the application more organized and easier to
understand.
Maintainability:
Changes in one component (e.g., UI changes in the View) are less likely to impact other components,
simplifying maintenance.
Testability:
Each component can be tested independently, improving the overall testability of the application.
Reusability:
Model and Controller components can potentially be reused in different Views or applications.
Parallel Development:
Different teams or developers can work on the Model, View, and Controller components simultaneously.
JFrame:
A top-level window with a title bar, borders, and options for minimizing, maximizing, and closing.
JDialog:
A pop-up window typically used for displaying messages or getting specific input from the user.
JApplet:
A top-level container for applets embedded in web pages (though applets are largely deprecated now).
2. Intermediate Containers and Components: These are elements placed within top-level containers to
organize the layout and provide user interaction.
JComponent: The base class for most Swing components, providing common functionalities like pluggable
look and feel, accessibility support, and event handling.
JPanel: A general-purpose lightweight container used to group and organize other components within a
frame or dialog.
JButton: A push-button component that triggers an action when clicked.
JLabel: A component used to display uneditable text or images.
JTextField: A single-line text input field.
JPasswordField: A specialized text field for password entry, obscuring the input characters.
JTextArea: A multi-line text area for displaying or editing larger blocks of text.
JCheckBox: A component that allows the user to select or deselect an option.
JRadioButton: A component used in groups where only one option can be selected at a time.
JComboBox: A drop-down list that allows the user to select one item from a list.
JList: A component that displays a list of items from which the user can select one or more.
JTable: A component for displaying data in a tabular format.
JTree: A component for displaying hierarchical data in a tree-like structure.
JSlider: A component that allows the user to select a value by sliding a knob within a bounded interval.
JSpinner: A single-line input field that lets the user select a number or object value from an ordered
sequence using up/down arrows or direct input.
JMenuBar, JMenu, JMenuItem: Components used to create menu bars, menus within the menu bar, and
individual menu items within a menu.
JFileChooser: A dialog window that allows the user to select files or directories.
JOptionPane: Provides standard dialog boxes for displaying messages or prompting for input.
JProgressBar: Displays the progress of a task towards completion.
These components can be combined and arranged using various layout managers
(e.g., BorderLayout, FlowLayout, GridLayout, GridBagLayout) to create complex and visually appealing
user interfaces.
Program:
import [Link].*;
import [Link].*;
public class ChatFrameExample
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Chat Frame");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](400, 400);
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("FILE");
JMenu m2 = new JMenu("Help");
[Link](m1);
[Link](m2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 = new JMenuItem("Save as");
[Link](m11);
[Link](m22);
[Link]().add([Link], panel);
[Link]().add([Link], mb);
[Link]().add([Link], ta);
[Link](true);
}
}
OutPut:
These are the root windows of a Swing application and are typically heavyweight components, meaning they
rely on the underlying operating system's windowing system.
JFrame: The most common top-level container, representing a standard window with a title bar, minimize,
maximize, and close buttons.
JDialog: A top-level container used for creating dialog boxes, which are typically smaller, temporary
windows used for specific user interactions (e.g., confirmation, input).
JWindow: A simpler top-level container without a title bar or borders, often used for splash screens or
custom window designs.
JApplet: Used for creating applets that run within a web browser, although its use has significantly declined.
General-Purpose Containers:
These are lightweight components that can be placed within top-level containers or other general-purpose
containers to organize and manage the layout of components.
JPanel: A versatile and commonly used container for grouping components, applying different layout
managers, and creating sub-sections within a larger GUI.
JScrollPane: A container that provides scroll functionality to its contained component, useful when the
content exceeds the visible area.
JLayeredPane: Allows components to be placed on different "layers" within the same container, enabling
overlapping and z-order control.
JSplitPane: Divides a container into two resizable sections, allowing the user to adjust the division between
them.
JTabbedPane: Provides a way to organize multiple panels into a tabbed interface, where only one tab's
content is visible at a time.
Key characteristics of Swing containers:
Containment hierarchy:
Containers can hold other containers, creating a hierarchical structure for the GUI.
Layout Managers:
Containers use layout managers (e.g., BorderLayout, FlowLayout, GridLayout, GridBagLayout) to control
the positioning and sizing of their contained components.
Containers provide methods like add() and remove() to manage their child components.
1. BorderLayout
2. BoxLayout
3. CardLayout
4. FlowLayout
5. GridBagLayout
6. GridLayout
7. GroupLayout
8. SpringLayout
BorderLayout:-
Every content pane is initialized to use a BorderLayout. (As Using Top-Level Containers explains, the content
pane is the main container in all frames, applets, and dialogs.) A BorderLayout places components in up to
five areas: top, bottom, left, right, and center. All extra space is placed in the center area. Tool bars that are
created using JToolBar must be created within a BorderLayout container, if you want to be able to drag and
drop the bars away from their starting positions.
BoxLayout
The BoxLayout class puts components in a single row or column. It respects the components' requested maximum sizes
and also lets you align components.
CardLayout
The CardLayout class lets you implement an area that contains different components at different times.
A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel
(group of components) the CardLayout displays. An alternative to using CardLayout is using a tabbed pane,
which provides similar functionality but with a pre-defined GUI.
FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row,
starting a new row if its container is not sufficiently wide. Both panels in CardLayoutDemo,
shown previously, use FlowLayout..
GridBagLayout
GridBagLayout is a sophisticated, flexible layout manager. It aligns components by placing them within a grid
of cells, allowing components to span more than one cell. The rows in the grid can have different heights, and
grid columns can have different widths.
GridLayout
GridLayout simply makes a bunch of components equal in size and displays them in the requested number of
rows and columns.
GroupLayout
GroupLayout is a layout manager that was developed for use by GUI builder tools, but it can also be used
manually. GroupLayout works with the horizontal and vertical layouts separately. The layout is defined for
each dimension independently. Consequently, however, each component needs to be defined twice in the
layout. The Find window shown above is an example of a GroupLayout.
SpringLayout
SpringLayout is a flexible layout manager designed for use by GUI builders. It lets you specify precise
relationships between the edges of components under its control. For example, you might define that the left
edge of one component is a certain distance (which can be dynamically calculated) from the right edge of a
second component. SpringLayout lays out the children of its associated container according to a set of
constraints,
Unit-5 Chapter-2
The delegation event model is a pattern for handling events, particularly in GUIs, where an event source
(like a button) generates an event and "delegates" the processing to one or more registered
listeners. Listeners must register with the source to receive notifications, ensuring that only interested
objects handle events, which improves efficiency by separating event generation from event handling
logic. This model is fundamental to many GUI toolkits like AWT and Swing.
Key components
Event:
An object that describes a state change in the source, such as a button click or a mouse movement.
Event Source:
The object that generates the event when its internal state changes, such as a GUI component.
Event Listener:
An object that receives and processes events. Listeners must be registered with the source to receive
notifications.
How it works
1. A user action occurs on the event source (e.g., a user clicks a button).
2. The event source creates an event object to describe the action.
3. The source notifies all registered listeners by calling a specific method on the listener object, passing the
event object as an argument.
4. The listener then processes the event and performs the required action.
Benefits
Separation of concerns: It cleanly separates the code that generates the event (the user interface logic) from
the code that handles it (the application logic).
Efficiency: Notifications are sent only to listeners that have registered interest, eliminating the overhead of
older models where events were propagated up the hierarchy even if not handled.
Modularity: The design promotes more modular and organized code.
Event Source :-
An event source is a component or system that generates events, which can range from log data in a security
context to specific user actions in an application. In IT, event sources can be applications, servers, or
services that log activities like user logins or network connections. In web development, it can be an object
like a button that triggers an event when clicked, or a service like FullCalendar that uses a JSON feed as an
event source.
In IT and Security
Definition:
An IT asset that produces log events, which are then collected, analyzed, and used for monitoring and
security purposes.
Examples:
LDAP, Active Directory, and VPNs (provide user-related data)
A component that provides data for events, such as a data feed for a calendar, a user interface element, or a
function that generates events.
Examples:
A simple array of event objects
A JavaScript object used for server-sent events, establishing a persistent connection to a server to receive
updates in real-time.
Examples:
Receiving live social media status updates
An event is an immutable fact that represents a change in the domain, and the sequence of all these events is
the "source of truth" for the system's state.
Examples:
Instead of storing a bank account's current balance, you store events like fundsDeposited and fundsWithdrawn.
Event Listeners:-
In Java, event listeners are a core component of event handling, particularly in GUI programming with AWT
and Swing. They implement the Observer design pattern, allowing objects to "listen" for and respond to
specific events triggered by other objects (event sources).
Here's a breakdown of how event listeners work in Java:
1. Event Source:
An event source is an object that generates events. In GUI applications, this is typically a component like
a JButton, JTextField, or JFrame.
2. Event Object:
When an event occurs (e.g., a button click, a key press), an event object is created. This object encapsulates
information about the event, such as its source and specific details (e.g., mouse coordinates for
a MouseEvent). Event objects typically extend [Link].
3. Event Listener Interface:
An event listener is an object that implements a specific event listener interface from
the [Link] package (or [Link] for Swing-specific listeners). Examples include:
o ActionListener: For ActionEvent (e.g., button clicks).
A class implements the chosen listener interface and provides concrete implementations for its
methods. These methods are the "event handlers" that define the actions to be taken when the corresponding
event occurs.
5. Registration:
The implemented listener object is registered with the event source using a method
like addActionListener(), addMouseListener(), etc. This establishes the connection, so the event source
knows which listener to notify when an event happens.
Program:
import [Link].*;
import [Link];
import [Link];
setVisible(true);
}
Event Classes :-
In Java, event classes are central to handling events, particularly in Graphical User Interface (GUI)
applications developed using AWT or Swing. These classes represent different types of occurrences or
interactions that can happen within an application.
Core Principles:
[Link]:
This is the root class for all event state objects in Java. All event classes inherit from EventObject, which
provides a fundamental structure for events, including a reference to the source object that generated the event.
[Link]:
This class is the root for all AWT-specific events and their subclasses. It supersedes the
older [Link] class, which is now considered obsolete and maintained only for backward compatibility.
Common Event Classes (primarily from [Link] and [Link] packages):
ActionEvent: Generated when a user performs an action, such as clicking a button, selecting a menu item, or
pressing Enter in a text field.
MouseEvent: Triggered by mouse interactions like clicking, pressing, releasing, moving, or dragging the
mouse. It also includes events for the mouse wheel (MouseWheelEvent).
ItemEvent: Occurs when an item in a list, checkbox, or choice component is selected or deselected.
WindowEvent: Relates to window-level events, such as opening, closing, iconifying, deiconifying, activating,
or deactivating a window.
Purpose:
Event classes encapsulate information about an event, allowing the application to respond
appropriately. When an event occurs, an object of the corresponding event class is created and dispatched to
registered event listeners, which then process the event based on its type and properties.
Handling mouse and keyboard events in Java involves using event listeners and adapter classes from
the [Link] package.
Interfaces:
MouseListener: For events like mouse clicks, presses, releases, entering, and exiting a component.
For example,
Inside these methods, define the actions to be performed when the corresponding event occurs.
Register the listener with the component that will generate the events
using addMouseListener(this) and/or addMouseMotionListener(this).
Adapter Classes (Optional):
If you only need to handle a few specific mouse events, you can
extend MouseAdapter or MouseMotionAdapter instead of directly implementing the interfaces. This allows
you to override only the methods you need, avoiding the need to provide empty implementations for unused
methods.
import [Link];
import [Link];
import [Link];
import [Link];
@Override
public void mouseClicked(MouseEvent e)
{
[Link]("Mouse Clicked at: " + [Link]() + ", " + [Link]());
}
@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed at: " + [Link]() + ", " + [Link]());
}
@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released at: " + [Link]() + ", " + [Link]());
}
@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered!");
}
@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited!");
}
Interface:
o KeyListener: For events like key presses, releases, and typing.
Implementation:
o Implement the KeyListener interface in your class.
o Inside these methods, define the actions to be performed based on the key event. You can get the character
or key code of the pressed key using methods like [Link]() or [Link]().
o Register the listener with the component that will generate the events using addKeyListener(this). Note that
the component must be "focusable" for keyboard events to be captured.
Program Example (KeyListener):
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public KeyboardEventHandler()
{
JPanel panel = new JPanel();
label = new JLabel("Press any key!");
[Link](label);
add(panel);
@Override
public void keyPressed(KeyEvent e)
{
[Link]("Key Pressed: " + [Link]([Link]()));
}
@Override
public void keyReleased(KeyEvent e)
{
[Link]("Key Released: " + [Link]([Link]()));
}
@Override
public void keyTyped(KeyEvent e)
{
[Link]("Key Typed: " + [Link]());
}
Adapter classes in Java are abstract classes that provide empty, default implementations for all methods
defined in a corresponding listener interface. They are primarily used to simplify event handling in GUI
applications (like those built with AWT or Swing).
When you implement a listener interface directly, you are required to provide an implementation for all its
methods, even if you only care about a few specific events. Adapter classes eliminate this requirement.
Reducing Boilerplate Code:
By extending an adapter class, you only need to override the methods corresponding to the events you want
to handle, significantly reducing the amount of boilerplate code needed.
Example:
Consider the MouseListener interface, which has multiple methods
like mousePressed(), mouseReleased(), mouseClicked(), mouseEntered(), and mouseExited(). If you only
want to handle a mousePressed event, using MouseAdapter simplifies the process:
JavaProgram
import [Link];
import [Link];
In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is to group
classes that belong together, which makes your code more readable and maintainable.
To access the inner class, create an object of the outer class, and then create an object of the inner class:
Program:
class OuterClass
{
int x = 10;
class InnerClass
{
int y = 5;
}
}
// Outputs 15 (5 + 10)
Unlike a "regular" class, an inner class can be private or protected. If you don't want outside objects to
access the inner class, declare the class as private:
Example
class OuterClass
{
int x = 10;
private class InnerClass
{
int y = 5;
}
}
public class Main
{
public static void main(String[] args)
{
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass();
[Link](myInner.y + myOuter.x);
}
}
OutPut:
An inner class can also be static, which means that you can access it without creating an object of the outer
class:
class OuterClass
{
int x = 10;
// Outputs 5
Note: just like static attributes and methods, a static inner class does not have access to members of
the outer class.
One advantage of inner classes, is that they can access attributes and methods of the outer class:
class OuterClass
{
int x = 10;
class InnerClass
{
public int myInnerMethod()
{
return x;
}
}
}
// Outputs 10
Anonymous Inner Class in Java
Nested Classes in Java is prerequisite required before adhering forward to grasp about anonymous Inner
class. It is an inner class without a name and for which only a single object is created. An anonymous
inner class can be useful when making an instance of an object with certain "extras" such as overriding
methods of a class or interface, without having to actually subclass a class.
// Java program to demonstrate Need for
// Anonymous Inner class
interface Age
{
// Defining variables and methods
int x = 21;
void getAge();
}
class MyClass implements Age
{
@Override public void getAge()
{
// Print statement
[Link]("Age is " + x);
}
}
class GFG
{
public static void main(String[] args)
{
MyClass obj = new MyClass();
[Link]();
}
}
Output:
Age is 21
// Java Program to Demonstrate Anonymous inner class
// Interface
interface Age
{
int x = 21;
void getAge();
}
// Main class
class AnonymousDemo
{
public static void main(String[] args)
{
Age oj1 = new Age()
{
@Override public void getAge()
{
[Link]("Age is " + x);
}
}
[Link]();
}
}
Output: age is 21
// Main class
class MyThread {
Output
Main Thread
Child Thread
Type 2: Anonymous Inner class that implements an interface
We can also have an anonymous inner class that implements an interface. For
example, we also know that by implementing Runnable interface we can create a
Thread. Here we use an anonymous Inner class that implements an interface.
Example
// Java program to illustrate defining a thread
// Using Anonymous Inner class that implements an interface
// Main class
class MyThread {
Output
Main Thread
Child Thread
Type 3: Anonymous Inner class that defines inside method/constructor argument
Anonymous inner classes in method/constructor arguments are often used in
graphical user interface (GUI) applications. To get you familiar with syntax lets have a
look at the following program that creates a thread using this type of Anonymous
Inner class
Example
// Java program to illustrate defining a thread
// Using Anonymous Inner class that define inside argument
// Main class
class MyThread {
// Main driver method
public static void main(String[] args)
{
// Using Anonymous Inner class that define inside
// argument
// Here constructor argument
Thread t = new Thread(new Runnable() {
[Link]();
[Link]("Main Thread");
}
}
Output
Main Thread
Child Thread