0% found this document useful (0 votes)
3 views48 pages

Advanced GUI in Java - Unit - 13

Unit 13 of the Java Programming course focuses on advanced GUI development using the Swing toolkit, covering components like JList, JTable, JTabbedPane, and JOptionPane. It also discusses advanced layout managers and event handling for creating responsive and feature-rich desktop applications. The unit culminates in a case study that integrates these advanced elements into a cohesive multi-panel application.

Uploaded by

canadaapp10
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)
3 views48 pages

Advanced GUI in Java - Unit - 13

Unit 13 of the Java Programming course focuses on advanced GUI development using the Swing toolkit, covering components like JList, JTable, JTabbedPane, and JOptionPane. It also discusses advanced layout managers and event handling for creating responsive and feature-rich desktop applications. The unit culminates in a case study that integrates these advanced elements into a cohesive multi-panel application.

Uploaded by

canadaapp10
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

DCA2106: Java Programming

BACHELOR OF COMPUTER APPLICATIONS


SEMESTER 3

DCA2106
JAVA PROGRAMMING
Unit: 13 - Advanced GUI in Java 1
DCA2106: Java Programming

Unit – 13

Advanced GUI in Java

Unit: 13 - Advanced GUI in Java 2


DCA2106: Java Programming

TABLE OF CONTENTS
Fig No /
SL SAQ / Page
Topic Table /
No Activity No
Graph
1 Introduction - -
4-5
1.1 Objectives - -
2 Advanced Swing Components - -

2.1 JList and JScrollPane - -

2.2 JTable and Data Display - - 6 - 16

2.3 JTabbedPane and JToolBar 1 -

2.4 JOptionPane for Dialogs 2 1


3 Advanced Layout Managers - -

3.1 BoxLayout - -

3.2 CardLayout - - 17 - 26

3.3 GroupLayout - -

3.4 SpringLayout - 2
4 Event Handling in Advanced Components - -

4.1 Handling List and Table Events 3 -


27 - 34
4.2 Dialog Interaction Events 4 -

4.3 Dynamic Interface Updates 5 3


5 Case Study: Building a Multi-Panel Application - -

5.1 Designing the Interface - -

5.2 Navigation Using JTabbedPane - - 35 - 39

5.3 Managing State Across Panels - -

5.4 Integrating Components and Events - 4


6 Summary - - 40
7 Glossary - - 41 - 42
8 Terminal Questions - - 43
9 Answers - - 44 - 47
10 References - - 48

Unit: 13 - Advanced GUI in Java 3


DCA2106: Java Programming

1. INTRODUCTION
In the previous unit, the unit explained the fundamentals of GUI development in Java using the Swing
toolkit. We learned about the basics of graphical user interfaces, differences between AWT and Swing,
core Swing components like JLabel, JButton, and JTextField, and how to arrange them using layout
managers such as FlowLayout, BorderLayout, and GridLayout. We also explored how to build simple
interactive applications by integrating Swing components with Java’s event-handling model.

Building upon that foundation, this unit delves into more advanced aspects of Swing and GUI
development. We will explore a wider range of Swing components such as JList, JScrollPane, JTable,
JTabbedPane, and JOptionPane, which are used in professional desktop applications for handling data,
organising interface sections, and interacting with users more dynamically. Additionally, we will
cover more sophisticated layout managers like BoxLayout, CardLayout, GroupLayout, and
SpringLayout to achieve greater control and flexibility in UI design. This unit will also focus on how
to manage events in these complex components and culminate in a case study that brings together
advanced elements into a cohesive multi-panel Java Swing application. By the end of this unit, you will
be well-equipped to build responsive, feature-rich desktop applications with well-structured and
intuitive user interfaces.

1.1. Objectives
After studying this unit, you should be able to:

• Explain advanced Swing components such as


JList, JScrollPane, JTable, JTabbedPane, and
JOptionPane to create richer and more interactive
GUIs.
• Apply advanced layout managers like BoxLayout,
CardLayout, GroupLayout, and SpringLayout to
achieve flexible and professional user interface
designs.
• Demonstrate effective event handling for complex components such as lists, tables, and dialog
boxes.
• Design GUI applications with multiple panels and integrated layout functionalities
• Define dynamic interface updates and user interactions within advanced GUI structures.

Unit: 13 - Advanced GUI in Java 4


DCA2106: Java Programming

• Create real-world, desktop-based Java applications that are intuitive, scalable, and maintainable.

Unit: 13 - Advanced GUI in Java 5


DCA2106: Java Programming

2. ADVANCED SWING COMPONENTS


While basic Swing components like JButton and JTextField allow for simple user interactions,
advanced Swing components provide powerful tools for building more dynamic and data-rich
applications. Components such as JList, JTable, JTabbedPane, JToolBar, and JOptionPane are designed
to handle complex UI requirements, like displaying lists and tables, organising content in tabs,
offering dialogs, and improving user interaction. These components enable developers to create
professional-grade interfaces with greater functionality and a more intuitive user experience.

2.1. JList and JScrollPane


In Swing, components like JList and JScrollPane are essential for creating user interfaces that deal
with multiple data entries and large content areas. They enhance usability by allowing users to view
and select from lists and scroll through overflowing content within a defined space.

JList – Displaying a List of Items

A JList is a Swing component that displays a list of items in a vertical scrollable column. Users can
select one or more items from the list. It’s useful for presenting options like available files, color
choices, or settings.

Creating a JList:

String[] languages = { "Java", "Python", "C++", "JavaScript" };


JList<String> languageList = new JList<>(languages);

Selection Modes:

• SINGLE_SELECTION – Only one item can be selected.


• SINGLE_INTERVAL_SELECTION – Multiple adjacent items.
• MULTIPLE_INTERVAL_SELECTION – Any number of items.

