Advanced GUI in Java - Unit - 13
Advanced GUI in Java - Unit - 13
DCA2106
JAVA PROGRAMMING
Unit: 13 - Advanced GUI in Java 1
DCA2106: Java Programming
Unit – 13
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 - -
3.1 BoxLayout - -
3.2 CardLayout - - 17 - 26
3.3 GroupLayout - -
3.4 SpringLayout - 2
4 Event Handling in Advanced Components - -
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:
• Create real-world, desktop-based Java applications that are intuitive, scalable, and maintainable.
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:
Selection Modes:
[Link](ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
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.
import [Link].*;
import [Link].*;
[Link](scrollPane, [Link]);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Output Description:
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:
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.
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.
Example Program:
import [Link].*;
import [Link].*;
[Link](scrollPane);
[Link](400, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Output Description:
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.
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:
[Link]("Home", panel1);
[Link]("Settings", panel2);
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:
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].*;
// Toolbar
JToolBar toolBar = new JToolBar();
[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:
These components contribute to better UI design and improved user navigation, making applications
easier to use and more intuitive.
Message Dialog:
JOptionPane.INFORMATION_MESSAGE);
Input Dialog:
Confirm Dialog:
import [Link].*;
Use Cases:
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.
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.
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:
Creating a BoxLayout:
import [Link].*;
import [Link].*;
[Link](new JLabel("Username:"));
[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:
Use Cases:
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.
Creating a CardLayout:
[Link](panel1, "Home");
[Link](panel2, "Profile");
To switch cards:
[Link](cardPanel, "Profile");
import [Link].*;
import [Link].*;
import [Link].*;
[Link](panel1, "Card1");
[Link](panel2, "Card2");
[Link](cardPanel);
[Link](300, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Output Description:
Use Cases:
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:
Basic Setup:
[Link](true);
[Link](true);
You can then define the horizontal and vertical layout using SequentialGroup and ParallelGroup.
import [Link].*;
import [Link].*;
[Link](
[Link]()
.addGroup([Link]([Link])
.addComponent(nameLabel)
.addComponent(emailLabel))
.addGroup([Link]([Link])
.addComponent(nameField)
.addComponent(emailField)
.addComponent(submitButton))
);
[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:
Use Cases:
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:
Basic Usage:
import [Link].*;
[Link](nameLabel);
[Link](nameField);
[Link](emailLabel);
[Link](emailField);
[Link](panel);
[Link](350, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Output Description:
Use Cases:
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.
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].*;
[Link](new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (![Link]()) {
[Link]("Selected: " + [Link]());
}
}
});
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
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.
import [Link].*;
import [Link].*;
import [Link].*;
String[][] data = {
{ "1", "Alice" },
{ "2", "Bob" },
{ "3", "Carol" }
};
[Link](350, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Best Practices:
if (response == JOptionPane.YES_OPTION) {
[Link]("Exiting...");
} else {
[Link]("Action cancelled.");
}
Explanation: The method returns YES_OPTION or NO_OPTION, which can be used in conditional
statements to handle user decisions.
Explanation: Input dialogs return a String. If the user cancels, null is returned.
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.
Use Cases:
Handling dialog events correctly ensures the application responds logically to user input and
maintains a smooth flow of interaction.
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.
import [Link].*;
import [Link].*;
[Link](e -> {
String text = [Link]();
[Link]("You entered: " + text);
});
[Link](panel);
[Link](350, 150);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
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:
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.
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.
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.
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].*;
[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.
Benefits:
JTabbedPane is ideal for applications with multiple related screens that users may want to access in
any order, such as settings, profiles, or dashboards.
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.
• 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:
Managing state ensures that all parts of the application stay synchronised and work together
seamlessly, improving both usability and reliability.
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.
[Link](e -> {
String name = [Link]();
[Link](name); // Store in shared object
[Link](mainPanel, "Summary"); // Switch panel
});
Integration Tips:
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.
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.
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.
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 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.
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.
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
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
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)
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)
10. REFERENCES
BOOKS
REFERENCES