UNIT – 4
Layout management
Layout management in Java controls how components (buttons, text fields, labels, etc.) are
arranged inside a container like a Frame, Panel, or JFrame. Instead of manually setting
positions, Java uses Layout Managers to automatically arrange components in a flexible and
platform-independent way.
Java provides layout managers in the AWT and Swing libraries.
Border Layout
BorderLayout is a layout manager in Java (AWT & Swing) that divides a container into five
regions:
North
South
East
West
Center
It is the default layout for JFrame.
Regions Explanation
Region Position Behavior
North Top Takes full width, preferred height
South Bottom Takes full width, preferred height
East Right Takes full height, preferred width
West Left Takes full height, preferred width
Center Middle Takes remaining space
If no constraint is given while adding a component, it goes to Center by default.
The window will show:
"North" button at the top
"South" button at the bottom
"East" button on the right
"West" button on the left
"Center" button in the middle (largest area)
FlowLayout
FlowLayout is a layout manager in Java that arranges components in a left-to-right flow,
similar to how words flow in a paragraph.
It is part of the [Link] package and is the default layout manager for JPanel.
📌 Concept of FlowLayout
Components are placed in a row from left to right.
When there is no more space, components automatically move to the next line.
Components are arranged in the order they are added.
Supports alignment options: LEFT, CENTER (default), RIGHT.
🔹 Constructors of FlowLayout
FlowLayout()
FlowLayout(int alignment)
FlowLayout(int alignment, int hgap, int vgap)
alignment → [Link], [Link], [Link]
hgap → horizontal gap between components
vgap → vertical gap between rows
🔹 Output
Buttons are arranged horizontally
If window size decreases, buttons move to the next row
Spacing between buttons is controlled by hgap and vgap
Grid Layout
GridLayout is a layout manager in Java that arranges components in a rectangular grid of
rows and columns.
It is part of the [Link] package.
📌 Concept of GridLayout
Divides the container into equal-sized cells.
Components are placed row by row (left to right).
All components have the same width and height.
No region concept like BorderLayout.
Components fill the entire container space.
👉 If one of rows or columns is set to 0, Java automatically calculates it based on the number
of components.
🔹 Constructors of GridLayout
GridLayout(int rows, int columns)
GridLayout(int rows, int columns, int hgap, int vgap)
rows → number of rows
columns → number of columns
hgap → horizontal gap
vgap → vertical gap
Output
The window is divided into 2 rows and 3 columns
6 buttons are placed evenly
All buttons are of equal size
Gaps of 10 pixels appear between rows and columns
ScrollPaneLayout in Java
ScrollPaneLayout is the layout manager used internally by JScrollPane in Swing.
It manages the position of:
Viewport
Horizontal Scroll Bar
Vertical Scroll Bar
Row Header
Column Header
Corner Components
It belongs to the [Link] package.
📌 Concept of ScrollPaneLayout
When you use a JScrollPane, Java automatically uses ScrollPaneLayout to arrange its
parts.
A JScrollPane contains:
Viewport → Displays the main component (like text area, table, etc.)
Vertical Scroll Bar → Appears when content exceeds height
Horizontal Scroll Bar → Appears when content exceeds width
Headers & Corners → Optional components
👉 You do not usually set ScrollPaneLayout manually.
👉 It works automatically inside JScrollPane.
🔹 Structure of JScrollPane
---------------------------------
| Column Header |
|--------------------------------|
| Row | Viewport | VScroll
|Head | |
|--------------------------------|
| Horizontal Scroll |
---------------------------------
Output
A window containing a text area
Vertical scrollbar appears automatically
Horizontal scrollbar appears if needed
Layout is handled internally by ScrollPaneLayout
Java Exception Handling
In Java, exception handling is a mechanism to handle runtime errors, allowing the normal
flow of a program to continue. Exceptions are events that occur during program execution
that disrupt the normal flow of instructions.
Basic try-catch Example
The try block contains code that might throw an exception,
The catch block handles the exception if it occurs.
class Geeks{
public static void main(String[] args) {
int n = 10;
int m = 0;
try {
int ans = n / m;
[Link]("Answer: " + ans);
} catch (ArithmeticException e){
[Link]("Error: Division by 0!");
}
}
}
Output
Error: Division by 0!
Finally Block
The finally block always executed whether an exception is thrown or not. The finally is used
for closing resources like db connections, open files and network connections, It is used after
a try-catch block to execute code that must run.
class FinallyExample {
public static void main(String[] args){
int[] numbers = { 1, 2, 3 };
try {
// This will throw ArrayIndexOutOfBoundsException
[Link](numbers[5]);
}
catch (ArrayIndexOutOfBoundsException e){
[Link]("Exception caught: " + e);
}
finally{
[Link]("This block always
executes.");
}
[Link]("Program continues...");
}
}
Output
Exception caught: [Link]:
Index 5 out of bounds for length 3
This block always executes.
Program continues...
throw and throws Keywords
1. throw: Used to explicitly throw a single exception. We use throw when something goes
wrong (or “shouldn’t happen”) and we want to stop normal flow and hand control to
exception handling.
class Demo {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Age must be 18 or
above");
}
}
public static void main(String[] args) {
checkAge(15);
}
}
Output:
Exception in thread "main" [Link]: Age must be 18 or above
at [Link]([Link])
at [Link]([Link])
2. throws: Declares exceptions that a method might throw, informing the caller to handle
them. It is mainly used with checked exceptions (explained below). If a method calls another
method that throws a checked exception, and it doesn’t catch it, it must declare that exception
in its throws clause
import [Link].*;
class Demo {
static void readFile(String fileName) throws IOException
{
FileReader file = new FileReader(fileName);
}
public static void main(String[] args){
try {
readFile("[Link]");
} catch (IOException e){
[Link]("File not found: " +
[Link]());
}
}
}
Output
File not found: [Link] (No such file or directory)
Internal Working of try-catch Block:
JVM executes code inside the try block.
If an exception occurs, remaining try code is skipped and JVM searches for a
matching catch block.
If found, the catch block executes.
Control then moves to the finally block (if present).
If no matching catch is found, the exception is handled by JVM’s default handler.
The finally block always executes, whether an exception occurs or not.
Note: When an exception occurs and is not handled, the program terminates abruptly and the
code after it, will never execute.
Java Exception Hierarchy
In Java, all exceptions and errors are subclasses of the Throwable class. It has two main
branches
1. Exception.
2. Error
The below figure demonstrates the exception hierarchy in Java:
Types of Java Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also
allows users to define their it's exceptions.
Exception
1. Built-in Exception
Built-in Exception are pre-defined exception classes provided by Java to handle common
errors during program execution. There are two type of built-in exception in java.
Checked Exception: These exceptions are checked at compile time, forcing the programmer
to handle them explicitly.
Unchecked Exception: These exceptions are checked at runtime and do not require explicit
handling at compile time.
2. User-Defined Exception
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called "user-defined Exceptions".
Methods to Print the Exception Information
printStackTrace(): Prints the full stack trace of the exception, including the name, message
and location of the error.
toString(): Prints exception information in the format of the Name of the exception.
getMessage() : Prints the description of the exception
Nested try-catch
In Java, you can place one try-catch block inside another to handle exceptions at multiple
levels.
public class NestedTryExample {
public static void main(String[] args) {
try {
[Link]("Outer try block");
try {
int a = 10 / 0; // This causes
ArithmeticException
} catch (ArithmeticException e) {
[Link]("Inner catch: " + e);
}
String str = null;
[Link]([Link]()); // This causes
NullPointerException
} catch (NullPointerException e) {
[Link]("Outer catch: " + e);
}
}
}
Output
Outer try block
Inner catch: [Link]: / by zero
Outer catch: [Link]: Cannot invoke
"[Link]()" because "<local1>" is null
Handling Multiple Exception
We can handle multiple type of exceptions in Java by using multiple catch
blocks, each catching a different type of exception.
try {
// Code that may throw an exception
} catch (ArithmeticException e) {
// Code to handle the exception
} catch(ArrayIndexOutOfBoundsException e){
// Code to handle the another exception
}catch(NumberFormatException e){
// Code to handle the another exception
}
Difference Between Exception and Error
Feature Exception Error
An event that occurs during
A serious problem that occurs
program execution, disrupting
Definition in the JVM, generally cannot
normal flow, which can be
be handled by the application.
handled using try-catch.
Package [Link] [Link]
Recoverable Yes, can be caught and handled. No, usually not recoverable.
IOException, SQLException, OutOfMemoryError,
Examples
ArithmeticException StackOverflowError
Model–View–Controller (MVC) Design Pattern
The Model–View–Controller (MVC) is a software architectural design pattern used to
separate an application into three interconnected components:
1. Model
2. View
3. Controller
This separation helps in organizing code, improving maintainability, reusability, and
scalability.
Model
The Model represents:
Data of the application
Business logic
Rules and validation
It is responsible for:
Storing data
Updating data
Notifying changes (in advanced frameworks)
📌 Example:
Student details in a database
Bank account balance
Product information
👉 Model does not know about View or Controller.
2️⃣ View
The View represents:
User Interface (UI)
What the user sees
It displays:
Data from the Model
Output results
📌 Example:
Form
Table
GUI window
Web page
👉 View does not contain business logic.
3️⃣ Controller
The Controller acts as a bridge between Model and View.
It:
Receives user input
Processes the input
Calls Model to update data
Selects appropriate View
📌 Example:
Button click handler
Form submission handler
🔁 Working of MVC
Step-by-step flow:
1. User interacts with View (e.g., clicks a button).
2. View sends request to Controller.
3. Controller processes input.
4. Controller updates Model.
5. Model changes data.
6. View displays updated data.
MVC Architecture Diagram
User
↓
View ↔ Controller ↔ Model
↑_________________________|
Output
Student Name: Ravi
Student Marks: 85
Student Name: Ravi
Student Marks: 95
✅ Advantages of MVC
✔ Separation of concerns
✔ Easy to maintain and test
✔ Reusable components
✔ Supports parallel development
✔ Scalable for large applications
❌ Disadvantages
✖ Slightly complex for small applications
✖ Requires more classes
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.
So, to summarise, Swing components are the interactive elements in
a Java application. We will see various Swing Components in this article
and see a few examples. Note that the examples are simple code
snippets. You can use them in your application and tailor them to suit your
application architecture.
Top 13 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.
Note: We would be using this image icon in further examples.
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_SEL
ECTION);
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.
Write a java program to diplay the string by using Jbutton Class.
Write a java program to create Username and Password by using JPasswordField with
ActionListener event.