[Link](ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

JScrollPane – Adding Scrollbars to Components

JScrollPane is used to wrap components like JList, JTable, or JTextArea when the content may exceed
the visible area. It automatically adds vertical and/or horizontal scrollbars as needed.

Using JScrollPane with JList:

Unit: 13 - Advanced GUI in Java 6


DCA2106: Java Programming

JScrollPane scrollPane = new JScrollPane(languageList);


This makes the list scrollable, especially useful when dealing with many items.

Example: JList with JScrollPane

import [Link].*;
import [Link].*;

public class JListScrollPaneExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JList with JScrollPane Example");

String[] fruits = { "Apple", "Banana", "Cherry", "Mango", "Orange", "Pineapple", "Grapes",


"Strawberry" };

JList<String> fruitList = new JList<>(fruits);


[Link](4);
[Link](ListSelectionModel.SINGLE_SELECTION);

JScrollPane scrollPane = new JScrollPane(fruitList);

[Link](scrollPane, [Link]);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

Output Description:

• Displays a list of fruits.


• Only 4 items are visible at a time.
• A vertical scrollbar allows users to scroll through all items.

Unit: 13 - Advanced GUI in Java 7


DCA2106: Java Programming

Use Cases:

• Selection menus
• Displaying lists of files, categories, or records
• Interfaces requiring vertical scrolling with limited space

Swing's JList and JScrollPane work together to provide a clean, efficient way to present multiple data
entries without cluttering the interface. Their combination enhances both functionality and user
experience.

The JList component in Swing is used to display a list of items from which the user can select one or
multiple entries. It supports both single and multiple selection modes, making it ideal for settings,
options, and simple data displays. However, when the list contains more items than can be viewed
comfortably within the available space, it should be embedded within a JScrollPane.

A JScrollPane provides a scrollable view of its contained component. When a JList is added to a
JScrollPane, vertical and/or horizontal scrollbars appear as needed, allowing users to navigate long
lists without overwhelming the interface.

Example:

String[] cities = { "Delhi", "Mumbai", "Kolkata", "Chennai", "Bangalore", "Hyderabad" };


JList<String> cityList = new JList<>(cities);
[Link](4);
JScrollPane scrollPane = new JScrollPane(cityList);

This combination ensures a neat layout while retaining accessibility to all list items. Together, JList
and JScrollPane offer a powerful way to present and manage selectable data in Java Swing
applications.

2.2. JTable and Data Display


The JTable component in Swing is used to display and manage tabular data, much like a spreadsheet.
It allows for the representation of data in rows and columns, making it a powerful tool for applications
that need to show structured information—such as inventories, student records, or transaction logs.

Each cell in a JTable can hold text, numbers, or even components like checkboxes. Tables can be
customised to support features such as sorting, editing, column resizing, and more. For large datasets,
JTable is typically placed inside a JScrollPane to provide scrollability.

Unit: 13 - Advanced GUI in Java 8


DCA2106: Java Programming

Creating a Simple JTable:

String[] columns = { "ID", "Name", "Age" };


String[][] data = {
{ "1", "Alice", "22" },
{ "2", "Bob", "25" },
{ "3", "Charlie", "28" }
};

JTable table = new JTable(data, columns);


JScrollPane scrollPane = new JScrollPane(table);

Example Program:

import [Link].*;
import [Link].*;

public class JTableExample {


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

String[] columns = { "ID", "Name", "Course" };


String[][] data = {
{ "101", "John", "Java" },
{ "102", "Sara", "Python" },
{ "103", "Mike", "C++" }
};

JTable table = new JTable(data, columns);


JScrollPane scrollPane = new JScrollPane(table);

[Link](scrollPane);
[Link](400, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

Unit: 13 - Advanced GUI in Java 9


DCA2106: Java Programming

Output Description:

• Displays a scrollable table with 3 rows and 3 columns.


• Columns: ID, Name, Course.
• Rows are automatically sized to fit the data.

Key Features of JTable:

• Column headers and row access.


• Single or multiple row selection.
• Editable and non-editable cells.
• Integration with TableModel for dynamic data.

Use Cases:

• Student gradebook
• Sales report
• Employee directory
• Any scenario involving structured data display

JTable is one of the most powerful components in Swing for working with data. Combined with
JScrollPane, it allows for scalable, responsive data representation suitable for both simple and
advanced applications.

2.3. JTabbedPane and JToolBar


Swing provides specialised components like JTabbedPane and JToolBar to enhance user interface
organisation and usability. These components help structure complex applications by separating
functionality into manageable sections and providing quick access to actions.

JTabbedPane – Organising Content with Tabs

Unit: 13 - Advanced GUI in Java 10


DCA2106: Java Programming

JTabbedPane allows developers to create tabbed panels, where each tab contains a different
component or interface. It is especially useful for applications with multiple sections like settings
screens, dashboards, or editors.

Creating a JTabbedPane:

JTabbedPane tabbedPane = new JTabbedPane();

JPanel panel1 = new JPanel();


[Link](new JLabel("Welcome to Tab 1"));

JPanel panel2 = new JPanel();


[Link](new JLabel("This is Tab 2"));

[Link]("Home", panel1);
[Link]("Settings", panel2);

ToolBar – Adding a Toolbar with Quick Actions

JToolBar is a component that provides a row (or column) of buttons and other elements for quick
access to common tasks, such as saving, opening files, or formatting text.

Creating a JToolBar:

JToolBar toolBar = new JToolBar();


[Link](new JButton("New"));
[Link](new JButton("Open"));
[Link](new JButton("Save"));

You can also add separators, combo boxes, or custom components to the toolbar. It can be placed at
the top, bottom, or sides of a window.

Example Program:

import [Link].*;
import [Link].*;

public class TabAndToolExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JTabbedPane and JToolBar Example");

// Toolbar
JToolBar toolBar = new JToolBar();

Unit: 13 - Advanced GUI in Java 11


DCA2106: Java Programming

[Link](new JButton("New"));
[Link](new JButton("Open"));
[Link](new JButton("Save"));

// Tabbed Pane
JTabbedPane tabs = new JTabbedPane();
[Link]("Dashboard", new JLabel("Dashboard Content"));
[Link]("Profile", new JLabel("Profile Settings"));
[Link]("Reports", new JLabel("Reports Area"));

[Link](new BorderLayout());
[Link](toolBar, [Link]);
[Link](tabs, [Link]);

[Link](400, 250);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

Output Description:

• A toolbar with "New", "Open", "Save" buttons at the top.


• A tabbed interface below it with 3 tabs: Dashboard, Profile, Reports.

Table 1: Use Cases of JTabbedPane and JToolBar

Component Use Case

Unit: 13 - Advanced GUI in Java 12


DCA2106: Java Programming

JTabbedPane Multi-page interfaces (e.g., settings, tools)


JToolBar Quick-access controls in editors, IDEs, etc.

These components contribute to better UI design and improved user navigation, making applications
easier to use and more intuitive.

2.4. JOptionPane for Dialogs


JOptionPane is a utility class in Swing used to create standard dialog boxes for interacting with users.
It provides an easy way to display messages, gather user input, and present options such as Yes/No,
OK/Cancel, or custom choices. These dialogs are essential in real-world applications for alerts,
confirmations, and user-driven decisions.

Table 2: Types of Dialogs in JOptionPane

Dialog Type Method Used Purpose


Message Dialog showMessageDialog() To display information
Input Dialog showInputDialog() To get user input
Confirm Dialog showConfirmDialog() To ask for confirmation (Yes/No/Cancel)
Option Dialog showOptionDialog() To customise options/buttons

Examples of Each Type:

Message Dialog:

[Link](null, "Operation Successful!", "Message",

JOptionPane.INFORMATION_MESSAGE);

Input Dialog:

String name = [Link]("Enter your name:");

Confirm Dialog:

int choice = [Link](null, "Do you want to save changes?", "Confirm",


JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
// Save changes
}

Unit: 13 - Advanced GUI in Java 13


DCA2106: Java Programming

Option Dialog (Custom):

String[] options = { "Red", "Blue", "Green" };


int result = [Link](
null,
"Choose a color:",
"Color Selector",
JOptionPane.DEFAULT_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]
);

Mini Example Application:

import [Link].*;

public class DialogExample {


public static void main(String[] args) {
int confirm = [Link](null, "Exit the application?", "Exit",
JOptionPane.YES_NO_OPTION);
if (confirm == JOptionPane.YES_OPTION) {
[Link](null, "Goodbye!", "Exit",
JOptionPane.INFORMATION_MESSAGE);
} else {
[Link](null, "Cancelled", "Stay", JOptionPane.WARNING_MESSAGE);
}
}
}

Unit: 13 - Advanced GUI in Java 14


DCA2106: Java Programming

Use Cases:

• Displaying status updates or error messages.


• Confirming user decisions (e.g., delete or exit).
• Collecting single-line input (like a username or email).
• Offering a set of choices in a compact dialog box.

JOptionPane simplifies interaction with users and promotes cleaner UI design by handling dialogs
with minimal code and maximum clarity. It's a must-know tool in any Java GUI developer’s toolkit.

SELF-ASSESSMENT QUESTIONS - 1
Fill in the Blanks:
1 The __________ component is used in Swing to display a scrollable list of items from which the
user can make one or more selections.
2 To make components like JList and JTable scrollable, we use the __________ container.
3 The __________ component is used to organise GUI content into tabs, making complex
interfaces more manageable.
4 __________ is a Swing component used to display tabular data in a grid of rows and columns.
5 To display dialog boxes such as confirmation or input prompts, Java Swing provides the
__________ utility class.
True or False:
6 JList allows only single item selection by default but can be configured for multiple selections.
7 JTable cannot be made scrollable because it does not support integration with JScrollPane.
8 JToolBar can be placed only at the top of a JFrame and nowhere else.

Unit: 13 - Advanced GUI in Java 15


DCA2106: Java Programming

9 JTabbedPane helps in switching between different panels within the same window without
creating new frames.
10 [Link]() is used to get user input via a dialog box.

Unit: 13 - Advanced GUI in Java 16


DCA2106: Java Programming

3. ADVANCED LAYOUT MANAGERS


As applications grow in complexity, organising components efficiently becomes essential. While basic
layouts like FlowLayout and BorderLayout are useful for simple interfaces, advanced layout
managers offer greater flexibility and control over component positioning. Managers such as
BoxLayout, CardLayout, GroupLayout, and SpringLayout help developers create dynamic, structured,
and responsive GUIs. These layouts are particularly useful in forms, wizards, tabbed panes, and
applications requiring adaptive layouts across different screen sizes.

3.1. BoxLayout
BoxLayout is an advanced layout manager in Swing that arranges components either vertically (top
to bottom) or horizontally (left to right), depending on the specified axis. Unlike simpler layouts like
FlowLayout, BoxLayout gives developers greater control over spacing, alignment, and nesting,
making it suitable for more refined and flexible UI designs.

Key Features:

• Components are stacked in a single row or column.


• You can use glue, struts, and rigid areas for custom spacing.
• Works well with Box, JPanel, or any container with setLayout().

Creating a BoxLayout:

[Link](new BoxLayout(container, BoxLayout.Y_AXIS)); // Vertical


[Link](new BoxLayout(container, BoxLayout.X_AXIS)); // Horizontal

Example: Vertical Form Using BoxLayout

import [Link].*;
import [Link].*;

public class BoxLayoutExample {


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

JPanel panel = new JPanel();


[Link](new BoxLayout(panel, BoxLayout.Y_AXIS));

[Link](new JLabel("Username:"));

Unit: 13 - Advanced GUI in Java 17


DCA2106: Java Programming

[Link](new JTextField(15));
[Link]([Link](10)); // Space between components
[Link](new JLabel("Password:"));
[Link](new JPasswordField(15));
[Link]([Link](15));
[Link](new JButton("Login"));

[Link](panel);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

Output Description:

• Components are stacked vertically.


• [Link]() adds fixed spacing.
• Clean layout ideal for login forms or vertical menus.

Useful Methods for Custom Spacing:

• [Link](int pixels) – Adds fixed vertical space.


• [Link](int pixels) – Adds fixed horizontal space.
• [Link](new Dimension(x, y)) – Adds fixed width & height.
• [Link]() – Pushes components apart (flexible spacing).

Use Cases:

• Vertical forms (login, registration, feedback)

Unit: 13 - Advanced GUI in Java 18


DCA2106: Java Programming

• Horizontal button bars or tool strips


• Sidebars and stacked menus

BoxLayout is a flexible alternative to grid-based layouts when you need precise control over
component stacking. Combined with spacing helpers like struts and glue, it enables clean and modern
GUI designs.

3.2. CardLayout
CardLayout is a powerful layout manager in Java Swing that allows you to stack multiple components
(usually panels) on top of each other like cards in a deck, where only one card is visible at a time. It is
ideal for building wizards, tab-like interfaces, and dynamic forms where the user navigates between
screens without opening new windows.

Key Features of CardLayout:

• Displays one component at a time.


• Components can be switched programmatically using a name or index.
• Useful for step-by-step workflows, like login → dashboard → settings.
• Works well with navigation buttons like "Next", "Back", and "Finish".

Creating a CardLayout:

CardLayout cardLayout = new CardLayout();


JPanel cardPanel = new JPanel(cardLayout);

You then add components using a unique string identifier:

[Link](panel1, "Home");
[Link](panel2, "Profile");

To switch cards:

[Link](cardPanel, "Profile");

Example: Switching Panels

import [Link].*;
import [Link].*;
import [Link].*;

Unit: 13 - Advanced GUI in Java 19


DCA2106: Java Programming

public class CardLayoutExample {


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

CardLayout cardLayout = new CardLayout();


JPanel cardPanel = new JPanel(cardLayout);

JPanel panel1 = new JPanel();


[Link](new JLabel("This is Card 1"));
JButton nextButton = new JButton("Next");
[Link](nextButton);

JPanel panel2 = new JPanel();


[Link](new JLabel("This is Card 2"));
JButton backButton = new JButton("Back");
[Link](backButton);

[Link](panel1, "Card1");
[Link](panel2, "Card2");

[Link](e -> [Link](cardPanel, "Card2"));


[Link](e -> [Link](cardPanel, "Card1"));

[Link](cardPanel);
[Link](300, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

Unit: 13 - Advanced GUI in Java 20


DCA2106: Java Programming

Output Description:

• Displays "Card 1" with a "Next" button.


• Clicking "Next" shows "Card 2", with a "Back" button to return.

Use Cases:

• Multi-step forms (e.g., sign-up wizards)


• Tab-like functionality without visible tabs
• Game UIs, settings panels, and dashboards

CardLayout simplifies the design of interfaces that require panel switching without creating new
windows or dialogs, improving user experience and maintaining a consistent layout.

3.3. GroupLayout
GroupLayout is an advanced and flexible layout manager introduced in Java SE 6, primarily designed
to simplify the process of designing complex user interfaces using tools like NetBeans GUI Builder. It
allows you to position components horizontally and vertically in groups, giving you precise control
over alignment and spacing.

Unlike simpler layouts that follow rows or grids, GroupLayout supports hierarchical component
arrangement, where components can be aligned based on shared baselines, sizes, or positions.

Key Features:

• Supports parallel and sequential grouping.


• Allows precise alignment and resizing behavior.
• Best used when designing forms with labels and input fields.
• Commonly used in form-based GUIs.

Basic Setup:

JPanel panel = new JPanel();

Unit: 13 - Advanced GUI in Java 21


DCA2106: Java Programming

GroupLayout layout = new GroupLayout(panel);


[Link](layout);

[Link](true);
[Link](true);

You can then define the horizontal and vertical layout using SequentialGroup and ParallelGroup.

Example: Simple Form with GroupLayout

import [Link].*;
import [Link].*;

public class GroupLayoutExample {


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

JLabel nameLabel = new JLabel("Name:");


JTextField nameField = new JTextField(15);
JLabel emailLabel = new JLabel("Email:");
JTextField emailField = new JTextField(15);
JButton submitButton = new JButton("Submit");

JPanel panel = new JPanel();


GroupLayout layout = new GroupLayout(panel);
[Link](layout);
[Link](true);
[Link](true);

[Link](
[Link]()
.addGroup([Link]([Link])
.addComponent(nameLabel)
.addComponent(emailLabel))
.addGroup([Link]([Link])
.addComponent(nameField)
.addComponent(emailField)
.addComponent(submitButton))

Unit: 13 - Advanced GUI in Java 22


DCA2106: Java Programming

);

[Link](
[Link]()
.addGroup([Link]([Link])
.addComponent(nameLabel)
.addComponent(nameField))
.addGroup([Link]([Link])
.addComponent(emailLabel)
.addComponent(emailField))
.addComponent(submitButton)
);

[Link](panel);
[Link](350, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

Output Description:

• Form layout with labels and fields aligned properly.


• Fields are aligned on the same line as labels.
• The "Submit" button is aligned beneath the fields.

Use Cases:

• Login and registration forms

Unit: 13 - Advanced GUI in Java 23


DCA2106: Java Programming

• Data entry forms with strict alignment


• Applications with complex component arrangements

Tip:

While GroupLayout offers precision, it is code-intensive to write manually. It is best used with GUI
builders like NetBeans, which generate the layout code automatically.

3.4. SpringLayout
SpringLayout is a flexible and low-level layout manager in Swing that allows you to position
components relative to each other and to the container edges using springs—objects that define
flexible spacing rules. Unlike other layout managers, SpringLayout gives developers fine-grained
control over the size and position of components, making it ideal for customised layouts where
standard alignment doesn't suffice.

Key Features:

• Allows you to explicitly define constraints between components.


• Springs can be fixed or elastic (adjustable).
• Suitable for dynamically sized layouts and complex UI arrangements.
• Offers precise positioning by defining relationships between components (e.g., “this label
should be 10 pixels to the right of that field”).

Basic Usage:

SpringLayout layout = new SpringLayout();


JPanel panel = new JPanel(layout);
You then use the putConstraint() method to define the positioning:
[Link]([Link], component1, 10, [Link], panel);
[Link]([Link], component1, 20, [Link], panel);

Example: Placing Two Labels and Text Fields

import [Link].*;

public class SpringLayoutExample {


public static void main(String[] args) {
JFrame frame = new JFrame("SpringLayout Example");
JPanel panel = new JPanel();

Unit: 13 - Advanced GUI in Java 24


DCA2106: Java Programming

SpringLayout layout = new SpringLayout();


[Link](layout);

JLabel nameLabel = new JLabel("Name:");


JTextField nameField = new JTextField(15);
JLabel emailLabel = new JLabel("Email:");
JTextField emailField = new JTextField(15);

[Link](nameLabel);
[Link](nameField);
[Link](emailLabel);
[Link](emailField);

// Constraints for nameLabel and nameField


[Link]([Link], nameLabel, 10, [Link], panel);
[Link]([Link], nameLabel, 25, [Link], panel);
[Link]([Link], nameField, 100, [Link], panel);
[Link]([Link], nameField, 25, [Link], panel);

// Constraints for emailLabel and emailField


[Link]([Link], emailLabel, 10, [Link], panel);
[Link]([Link], emailLabel, 60, [Link], panel);
[Link]([Link], emailField, 100, [Link], panel);
[Link]([Link], emailField, 60, [Link], panel);

[Link](panel);
[Link](350, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

Unit: 13 - Advanced GUI in Java 25


DCA2106: Java Programming

Output Description:

• Two rows: one for "Name" and one for "Email".


• Labels and fields are positioned explicitly using pixel offsets.

Use Cases:

• Custom dialog boxes


• Form layouts with non-standard spacing
• GUIs that require pixel-perfect positioning

Note:

While SpringLayout is powerful, it can become verbose and error-prone for large forms. It’s best
suited when other layout managers fall short in providing the required flexibility.

SELF-ASSESSMENT QUESTIONS - 2
Fill in the Blanks:
1 __________ arranges components either vertically or horizontally in a single row or column.
2 In CardLayout, only one component (or panel) is visible at a time, and switching is done using
the __________ method.
3 __________ allows precise alignment by grouping components horizontally and vertically, and is
ideal for complex form layouts.
4 __________ is a low-level layout manager that uses constraints (springs) to position
components relative to others.
5 In BoxLayout, you can add spacing between components using methods like
[Link]() or __________.
True or False:
6 BoxLayout supports both vertical and horizontal component arrangement depending on the
specified axis.
7 CardLayout is suitable for tabbed interfaces with visible tabs.
8 GroupLayout is designed to work best when layouts are created manually without any GUI
builder.
9 SpringLayout allows dynamic, rule-based positioning by defining relationships between
components.
10 CardLayout is commonly used for wizards or step-by-step interfaces.

Unit: 13 - Advanced GUI in Java 26


DCA2106: Java Programming

4. EVENT HANDLING IN ADVANCED COMPONENTS


As Swing applications become more interactive, handling events in advanced components like JList,
JTable, and dialog boxes becomes essential. These components generate specific events based on user
actions such as selections, clicks, or input. By using appropriate listener interfaces, developers can
respond to these actions dynamically—enabling behaviors like updating display information,
validating user choices, or triggering background processes. This section explores how to capture and
handle such events to build responsive and user-friendly interfaces.

4.1. Handling List and Table Events


In Java Swing, advanced components like JList and JTable support various types of user interaction
events. Proper event handling enables developers to capture user actions such as selecting items from
a list or clicking on a specific table row. These events are crucial for building responsive and
interactive GUI applications.

Handling JList Events (ListSelectionListener)

To respond to changes in a JList, such as when a user selects or deselects an item, you use the
ListSelectionListener interface.

import [Link].*;
import [Link].*;

public class JListEventExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JList Event Example");

String[] colors = { "Red", "Green", "Blue", "Yellow" };


JList<String> colorList = new JList<>(colors);
JLabel label = new JLabel("Selected: None");

[Link](new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (![Link]()) {
[Link]("Selected: " + [Link]());
}
}

Unit: 13 - Advanced GUI in Java 27


DCA2106: Java Programming

});

[Link](new JScrollPane(colorList), "Center");


[Link](label, "South");

[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

Handling JTable Events (ListSelectionListener or MouseListener)

For JTable, you can capture selection events when users click on rows or columns. You can also use a
MouseListener for more specific interactions like double-clicks.

Example – Row Selection:

import [Link].*;
import [Link].*;
import [Link].*;

public class JTableEventExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JTable Event Example");

String[][] data = {
{ "1", "Alice" },
{ "2", "Bob" },
{ "3", "Carol" }
};

Unit: 13 - Advanced GUI in Java 28


DCA2106: Java Programming

String[] columns = { "ID", "Name" };

JTable table = new JTable(data, columns);


JLabel label = new JLabel("Selected: None");

ListSelectionModel selectionModel = [Link]();


[Link](e -> {
if (![Link]()) {
int selectedRow = [Link]();
if (selectedRow != -1) {
String name = (String) [Link](selectedRow, 1);
[Link]("Selected: " + name);
}
}
});

[Link](new JScrollPane(table), "Center");


[Link](label, "South");

[Link](350, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

Table 3: Summary of JList and JTable

Component Event Listener Purpose


JList ListSelectionListener Track item selection

Unit: 13 - Advanced GUI in Java 29


DCA2106: Java Programming

JTable ListSelectionListener / MouseListener Detect row selection or clicks

Best Practices:

• Always check for ![Link]() to avoid redundant event triggers.


• Keep UI updates and business logic separate in event handlers.
• Use TableModel for more advanced table interactions and updates.

4.2. Dialog Interaction Events


In Swing, dialog boxes are used to interact with users through prompts, confirmations, and inputs.
While components like JOptionPane simplify dialog creation, handling user responses effectively is
critical for making decisions based on input or confirmation.

Understanding Dialog Interaction

Dialogs typically appear when the application needs:

• A confirmation (e.g., "Do you want to save?")


• A choice (e.g., "Choose a color")
• Input from the user (e.g., "Enter your name")

Each interaction returns a value that must be processed by the program.

Handling Confirm Dialog Events

int response = [Link](


null,
"Do you want to exit?",
"Confirm Exit",
JOptionPane.YES_NO_OPTION
);

if (response == JOptionPane.YES_OPTION) {
[Link]("Exiting...");
} else {
[Link]("Action cancelled.");
}

Unit: 13 - Advanced GUI in Java 30


DCA2106: Java Programming

Explanation: The method returns YES_OPTION or NO_OPTION, which can be used in conditional
statements to handle user decisions.

Handling Input Dialog Events

String name = [Link]("Enter your name:");


if (name != null && ![Link]()) {
[Link]("Hello, " + name + "!");
} else {
[Link]("No input provided.");
}

Explanation: Input dialogs return a String. If the user cancels, null is returned.

Handling Option Dialog Events (Custom Choices)

String[] options = { "Low", "Medium", "High" };


int selection = [Link](
null,
"Select priority:",
"Priority Setting",
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
options,
options[1]
);

if (selection != -1) {
[Link]("Selected: " + options[selection]);
}

Explanation: Custom options let you build more dynamic dialog interfaces and handle the user's
selection by index.

Table 4: Summary of Return Types

Dialog Type Return Type Used For


showConfirmDialog int (YES/NO) Confirming actions

Unit: 13 - Advanced GUI in Java 31


DCA2106: Java Programming

showInputDialog String Capturing simple user input


showOptionDialog int (index) Custom responses and selections

Use Cases:

• Saving or deleting confirmation


• Getting input like name, age, or email
• Selecting from multiple configuration choices

Handling dialog events correctly ensures the application responds logically to user input and
maintains a smooth flow of interaction.

4.3. Dynamic Interface Updates


In modern GUI applications, interfaces must often respond dynamically to user input or program
events. This involves updating components in real-time—such as changing labels, enabling/disabling
buttons, modifying tables, or switching panels—based on actions performed by the user.

Swing provides several ways to perform these dynamic interface updates, allowing the GUI to reflect
the current state of the application and improve the user experience.

Common Scenarios for Dynamic Updates:

• Showing or hiding panels based on selections


• Updating labels with input values
• Enabling/disabling buttons after validation
• Adding/removing elements from lists or tables
• Displaying different content without restarting the GUI

Example: Updating a Label Based on TextField Input

import [Link].*;
import [Link].*;

public class DynamicUpdateExample {


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

JTextField inputField = new JTextField(15);


JLabel displayLabel = new JLabel("Your input will appear here.");

Unit: 13 - Advanced GUI in Java 32


DCA2106: Java Programming

JButton updateButton = new JButton("Update");

[Link](e -> {
String text = [Link]();
[Link]("You entered: " + text);
});

JPanel panel = new JPanel();


[Link](inputField);
[Link](updateButton);
[Link](displayLabel);

[Link](panel);
[Link](350, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

Table 5: Other Dynamic Techniques

Technique Description
[Link](true/false) Show or hide a component dynamically
[Link](true/false) Enable or disable a button or field
[Link](); repaint(); Refresh layout after adding/removing components
[Link](container, "card") Switch between multiple views

Best Practices:

• Minimise UI flickering by grouping updates.


• Use [Link]() for updates from background threads.
• Avoid long operations on the Event Dispatch Thread (EDT)—use SwingWorker.

Unit: 13 - Advanced GUI in Java 33


DCA2106: Java Programming

Use Cases:

• Form validations (disabling the submit button until fields are filled)
• Real-time feedback (like password strength meters)
• Theme or layout switching
• Live search and filtering in tables or lists

Dynamic updates make the GUI responsive and intuitive, helping users interact with the application
efficiently and confidently.

SELF-ASSESSMENT QUESTIONS - 3
Fill in the Blanks:
1 __________ is the listener interface used to detect item selection changes in a JList.
2 To avoid handling duplicate or intermediate events, it is recommended to check __________
inside valueChanged() method.
3 In JTable, you can detect row selections using a ListSelectionListener or more specific
interactions with a __________.
4 The [Link]() method returns an __________ indicating the user's
decision.
5 To update a component's visibility during runtime, we can use the method
setVisible(__________).
True or False:
6 JList and JTable generate selection events that can be handled using ListSelectionListener.
7 Input dialogs created with [Link]() return a boolean value.
8 You must call revalidate() and repaint() when dynamically adding components to a
container.
9 MouseListener can be used to detect double-click events on a JTable row.
10 Swing components should always be updated on the main method thread, even during long-
running operations.

Unit: 13 - Advanced GUI in Java 34


DCA2106: Java Programming

5. CASE STUDY: BUILDING A MULTI-PANEL


APPLICATION
This section presents a practical example of creating a multi-panel GUI application using Swing. By
dividing the interface into separate panels—such as a welcome screen, input form, and summary
view—we can build structured and user-friendly applications. With the help of layout managers like
CardLayout and event handling, users can smoothly navigate between different sections of the
application within a single window.

5.1. Designing the Interface


In this section, we will learn how to design a simple application that uses multiple panels within a
single window. A multi-panel application divides the interface into separate sections, each
responsible for a specific task—such as displaying a welcome message, accepting user input, or
showing results.

To build such an application, we use JPanel for creating each panel and CardLayout to manage
switching between them. This layout allows only one panel to be visible at a time, making it ideal for
step-by-step interfaces.

For example, a basic application may include:

• A Home Panel that welcomes the user


• A Form Panel to enter information like name and age
• A Summary Panel to display the entered details

We also include navigation buttons such as "Next", "Back", and "Submit" to move between panels.
Each button responds to user actions using ActionListener.

Designing the interface this way makes the program easier to understand, maintain, and expand later
on.

5.2. Navigation Using JTabbedPane


JTabbedPane is a Swing component that allows users to navigate between different sections of an
application using tabs. Each tab corresponds to a separate panel, and only one panel is visible at a
time. It provides a simple and user-friendly way to organise multiple interfaces within a single
window.

Unit: 13 - Advanced GUI in Java 35


DCA2106: Java Programming

In a multi-panel application, JTabbedPane can be used to switch between forms, settings, and output
screens without writing complex layout-switching code. Each panel is added to the tabbed pane with
a title, and the user can switch views by clicking the tabs.

Example:

import [Link].*;

public class TabbedPaneExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Multi-Panel with JTabbedPane");

JTabbedPane tabbedPane = new JTabbedPane();

JPanel homePanel = new JPanel();


[Link](new JLabel("Welcome to the Home Panel"));

JPanel formPanel = new JPanel();


[Link](new JLabel("Enter your name:"));
[Link](new JTextField(10));

JPanel summaryPanel = new JPanel();


[Link](new JLabel("This is the Summary Panel"));

[Link]("Home", homePanel);
[Link]("Form", formPanel);
[Link]("Summary", summaryPanel);

[Link](tabbedPane);
[Link](350, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

Output Description:

• The application window displays three tabs: Home, Form, and Summary.
• Clicking each tab shows the corresponding panel content.

Unit: 13 - Advanced GUI in Java 36


DCA2106: Java Programming

Benefits:

• Easy to implement and manage.


• Automatically handles navigation through tabs.
• Keeps the user interface clean and organised.

JTabbedPane is ideal for applications with multiple related screens that users may want to access in
any order, such as settings, profiles, or dashboards.

5.3. Managing State Across Panels


In a multi-panel application, it is important to share and preserve data entered or selected by the user
as they move from one panel to another. This is known as managing state across panels. Without
proper state management, user input may be lost when switching views, resulting in a poor user
experience.

To manage state effectively, developers often use shared variables, objects, or data models that are
accessible to all panels. For example, if a user enters their name in one panel, that information should
be available in the summary panel later.

Common Techniques to Manage State:

• Shared Data Models: Store user input in a class or object that can be accessed by all panels.
• Passing Data Between Panels: Use setters and getters to pass values from one panel to another.
• Global Variables or Controller Classes: Store shared state in a central controller or static
variables (in simple applications).

Example:

class UserData {
String name;
int age;
// getters and setters
}

You can update this object in the form panel and then access the same object in the summary panel
to display the data.

Best Practices:

• Keep shared data in one central class.

Unit: 13 - Advanced GUI in Java 37


DCA2106: Java Programming

• Avoid using global variables unless the application is very small.


• Use listeners or observers if one panel needs to react when another updates data.

Managing state ensures that all parts of the application stay synchronised and work together
seamlessly, improving both usability and reliability.

5.4. Integrating Components and Events


In a multi-panel GUI application, integrating components with event handling is essential to make the
interface interactive and functional. This means linking buttons, input fields, and other components
with event listeners so that user actions lead to meaningful outcomes—such as switching panels,
validating inputs, or displaying messages.

By combining components like JButton, JTextField, JTable, and JTabbedPane with their respective
event listeners (e.g., ActionListener, ListSelectionListener), developers can build responsive
interfaces where each panel performs specific tasks and interacts with others.

Example Scenario:

Suppose you have a form panel where a user enters their name and clicks Submit. On clicking the
button, an ActionListener captures the input, stores it, and switches to a summary panel to display
the entered data.

Sample Code Snippet:

[Link](e -> {
String name = [Link]();
[Link](name); // Store in shared object
[Link](mainPanel, "Summary"); // Switch panel
});

Integration Tips:

• Use meaningful component names for clarity.


• Validate inputs before processing.
• Keep event-handling logic modular to avoid tightly coupled code.
• Use CardLayout or JTabbedPane to control panel transitions based on events.

Unit: 13 - Advanced GUI in Java 38


DCA2106: Java Programming

By integrating components and events effectively, you can build smooth, user-friendly applications
that respond to user input and guide them through multiple stages of interaction within a single
interface.

SELF-ASSESSMENT QUESTIONS - 4
Fill in the Blanks:
1 A __________ is used to manage switching between multiple panels within the same window by
displaying one at a time.
2 __________ allows users to switch between panels using tabbed navigation, displaying one
panel per tab.
3 To share data across multiple panels, developers often use a common __________ class to store
user input.
4 Navigation between panels in a CardLayout application is typically triggered by components
like __________.
5 To respond to user actions such as clicks or submissions, components must be registered
with an __________.
True or False:
6 In a multi-panel application, each panel typically serves a unique purpose, such as input,
display, or summary.
7 Using JTabbedPane requires writing custom logic to switch between tabs manually.
8 Data entered in one panel can be shared with others using a shared object or controller.
9 CardLayout requires multiple windows to be created and disposed for navigation.
10 Effective integration of components and events helps create a responsive and user-friendly
interface.

Unit: 13 - Advanced GUI in Java 39


DCA2106: Java Programming

6. SUMMARY
Let’s summarise this unit.

In this unit, we explored the advanced capabilities of Java Swing for building rich and professional
desktop applications. We started by examining advanced Swing components like JList, JScrollPane,
JTable, JTabbedPane, and JToolBar, which enabled us to create more interactive and data-driven
interfaces. We then studied JOptionPane, which provided easy ways to interact with users via
standard dialog boxes.

We moved on to understand advanced layout managers such as BoxLayout, CardLayout, GroupLayout,


and SpringLayout, gaining deeper control over the positioning and alignment of components within
user interfaces. These layout managers gave us the flexibility to design responsive and structured GUI
forms.

Further, we learned how to handle events in advanced components, particularly in JList and JTable,
and how to use dialogs and dynamic interface updates to respond to user actions. Finally, we
consolidated our learning through a practical case study that involved building a multi-panel
application. This exercise demonstrated how to integrate components, manage state across panels,
and design intuitive navigation using JTabbedPane.

Unit: 13 - Advanced GUI in Java 40


DCA2106: Java Programming

7. GLOSSARY
Financial Management is concerned with the procurement of the least cost funds, and its effective

A Java GUI toolkit that provides a rich set of components for building
Swing -
graphical user interfaces.

A Swing component used to display a list of items from which users can
JList -
select one or more options.

A container that provides a scrollable view of another component,


JScrollPane -
commonly used with lists, tables, or large text areas.

A Swing component that displays data in a tabular (rows and columns)


JTable -
format and allows data manipulation.

A container component that allows switching between multiple panels


JTabbedPane -
via tabs.

A Swing component that provides a row (or column) of tool buttons,


JToolBar -
typically used for quick access to commonly used functions.

A utility class used to create standard dialog boxes such as message,


JOptionPane -
input, confirm, and option dialogs.

An object that controls the size and position of components within a


Layout Manager -
container in Java Swing.

A layout manager that arranges components either vertically (Y-axis) or


BoxLayout -
horizontally (X-axis) in a single line.

A layout manager that treats each component as a card; only one card is
CardLayout -
visible at a time, making it suitable for multi-screen interfaces.

A powerful layout manager that arranges components hierarchically


GroupLayout - using parallel and sequential groups; commonly used in form-based
GUIs.

A flexible layout manager that allows explicit control over the


SpringLayout -
positioning of components using constraints called "springs."

Unit: 13 - Advanced GUI in Java 41


DCA2106: Java Programming

The process of responding to user actions (like clicks or selections) by


Event Handling -
attaching listeners to GUI components.

An interface used to receive notifications when a selection in a list or


ListSelectionListener -
table changes.

A generic container used to group related components together; often


Panel -
used with layout managers for organising the GUI.

The practice of storing and sharing data across multiple GUI


State Management -
components or panels to maintain continuity in user interaction.

Unit: 13 - Advanced GUI in Java 42


DCA2106: Java Programming

8. TERMINAL QUESTIONS
1. Explain the purpose and functionality of the JList component in Java Swing. How does it differ
from other list-type components?
2. What is the role of JScrollPane in Java Swing applications? Illustrate with an example how it is
used in combination with JList.
3. Compare and contrast the selection modes available in JList. Provide use cases where each mode
is appropriate.
4. Describe how a JTable is created and explain its main features. What kind of applications benefit
most from using JTable?
5. Write a Java program that displays a scrollable table using JTable and JScrollPane. Include at least
three columns and five rows of data.
6. What is JTabbedPane and how does it improve user interface design in Swing applications?
Provide a scenario where it is most effectively used.
7. How does a JToolBar enhance the usability of desktop applications? Demonstrate its use with a
code snippet.
8. What are the different types of dialog boxes supported by JOptionPane? Explain each type with
example usage.
9. Compare the layout managers BoxLayout, CardLayout, GroupLayout, and SpringLayout. Highlight
the strengths and ideal use cases for each.
10. Develop a Java GUI using BoxLayout that includes a username field, a password field, and a login
button arranged vertically.
11. Explain how CardLayout can be used to manage multiple panels in a single window. Provide an
example with navigation controls.
12. What are the benefits and challenges of using GroupLayout in Swing applications? When would
you choose it over simpler layout managers?
13. How does SpringLayout differ from other layout managers? Write a small program that positions
two text fields using SpringLayout.
14. Describe how event handling works in JList and JTable. Include the types of events they generate
and how you would respond to them.
15. In a multi-panel application using CardLayout, how would you manage the user’s input across
different panels? Explain with reference to state management techniques.

Unit: 13 - Advanced GUI in Java 43


DCA2106: Java Programming

9. ANSWERS
Self-Assessment Questions
Self-Assessment Questions - 1

1. JList
2. JScrollPane
3. JTabbedPane
4. JTable
5. JOptionPane
6. True
7. False
8. False
9. True
10. True

Self-Assessment Questions - 2

1. BoxLayout
2. show()
3. GroupLayout
4. SpringLayout
5. [Link]()
6. True
7. False
8. False
9. True
10. True

Self-Assessment Questions - 3

1. ListSelectionListener
2. [Link]()
3. MouseListener
4. int

Unit: 13 - Advanced GUI in Java 44


DCA2106: Java Programming

5. true/false
6. True
7. False
8. True
9. True
10. False

Self-Assessment Questions - 4

1. CardLayout
2. JTabbedPane
3. data model / shared object
4. JButton
5. ActionListener
6. True
7. False
8. True
9. False
10. True

Terminal Questions Answers


1. JList is a Swing component used to display a scrollable list of items. It supports both single and
multiple selection modes, making it suitable for options menus, selection panels, or categorised
lists. Compared to simpler list-type components, JList provides more flexibility, visual
customisation, and user interaction support.
(Ref: Section 2.1)
2. JScrollPane enables scrolling for components whose content exceeds the visible area. When used
with JList, it allows users to scroll through items without expanding the interface size. For example,
wrapping a JList in a JScrollPane is essential when displaying long lists of data in a compact view.
(Ref: Section 2.1)
3. JList supports three selection modes: SINGLE_SELECTION (select only one item),
SINGLE_INTERVAL_SELECTION (select multiple adjacent items), and
MULTIPLE_INTERVAL_SELECTION (select any number of items). These modes offer flexibility
depending on whether the user needs to choose one, a range, or non-adjacent items.
(Ref: Section 2.1)

Unit: 13 - Advanced GUI in Java 45


DCA2106: Java Programming

4. JTable is a Swing component used to display structured tabular data with rows and columns. It
supports features like cell editing, row selection, and scrollability via JScrollPane. Applications
such as inventory systems, employee databases, and financial reports benefit from using JTable
for clear data presentation.
(Ref: Section 2.2)
5. To create a scrollable table, instantiate JTable with a 2D data array and a column array, and wrap
it in a JScrollPane. Add the scroll pane to a JFrame and set visible rows and columns. This structure
allows for a compact, organised display of tabular information.
(Ref: Section 2.2)
6. JTabbedPane organises interface content using tabs. Each tab corresponds to a panel, allowing
users to switch between views without changing the window. It's useful in applications like
settings, dashboards, or editors where logical separation of features enhances usability and
reduces clutter.
(Ref: Section 2.3)
7. JToolBar offers a row of buttons and other interactive components for quick access to common
functions. Positioned at the top, bottom, or sides of a window, toolbars improve productivity by
reducing the number of clicks needed to perform frequent actions like open, save, or edit.
(Ref: Section 2.3)
8. JOptionPane supports various dialog types: showMessageDialog() (display messages),
showInputDialog() (get user input), showConfirmDialog() (confirm user decisions), and
showOptionDialog() (custom button options). These dialogs enhance user interaction by handling
input, feedback, and confirmations with minimal code.
(Ref: Section 2.4)
9. BoxLayout arranges components in vertical or horizontal stacks; CardLayout stacks panels and
displays one at a time for wizards or forms; GroupLayout aligns components in sequential or
parallel groups for precise control; and SpringLayout positions components relative to each other
for pixel-level adjustments.
(Ref: Sections 3.1 – 3.4)
10. Using BoxLayout, components like JLabel, JTextField, and JButton can be vertically stacked in a
JPanel. Adding vertical spacing with [Link]() makes the layout cleaner and ideal
for login or form-based interfaces.
(Ref: Section 3.1)

Unit: 13 - Advanced GUI in Java 46


DCA2106: Java Programming

11. CardLayout manages multiple panels by displaying only one at a time. You can switch between
them using show() with a card name. This is ideal for step-by-step workflows like signup forms
or multi-screen applications controlled by navigation buttons.
(Ref: Section 3.2)
12. GroupLayout offers precise alignment and sizing of components, making it ideal for complex,
form-based UIs. Its main advantage is layout flexibility, but it can be verbose and is best used with
GUI builders like NetBeans to avoid manual coding errors.
(Ref: Section 3.3)
13. SpringLayout uses constraint-based positioning to place components relative to each other or the
container. It provides fine control over layout and spacing. For example, two JTextField
components can be placed with pixel-defined distance from labels using putConstraint().
(Ref: Section 3.4)
14. Event handling in JList uses ListSelectionListener to detect item selections. For JTable, both
ListSelectionListener (for row selections) and MouseListener (for mouse events) are used. These
listeners allow dynamic responses like updating labels or triggering calculations.
(Ref: Section 4.1)
15. To manage state across panels using CardLayout, shared data objects (e.g., a UserData class) can
be used. Panels update and retrieve data from this shared model using setters/getters, ensuring
user input is preserved across views. This keeps the interface consistent and responsive.
(Ref: Section 5.3)

Unit: 13 - Advanced GUI in Java 47


DCA2106: Java Programming

10. REFERENCES
BOOKS

• Head First Java by Kathy Sierra & Bert Bates


• Java: A Beginner's Guide by Herbert Schildt
• Introduction to Java Programming and Data Structures by Y. Daniel Liang
• Core Java Volume I – Fundamentals by Cay S. Horstmann
• Thinking in Java by Bruce Eckel

REFERENCES

• Head First Java, 3rd Edition — Kathy Sierra, Bert Bates-


[Link]
• Head First Java — Kathy Sierra, Bert Bates (eBook)- [Link]
us/book/210574751/head-first-java/kathy-sierra/
• Head First Java, Second Edition — Kathy Sierra, Bert Bates-
[Link]
cond_Edition.pdf
• Head First Java — Kathy Sierra, Bert Bates (Google Books)-
[Link]

Unit: 13 - Advanced GUI in Java 48

You might also like