[go: up one dir, main page]

0% found this document useful (0 votes)
5 views143 pages

Swing

Uploaded by

wel24065
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)
5 views143 pages

Swing

Uploaded by

wel24065
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
You are on page 1/ 143

(SWING)

JAVA GUI
HOME

BY
Maryam O. Albosyifi
Introduction to Swing
Introduction to Swing
What is Swing?

A part of Java Foundation Classes (JFC).

A lightweight GUI toolkit for building desktop applications.


Introduction

Provides platform-independent, rich graphical interfaces.

It is built on the top of AWT (Abstract Windowing Toolkit).

Paints GUI controls itself pixel-by-pixel

Does not delegate to OS’s window system

OO design
About the JFC and Swing
JFC is short for Java Foundation Classes, which includes a
group of features for building graphical user interfaces
(GUIs) and adding rich graphics functionality .
Introduction to Swing
Key Features of Java Swing

Platform Independence: One of the primary advantages of Swing is its platform independence.

Rich Set of Components: Swing offers a wide range of components that can be used to create complex
Introduction

GUIs.

Customizability: Swing components are highly customizable, allowing developers to control various aspects

of their appearance and behavior. Properties such as size, color, font.

Event Handling: Swing provides a robust event handling mechanism that allows developers to respond to

user interactions.

Layout Managers: Swing includes a set of layout managers that facilitate the arrangement of components

within a container.
Introduction to Swing
Swing Hierarchy
Introduction
Basic Swing Components
Swing components

Swing provides a comprehensive set of components for building GUIs, including buttons, text fields,
panels, and more. These components are highly customizable, allowing developers to create visually
Swing Components

appealing and user-friendly interfaces.

Hierarchy of Swing Components:

Swing components extend the javax.swing package. Below is a simplified hierarchy:

java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ Various Swing components (JButton, JLabel, etc.)
Basic Swing Components
List of Common Swing Components

Component Description
JFrame A top-level container that represents a window with decorations like a title bar and close button.
Swing Components

JPanel A general-purpose container for holding and organizing components.


JButton A push button that can trigger an action when clicked.
JLabel A component used to display static text or images.
JTextField A single-line text input field.
JPasswordField A text field for password input that hides characters entered by the user.
JTextArea A multi-line area for text input or display.
JCheckBox A toggle button that can be checked or unchecked.
JRadioButton A button that is part of a group, allowing only one selection at a time.
JComboBox A drop-down list for selecting one item from a list.
JList A component to display a list of items for selection.
JTable A table component to display and edit tabular data.
JTree A hierarchical tree view component.
JScrollPane A container that adds scroll bars to another component.
JTabbedPane A container that allows tabbed navigation between components.
Basic Swing Components
List of Common Swing Components

Component Description
Swing Components

JMenuBar A menu bar for adding menus and submenus to a GUI.


JToolBar A movable toolbar with buttons and other controls.
JSlider A component for selecting a value by sliding a knob along a track.
JProgressBar A component to show progress for a task.
JDialog A pop-up dialog box for messages, input, or custom interactions.
JFileChooser A dialog box for file selection.
JSpinner A component for selecting a value by incrementing or decrementing it.
Basic Swing Components
JFrame in Java Swing

Definition :A top-level container used to create a main application window


Hierarchy:
Swing Components

java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ java.awt.Window
↳ java.awt.Frame
↳ javax.swing.JFrame
Constructors of Jframe
JFrame():
Creates a new, initially invisible frame with no title.
JFrame(String title)
Creates a new, initially invisible frame with the specified title.
Basic Swing Components
Key Features of Jframe:
Swing Components

Top-Level Container: Serves as the main window for applications.

Resizable and Movable: Users can resize or move the window.

Customizable: Supports adding Swing components like buttons, labels, panels, etc.

Integrated Menu Bar: Can include a JMenuBar.

Default Close Operation: Specify behavior when the window is closed (e.g., exit the application,

hide the frame).


Basic Swing Components
Common Methods of JFrame

Method Description
Swing Components

setTitle(String title) Sets the title of the frame.


setSize(int width, int height) Sets the size of the frame.
setDefaultCloseOperation(int operation) Defines the operation on close (e.g., EXIT_ON_CLOSE).
setLayout(LayoutManager mgr) Sets the layout manager for the frame.
add(Component comp) Adds a component to the frame.
setVisible(boolean b) Shows or hides the frame.
setResizable(boolean resizable) Enables or disables resizing of the frame.
setLocation(int x, int y) Sets the location of the frame relative to the screen.
Basic Swing Components
Practical Example: Simple JFrame
Swing Components

The output:
Basic Swing Components
Example: JFrame with Multiple Components
Swing Components

The output:
Basic Swing Components
Example: JFrame with Multiple Components

The output:
Swing Components
Basic Swing Components
setDefaultCloseOperation Method in Jframe

The setDefaultCloseOperation method in Java Swing is used to specify the behavior of a JFrame when
Swing Components

the user closes the window. This method determines what happens to the application when the close
button (usually represented by an "X" at the top-right corner of the window) is clicked.

Method Signature:
public void setDefaultCloseOperation(int operation)
Parameter:

Operation An integer constant specifying the close behavior. It can take one of the following values
defined in javax.swing.WindowConstants:
Basic Swing Components
Constant Description
JFrame.EXIT_ON_CLOSE Exits the application when the frame is closed. This terminates the JVM.
Hides the frame when the close button is clicked (default behavior if not
JFrame.HIDE_ON_CLOSE
explicitly set).
Swing Components

Disposes of the frame, releasing all its resources but keeps the application
JFrame.DISPOSE_ON_CLOSE
running if other frames are open.
Prevents any action from being taken when the frame is closed. Typically
JFrame.DO_NOTHING_ON_CLOSE
used with custom close handling.

Explanation of Constants:
EXIT_ON_CLOSE:
• Ends the application and stops the JVM when the frame is closed.
• Use this option when the frame is the main window of your application.
HIDE_ON_CLOSE:
• The frame becomes invisible, but the application continues to run.
• Useful if you want to show the frame again later without recreating it.
Basic Swing Components

DISPOSE_ON_CLOSE:
Releases resources used by the frame and removes it from memory.
The application continues to run if other windows are open.
Swing Components

Ideal for closing secondary windows.


DO_NOTHING_ON_CLOSE:
Prevents the frame from closing when the close button is clicked.
Use this option to implement custom close behavior (e.g., showing a confirmation dialog).

Default Behavior

If setDefaultCloseOperation is not explicitly called, the default behavior is HIDE_ON_CLOSE.


Basic Swing Components
Examples: 1. Using EXIT_ON_CLOSE When the user clicks the
close button, the application
will terminate.
Swing Components

The output:
Basic Swing Components
Examples: 2. Using DISPOSE_ON_CLOSE
When the window is closed, its
resources are released, but
the JVM remains running if
other windows are open.
Swing Components

The output:
Basic Swing Components
JPanel in Java Swing

Definition :JPanel is a generic container in Java Swing used to group and organize other Swing
Swing Components

components. It provides a flexible space for laying out components, It doesn't have borders or
titles by default but can be customized.
Hierarchy:
java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.JPanel
Basic Swing Components
JPanel in Java Swing

Constructors of JPanel
Swing Components

JPanel():
Creates a panel with a default FlowLayout.
JPanel(LayoutManager layout):
Creates a panel with the specified layout manager.
JPanel(boolean isDoubleBuffered):
Creates a panel with default FlowLayout and enables or disables double buffering.
JPanel(LayoutManager layout, boolean isDoubleBuffered):
Creates a panel with the specified layout and double buffering option.
Basic Swing Components
JPanel in Java Swing

Key Features
Swing Components

Lightweight:
Designed to group components without heavy resource consumption.
Flexible Layouts:
Can use various layout managers to organize its child components.
Customizable Appearance:
Supports borders, backgrounds, and custom painting.
Nested Panels:
Can contain other JPanel instances for hierarchical layouts.
Basic Swing Components
JPanel in Java Swing

Common Methods:
Swing Components

Method Description
add(Component comp) Adds a component to the panel.
setLayout(LayoutManager mgr) Sets the layout manager for the panel.
getLayout() Returns the current layout manager.
setBackground(Color bg) Sets the background color of the panel.
setBorder(Border border) Sets the border for the panel.
paintComponent(Graphics g) Overrides this method for custom rendering of the panel's content.
repaint() Repaints the panel to reflect any changes.
Basic Swing Components
Examples: 1: Simple JPanel with Default Layout
Swing Components

The output:
Basic Swing Components
Examples: 2: JPanel with BorderLayout and Nested Panels
Swing Components
Basic Swing Components
Examples: 2: JPanel with BorderLayout and Nested Panels

The output:
Swing Components
Basic Swing Components
Examples: 3: JPanel with Custom Painting
Swing Components

The output:
Basic Swing Components
JDialog in Java Swing

Definition:
Swing Components

JDialog is a part of Swing and is used to create dialog boxes in desktop applications. It is a subclass of
Dialog in AWT and is lightweight and platform-independent. JDialog provides more flexibility and
features than its AWT counterpart.

Hierarchy:
java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ java.awt.Window
↳ java.awt.Dialog
↳ javax.swing.JDialog
Basic Swing Components
JDialog in Java Swing

Constructors of Jpanel:
JDialog():
Swing Components

Creates a modeless dialog with no parent frame and no title.


JDialog(Frame owner):
Creates a modeless dialog with the specified owner frame.
JDialog(Frame owner, boolean modal):
Creates a dialog with the specified owner frame and modality.
JDialog(Frame owner, String title):
Creates a modeless dialog with the specified owner frame and title.
JDialog(Frame owner, String title, boolean modal):
Creates a dialog with the specified owner frame, title, and modality.
JDialog(Dialog owner, String title, boolean modal):
Creates a dialog with another dialog as its owner.
Basic Swing Components
JDialog in Java Swing

Key Features:
Swing Components

Modal and Modeless: Can block interaction with other windows (modal) or allow it (modeless).

Customizable: Supports adding components like labels, buttons, text fields, etc.

Resizable: Can be resizable or fixed, depending on the requirements.

Parent Association: Typically linked to a parent Frame or JFrame.


Basic Swing Components
JDialog in Java Swing

Common Methods:
Swing Components

Method Description
setModal(boolean modal) Sets whether the dialog is modal or modeless.
setTitle(String title) Sets the title of the dialog.
setSize(int width, int height) Sets the size of the dialog.
setVisible(boolean b) Makes the dialog visible or invisible.
setDefaultCloseOperation(int op) Sets the default close operation for the dialog.
add(Component comp) Adds a component to the dialog.
setLocationRelativeTo(Component c) Positions the dialog relative to another component.
dispose() Releases all resources used by the dialog and hides it.
Basic Swing Components
JDialog in Java Swing

Usage of Jdialog:
Swing Components

Informational Messages: Display important information to the user.

Input Forms: Collect user input in a separate window.

Custom Pop-Ups: Create custom dialog boxes for specific tasks.


Basic Swing Components
Examples: 1: Simple Modal JDialog
Swing Components

The output:
Basic Swing Components
Examples: 2: Modeless JDialog
Swing Components

The output:
Basic Swing Components
Example 3: JDialog for User Input
Swing Components

The output:
Basic Swing Components
JLabel in Java Swing

Definition:
Swing Components

JLabel is a component in the Swing library used to display a short string or an image icon. It is
commonly used to provide descriptive text for other components (e.g., text fields, buttons) or to
display information to the user.

Hierarchy:
java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.JLabel
Basic Swing Components

Constructors:
JLabel provides several constructors for creating labels with or without text or images:
Swing Components

Constructor Description
JLabel() Creates an empty label.
JLabel(String text) Creates a label with specified text.
JLabel(String text, int horizontalAlignment) Creates a label with text and horizontal alignment.
JLabel(Icon icon) Creates a label with the specified image icon.
JLabel(Icon icon, int horizontalAlignment) Creates a label with an image and horizontal alignment.
Creates a label with text, image, and horizontal
JLabel(String text, Icon icon, int horizontalAlignment)
alignment.
Basic Swing Components

Common Methods:
Here are some commonly used methods in JLabel:
Swing Components

Method Description
void setText(String text) Sets the text of the label.
String getText() Returns the text of the label.
void setIcon(Icon icon) Sets an icon for the label.
Icon getIcon() Returns the icon of the label.
Sets the horizontal alignment of the label (e.g., LEFT, CENTER,
void setHorizontalAlignment(int alignment)
RIGHT).
Sets the vertical alignment of the label (e.g., TOP, CENTER,
void setVerticalAlignment(int alignment)
BOTTOM).
void setFont(Font font) Sets the font for the label’s text.
void setForeground(Color color) Sets the color of the label’s text.
Sets a tooltip for the label (visible when hovering over the
void setToolTipText(String text)
label).
Basic Swing Components
Horizontal and Vertical Alignment Constants
Alignment constants are used for positioning text and icons:

Horizontal Alignment:
Swing Components

SwingConstants.LEFT

SwingConstants.CENTER

SwingConstants.RIGHT

SwingConstants.LEADING

SwingConstants.TRAILING

Vertical Alignment:

SwingConstants.TOP

SwingConstants.CENTER

SwingConstants.BOTTOM
Basic Swing Components

Uses of Jlabel
Displaying static information like titles or descriptions.
Swing Components

Providing descriptive text for other components.

Displaying icons or images in a user interface.


Basic Swing Components
Example : JLabel
Swing Components
Basic Swing Components
Example : JLabel
Swing Components

The output:
Basic Swing Components
JButton in Java Swing

Definition:
Swing Components

JButton is a Swing component used to create a push button that triggers an action when clicked. It can
display text, an icon, or both, and it is commonly used to perform actions or capture user input..

Hierarchy:
java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.AbstractButton
↳ javax.swing.JButton
Basic Swing Components
JButton in Java Swing

Constructors:
JButton provides several constructors to create buttons with or without text or icons:
Swing Components

Constructor Description
JButton() Creates a button with no text or icon.
JButton(String text) Creates a button with the specified text.
JButton(Icon icon) Creates a button with the specified icon.
JButton(String text, Icon icon) Creates a button with both text and icon.
Basic Swing Components
Common Methods:
Here are some commonly used methods in JButton:

Method Description
Swing Components

void setText(String text) Sets the text of the button.


String getText() Returns the text of the button.
void setIcon(Icon icon) Sets an icon for the button.
Icon getIcon() Returns the icon of the button.
void addActionListener(ActionListener l) Adds an action listener to handle button clicks.
void setEnabled(boolean enabled) Enables or disables the button.
boolean isEnabled() Checks whether the button is enabled.
void setToolTipText(String text) Sets a tooltip text for the button.
void setMnemonic(char mnemonic) Sets a mnemonic (keyboard shortcut) for the button.
void setHorizontalAlignment(int alignment) Sets the horizontal alignment of the button text and icon.
void setVerticalAlignment(int alignment) Sets the vertical alignment of the button text and icon.
Basic Swing Components

Features of Jbutton
Swing Components

➢ Supports text and icon.


➢ Can trigger ActionEvents for event handling.
➢ Provides tooltips for additional information.
➢ Customizable using setFont, setForeground, etc.
Basic Swing Components
Example : JButton
Swing Components
Basic Swing Components
Example : JButton
Swing Components

The output:

ToolTipText
Basic Swing Components
JTextField in Java Swing

Definition:
Swing Components

JTextField is a Swing component that provides a single-line text input field. It is commonly used for
gathering user input or displaying editable or read-only text.

Hierarchy:

java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.text.JTextComponent
↳ javax.swing.JTextField
Basic Swing Components
JTextField in Java Swing

Constructors:
Swing Components

JTextField provides several constructors for creating text fields with or without initial text and
specified column sizes:

Constructor Description
JTextField() Creates a new empty text field.
JTextField(String text) Creates a text field initialized with the specified text.
JTextField(int columns) Creates an empty text field with the specified number of columns.
JTextField(String text, int columns) Creates a text field with specified text and number of columns.
Basic Swing Components
Common Methods:
Here are some commonly used methods in JTextField:

Method Description
Swing Components

void setText(String text) Sets the text of the text field.


String getText() Retrieves the current text in the text field.
void setEditable(boolean editable) Enables or disables editing of the text field.
boolean isEditable() Checks if the text field is editable.
void setColumns(int columns) Sets the number of columns in the text field.
int getColumns() Returns the number of columns in the text field.
void setHorizontalAlignment(int alignment) Sets the horizontal alignment of the text.
int getHorizontalAlignment() Gets the horizontal alignment of the text.
void addActionListener(ActionListener l) Adds an ActionListener to handle events like pressing Enter.
void setFont(Font font) Sets the font of the text in the text field.
void setForeground(Color color) Sets the text color.
void setBackground(Color color) Sets the background color.
Basic Swing Components

Alignment Constants:
Swing Components

The horizontal alignment constants for text are:


➢ JTextField.LEFT (default)
➢ JTextField.CENTER
➢ JTextField.RIGHT
Basic Swing Components
Advanced Features
Read-Only Text Field
textField.setEditable(false);
Swing Components

Custom Alignment:
textField.setHorizontalAlignment(JTextField.CENTER);
Tooltips
textField.setToolTipText("Type your name here and press Enter");
Custom Fonts and Colors:
textField.setFont(new Font("Arial", Font.BOLD, 14));
textField.setForeground(Color.BLUE);
textField.setBackground(Color.LIGHT_GRAY);
Basic Swing Components
Example : JTextField
Swing Components
Basic Swing Components
Example : JTextField
Swing Components

The output:
Basic Swing Components
JPasswordField in Java Swing
Definition:
JPasswordField is a subclass of JTextField used for securely handling sensitive input, such as
Swing Components

passwords. It hides user input by displaying a placeholder character (typically an asterisk * or dot ●)
instead of the actual characters.

Hierarchy:

java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.text.JTextComponent
↳ javax.swing.JTextField
↳ javax.swing.JPasswordField
Basic Swing Components
JPasswordField in Java Swing

Constructors:
Swing Components

JPasswordField provides multiple constructors to create password fields with different configurations:

Constructor Description
JPasswordField() Creates a password field with default settings.
JPasswordField(int columns) Creates a password field with a specified number of columns.
JPasswordField(String text) Creates a password field initialized with the specified text.
JPasswordField(String text, int columns) Creates a password field initialized with the text and columns.
Basic Swing Components
JPasswordField in Java Swing

Common Methods:
Swing Components

Here are some commonly used methods of JPasswordField:

Method Description
char[] getPassword() Retrieves the password entered as a character array.
void setEchoChar(char c) Sets the character used to mask user input.
char getEchoChar() Retrieves the current echo character.
void cut() Removes the selected text and places it in the clipboard.
void copy() Copies the selected text to the clipboard (visible only if unmasked).
void paste() Pastes text from the clipboard.
void setText(String t) Sets the text in the password field.
Basic Swing Components
JPasswordField in Java Swing

Features of JPasswordField:
Swing Components

Secure Input:
hides user input by displaying a placeholder character.
Echo Character:
Displays a customizable echo character instead of actual input.
TextField Integration:
Inherits all functionality of JTextField, such as event handling and text operations.
Basic Swing Components
Example : JPasswordField
Swing Components
Basic Swing Components
Example : JPasswordField
Swing Components

The output:
Basic Swing Components
Example : JPasswordField (Custom Echo Character)
Swing Components

The output:
Basic Swing Components
JTextArea in Java Swing

Definition:
JTextArea is a Swing component that provides a multi-line area for displaying or editing plain text. It
Swing Components

is commonly used in applications where users need to input or view a large amount of text, such as
forms, editors, or logs.
Hierarchy:

java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.text.JTextComponent
↳ javax.swing.JTextArea
Basic Swing Components
JTextArea in Java Swing

Constructors:
Swing Components

JTextArea provides several constructors to create text areas with varying levels of customization:

Constructor Description
JTextArea() Creates an empty text area.
JTextArea(String text) Creates a text area with the specified initial text.
Creates a text area with the specified number of rows and
JTextArea(int rows, int columns)
columns.
JTextArea(String text, int rows, int columns) Creates a text area with specified text, rows, and columns.
Basic Swing Components
Common Methods:
Here are some commonly used methods in JTextArea:
Method Description
void setText(String text) Sets the text of the text area.
Swing Components

String getText() Retrieves the current text in the text area.


void append(String text) Appends the specified text to the end of the text area.
void insert(String text, int pos) Inserts the specified text at the specified position.
void replaceRange(String str, int start, int end) Replaces the text in the specified range with the given string.
void setLineWrap(boolean wrap) Enables or disables line wrapping.
void setWrapStyleWord(boolean word) Enables word-based wrapping when line wrapping is enabled.
void setEditable(boolean editable) Enables or disables editing of the text area.
boolean isEditable() Checks if the text area is editable.
void setRows(int rows) Sets the number of rows in the text area.
int getRows() Returns the number of rows in the text area.
void setColumns(int columns) Sets the number of columns in the text area.
int getColumns() Returns the number of columns in the text area.
Basic Swing Components
Features of JTextArea:

Multi-line Support: Can handle multiple lines of text.


Swing Components

Line Wrapping: Supports line wrapping to avoid horizontal scrolling.

Editable or Read-Only: Configurable for user input or display-only purposes.

Custom Fonts and Colors: Fully customizable for aesthetics or clarity.

Uses of JTextArea:

Displaying multi-line logs or messages.

Creating simple text editors.

Providing a text input area for forms or configurations.


Basic Swing Components
Advanced Features:
Read-Only Mode:
textArea.setEditable(false);
Swing Components

Custom Colors
textArea.setBackground(Color.LIGHT_GRAY);
textArea.setForeground(Color.DARK_GRAY);
Custom Font

textArea.setFont(new Font("Courier New", Font.BOLD, 16));


Basic Swing Components
Example : JTextArea
Swing Components
Basic Swing Components
Example : JTextArea

The output:
Swing Components
Basic Swing Components
JScrollPane in Java Swing

Definition:
Swing Components

JScrollPane is a Swing container that provides a scrollable view of a component. It allows adding
scrollbars to components that do not natively support scrolling, such as JPanel, JTextArea, or JTable.

Hierarchy:

java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.JScrollPane
Basic Swing Components
JScrollPane in Java Swing

Constructors:
Swing Components

JScrollPane offers several constructors to create scroll panes with different configurations:

Constructor Description
JScrollPane() Creates an empty scroll pane with no child component.
Creates a scroll pane with the specified component as the
JScrollPane(Component view)
viewport.
JScrollPane(Component view, int vsbPolicy,
Creates a scroll pane with a component and scrollbar policies.
int hsbPolicy)
Basic Swing Components
JScrollPane in Java Swing

Scrollbar Policies:
Swing Components

Scrollbar policies determine when scrollbars appear:

Constant Description
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED Vertical scrollbar appears when needed (default).
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS Vertical scrollbar is always displayed.
JScrollPane.VERTICAL_SCROLLBAR_NEVER Vertical scrollbar is never displayed.
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED Horizontal scrollbar appears when needed.
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS Horizontal scrollbar is always displayed.
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER Horizontal scrollbar is never displayed.
Basic Swing Components
JScrollPane in Java Swing

Common Methods:
Swing Components

Here are some commonly used methods in JScrollPane:

Method Description
void setViewportView(Component view) Sets the component to be displayed in the viewport.
JViewport getViewport() Returns the viewport that displays the component.
void setVerticalScrollBarPolicy(int policy) Sets the vertical scrollbar policy.
void setHorizontalScrollBarPolicy(int policy) Sets the horizontal scrollbar policy.
JScrollBar getVerticalScrollBar() Returns the vertical scrollbar.
JScrollBar getHorizontalScrollBar() Returns the horizontal scrollbar.
void setColumnHeaderView(Component view) Sets the column header component.
void setRowHeaderView(Component view) Sets the row header component.
Basic Swing Components
JScrollPane in Java Swing
Swing Components

Uses of JScrollPane:

Wrapping large components like JTextArea, JTable, or JPanel.

Managing dynamically resizing content.

Creating scrollable forms or lists.


Basic Swing Components
Example : JScrollPane
Swing Components

The output:
Basic Swing Components
JCheckBox in Java Swing

Definition:
JCheckBox is a Swing component that represents a checkable box with a label. It is typically used to
Swing Components

allow the user to make a binary choice, such as selecting or deselecting an option.

Hierarchy:
java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.AbstractButton
↳ javax.swing.JToggleButton
↳ javax.swing.JCheckBox
Basic Swing Components
JCheckBox in Java Swing

Constructors:
JCheckBox provides several constructors to create checkboxes:
Swing Components

Constructor Description
JCheckBox() Creates an unselected checkbox with no text or icon.
JCheckBox(String text) Creates an unselected checkbox with the specified text.
JCheckBox(String text, boolean selected) Creates a checkbox with specified text and initial selection state.
JCheckBox(Icon icon) Creates an unselected checkbox with the specified icon.
JCheckBox(Icon icon, boolean selected) Creates a checkbox with specified icon and initial selection state.
JCheckBox(String text, Icon icon) Creates an unselected checkbox with specified text and icon.
JCheckBox(String text, Icon icon, boolean selected) Creates a checkbox with specified text, icon, and initial state.
Basic Swing Components
JCheckBox in Java Swing

Features of JCheckBox:
Swing Components

Binary Selection: Allows selecting or deselecting options.

Customizable Appearance: Supports text, icons, and custom layouts.

Event Handling: Responds to user actions via ActionListener or ItemListener.


Basic Swing Components
JCheckBox in Java Swing

Advanced Features
Swing Components

Custom Icons:
checkBox1.setIcon(new ImageIcon("unchecked_icon.png"));
checkBox1.setSelectedIcon(new ImageIcon("checked_icon.png"));
Keyboard Mnemonic:

checkBox1.setMnemonic(KeyEvent.VK_O); // Alt + O selects "Option 1"

Custom Alignment:
checkBox1.setHorizontalTextPosition(SwingConstants.LEFT);
Basic Swing Components
JCheckBox in Java Swing

Uses of JCheckBox:
Swing Components

Providing multiple selectable options (e.g., preferences, settings).

Enabling/disabling specific features in applications.

Creating custom forms or dialogs.


Basic Swing Components
Example : JCheckBox
Swing Components
Basic Swing Components
Example : JCheckBox
Swing Components

The output:
Basic Swing Components
JRadioButton in Java Swing

Definition:
JRadioButton is a Swing component that represents a button which can be selected or deselected.
Swing Components

Unlike JCheckBox, JRadioButton is typically used in groups where only one button in the group can be
selected at a time.

Hierarchy:
java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.AbstractButton
↳ javax.swing.JToggleButton
↳ javax.swing.JRadioButton
Basic Swing Components
JRadioButton in Java Swing

Constructors:
JRadioButton provides multiple constructors for creating radio buttons with different initial configurations:
Swing Components

Constructor Description
JRadioButton() Creates an unselected radio button with no text or icon.
JRadioButton(String text) Creates an unselected radio button with the specified text.
JRadioButton(String text, boolean selected) Creates a radio button with specified text and initial state.
JRadioButton(Icon icon) Creates an unselected radio button with the specified icon.
JRadioButton(Icon icon, boolean selected) Creates a radio button with specified icon and initial state.
JRadioButton(String text, Icon icon) Creates an unselected radio button with specified text and icon.
JRadioButton(String text, Icon icon, boolean selected) Creates a radio button with text, icon, and initial state.
Basic Swing Components
JRadioButton in Java Swing

Common Methods:
Here are the most commonly used methods of JRadioButton:
Swing Components

Method Description
boolean isSelected() Checks if the radio button is selected.
void setSelected(boolean selected) Sets the selection state of the radio button.
String getText() Retrieves the text of the radio button.
void setText(String text) Sets the text of the radio button.
Icon getIcon() Retrieves the icon of the radio button.
void setIcon(Icon icon) Sets the icon of the radio button.
void addActionListener(ActionListener listener) Adds an action listener to respond to selection changes.
void setMnemonic(int mnemonic) Sets the keyboard mnemonic for the radio button.
void setHorizontalTextPosition(int position) Sets the horizontal position of the text relative to the icon.
void setVerticalTextPosition(int position) Sets the vertical position of the text relative to the icon.
Basic Swing Components
JRadioButton in Java Swing

Features of JRadioButton:
Swing Components

Mutual Exclusivity:
Typically used in groups to allow only one selection at a time.
Customizable Appearance:
Supports text, icons, and custom layouts.
Event Handling:
Responds to user actions via ActionListener or ItemListener.
Basic Swing Components
JRadioButton in Java Swing

Advanced Features:
Swing Components

Custom Icons:
option1.setIcon(new ImageIcon("unchecked_icon.png"));
option1.setSelectedIcon(new ImageIcon("checked_icon.png"));
Keyboard Mnemonic:

option1.setMnemonic(KeyEvent.VK_O); // Alt + O selects "Option 1"

Custom Alignment:
option1.setHorizontalTextPosition(SwingConstants.LEFT);
Basic Swing Components
Example : JRadioButton
Swing Components
Basic Swing Components
Example : JRadioButton
Swing Components

The output:
Basic Swing Components
JOptionPane in Java Swing

Definition:
Swing Components

JOptionPane is a utility class in Java Swing that provides a simple way to create standard dialog boxes.
It is used to display messages, take input from the user, or present options for selection. JOptionPane
eliminates the need for manually designing dialog boxes for common tasks..

Hierarchy:
java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.JOptionPane
Basic Swing Components

Constructors:
JOptionPane provides no public constructors since it is designed to be used with static
methods like showMessageDialog, showConfirmDialog, etc.
Swing Components

Uses of JOptionPane:
Message Dialogs: Show informational, warning, or error messages.
Confirmation Dialogs: Ask for user confirmation (Yes/No/Cancel).
Input Dialogs: Get input from the user.
Option Dialogs: Present a set of custom options for selection.
Basic Swing Components

Common Static Methods


Swing Components

Method Description
showMessageDialog(Component parent, Object message) Displays an informational message.
showConfirmDialog(Component parent, Object message) Displays a dialog with Yes/No/Cancel options.
showInputDialog(Component parent, Object message) Displays a dialog to get user input.
showOptionDialog(Component parent, Object message, String
title, int optionType, int messageType, Icon icon, Object[] Displays a customizable dialog.
options, Object initialValue)
createDialog(Component parent, String title) Creates a custom dialog.
Basic Swing Components

Common Message Types:


JOptionPane provides constants to define the type of message displayed:
Swing Components

Constant Description
JOptionPane.PLAIN_MESSAGE No icon/message type.
JOptionPane.INFORMATION_MESSAGE Information icon.
JOptionPane.WARNING_MESSAGE Warning icon.
JOptionPane.ERROR_MESSAGE Error icon.
JOptionPane.QUESTION_MESSAGE Question icon.
Basic Swing Components
Example 1: Simple Message Dialog
Swing Components

The output:
Basic Swing Components
Example 2: Confirmation Dialog
Swing Components

The output:
Basic Swing Components
Example 3: Input Dialog
Swing Components

The output:
Basic Swing Components
Example 4: Custom Option Dialog
Swing Components

The output:
Basic Swing Components
Example 5: Custom Dialog with Icons
Swing Components

The output:
Basic Swing Components
JComboBox in Java Swing

Definition:
Swing Components

JComboBox is a Swing component that provides a drop-down menu for selecting one item from a list. It
combines a text box and a list, enabling users to choose from predefined options or enter their own
value if editable.

Hierarchy:

java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.JComboBox<E>
Basic Swing Components
JComboBox in Java Swing

Constructors
Swing Components

Constructor Description
JComboBox() Creates a default combo box with no items.
JComboBox(E[] items) Creates a combo box with the specified array of items.
JComboBox(Vector<E> items) Creates a combo box with the specified Vector of items.
JComboBox(ComboBoxModel<E> model) Creates a combo box with the specified data model.
Basic Swing Components
JComboBox in Java Swing

Common Methods
Swing Components

Method Description
void addItem(E item) Adds an item to the combo box.
void removeItem(Object item) Removes the specified item from the combo box.
void removeAllItems() Removes all items from the combo box.
void setSelectedItem(Object item) Sets the selected item in the combo box.
Object getSelectedItem() Returns the currently selected item.
void setEditable(boolean editable) Sets whether the combo box is editable.
boolean isEditable() Returns true if the combo box is editable, false otherwise.
int getItemCount() Returns the number of items in the combo box.
Object getItemAt(int index) Returns the item at the specified index.
ComboBoxModel<E> getModel() Retrieves the data model for the combo box.
void setModel(ComboBoxModel<E> model) Sets a new data model for the combo box.
Basic Swing Components
JComboBox in Java Swing

Features
Swing Components

Dropdown List:
Provides a compact way to show multiple options.
Editable Option:
Can be set as editable, allowing users to type their own input.
Data Binding:
Uses a ComboBoxModel to manage its data, making it easy to update dynamically.
Basic Swing Components
JComboBox in Java Swing

Example 1: Basic JComboBox Usage


Swing Components

The output:
Basic Swing Components
JComboBox in Java Swing

Example 2: Handling JComboBox Events


Swing Components
Basic Swing Components
JComboBox in Java Swing

Example 2: Handling JComboBox Events


Swing Components

The output:
Basic Swing Components
JComboBox in Java Swing

Example 3: Editable JComboBox


Swing Components

The output:
Basic Swing Components
JList in Java Swing

Definition:
Swing Components

JList is a Swing component used to display a list of items from which users can select one or more. It
supports both single and multiple selections and is often used in GUI applications to allow users to
choose from a set of predefined options.

Hierarchy:

java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.JList<E>
Basic Swing Components
JList in Java Swing

Constructors:
Swing Components

Constructor Description
JList() Creates an empty list with no data.
JList(E[] listData) Creates a list populated with the specified array of items.
JList(Vector<? extends E> listData) Creates a list populated with the specified vector of items.
JList(ListModel<E> dataModel) Creates a list using the specified data model.
Basic Swing Components
Common Methods:

Method Description
void setListData(E[] listData) Populates the list with the specified array of items.
Swing Components

void setListData(Vector<? extends E> listData) Populates the list with the specified vector of items.
E getSelectedValue() Returns the first selected value from the list.
int getSelectedIndex() Returns the index of the first selected item.
int[] getSelectedIndices() Returns the indices of all selected items.
List<E> getSelectedValuesList() Returns a list of selected values.
void setSelectedIndex(int index) Sets the selected item by index.
void setSelectionMode(int mode) Sets the selection mode (single, single interval, or multiple).
void clearSelection() Clears the current selection.
void addListSelectionListener(ListSelectionListener listener) Adds a listener to detect selection changes.
ListModel<E> getModel() Returns the data model associated with the list.
void setModel(ListModel<E> model) Sets a custom data model for the list.
Basic Swing Components
Selection Modes :

JList supports three selection modes:


Swing Components

SINGLE_SELECTION:
Only one item can be selected at a time.
SINGLE_INTERVAL_SELECTION:
Multiple contiguous items can be selected.
MULTIPLE_INTERVAL_SELECTION:
Multiple non-contiguous items can be selected.
Basic Swing Components
JList in Java Swing

Example 1: Basic JList


Swing Components

The output:
Basic Swing Components
Example 2: JList with Selection Listener
Swing Components

The output:
Basic Swing Components
Example 3: Multiple Selection JList
Swing Components

The output:
Basic Swing Components
Example 3: Multiple Selection JList
Swing Components

The output:
Basic Swing Components
Key Points:

Custom Renderers:
Swing Components

Use setCellRenderer to customize how items are displayed in the list.


Dynamic Models:
Use DefaultListModel to dynamically add, remove, or modify items in the list.
Event Handling:
Add ListSelectionListener to respond to item selection changes.
Basic Swing Components
DefaultListModel in Java Swing

Definition:
Swing Components

DefaultListModel is a built-in class in Java Swing used to manage the data model for a JList. It
provides dynamic capabilities, allowing you to add, remove, or update items in the list at runtime.

Hierarchy:

java.lang.Object
↳ javax.swing.AbstractListModel<E>
↳ javax.swing.DefaultListModel<E>
Basic Swing Components
DefaultListModel in Java Swing

Features:
Swing Components

• A mutable implementation of ListModel.

• Allows dynamic modification of list contents.

• Notifies JList whenever the data changes, enabling automatic updates.


Constructors:

Constructor Description
DefaultListModel() Creates an empty DefaultListModel.
Basic Swing Components
Common Methods:
Method Description
void addElement(E element) Adds the specified element to the end of the list.
void insertElementAt(E element, int index) Inserts the specified element at the specified position.
Swing Components

void removeElementAt(int index) Removes the element at the specified position.


void removeElement(Object obj) Removes the first occurrence of the specified element.
void removeAllElements() Removes all elements from the list.
int getSize() Returns the number of elements in the list.
E getElementAt(int index) Returns the element at the specified position.
boolean contains(Object elem) Checks if the list contains the specified element.
int indexOf(Object elem) Returns the index of the first occurrence of the specified element.
void setElementAt(E element, int index) Replaces the element at the specified index with a new element.
void clear() Removes all elements from the list.
Basic Swing Components
Example 1: Basic Usage of DefaultListModel
Swing Components

The output:
Basic Swing Components
Example 2: Add and Remove Items Dynamically
Swing Components
Basic Swing Components
Example 2: Add and Remove Items Dynamically
Swing Components

The output:
Basic Swing Components
Example 3: Updating Elements in DefaultListModel
Swing Components
Basic Swing Components
Example 3: Updating Elements in DefaultListModel The output:
Swing Components
Basic Swing Components
JSpinner in Java Swing

Definition:
Swing Components

JSpinner is a Swing component that allows users to select a value from a sequence of values by
incrementing or decrementing the current value. It is often used for numeric inputs, dates, or
predefined choices.

Hierarchy:
java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.JSpinner
Basic Swing Components
JSpinner in Java Swing

Definition:
Swing Components

JSpinner is a Swing component that allows users to select a value from a sequence of values by
incrementing or decrementing the current value. It is often used for numeric inputs, dates, or
predefined choices.

Hierarchy:
java.lang.Object
↳ java.awt.Component
↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.JSpinner
Basic Swing Components
JSpinner in Java Swing

Constructors:
Swing Components

Constructor Description
JSpinner() Creates a spinner with a default SpinnerNumberModel.
JSpinner(SpinnerModel model) Creates a spinner with the specified data model.
Basic Swing Components
JSpinner in Java Swing

Common Methods:
Swing Components

Method Description
void setModel(SpinnerModel model) Sets the data model for the spinner.
SpinnerModel getModel() Returns the current spinner model.
Object getValue() Returns the current value of the spinner.
void setValue(Object value) Sets the current value of the spinner.
JComponent getEditor() Returns the editor component of the spinner.
void setEditor(JComponent editor) Sets a custom editor component for the spinner.
void addChangeListener(ChangeListener listener) Adds a listener to detect value changes.
void removeChangeListener(ChangeListener listener) Removes a previously added change listener.
Basic Swing Components
JSpinner in Java Swing

Spinner Models
Swing Components

Spinners use models to manage their values. Java provides several built-in models:

• SpinnerNumberModel: For numeric values.


Allows specifying a range, step size, and initial value.
• SpinnerDateModel: For date values.
Allows incrementing or decrementing dates.
• SpinnerListModel: For a list of values.
Allows cycling through predefined choices.
Basic Swing Components
Example 1: Basic JSpinner with Numbers
Swing Components

The output:
Basic Swing Components
Example 2: JSpinner with Numeric Range
Swing Components

The output:
Basic Swing Components

Example 3: JSpinner with Dates


Swing Components

The output:
Basic Swing Components

Example 4: JSpinner with Custom List


Swing Components

The output:
Basic Swing Components
Example 5: Handling Value Changes
Swing Components

The output:
Basic Swing Components
Key Points:

• Editor Customization: The editor can be customized to display different formats,


Swing Components

such as dates or formatted text.

• Dynamic Updates: Models can be updated dynamically to reflect changes in the

list of selectable values.

• Event Handling: Use ChangeListener to detect when the spinner's value changes.
Basic Swing Components
JTree in Java Swing

Constructors:
Swing Components

Constructor Description
JTree() Creates an empty tree with no nodes.
JTree(TreeNode root) Creates a tree with the specified root node.
JTree(Object[] value) Creates a tree from the specified array of objects.
JTree(Vector<?> value) Creates a tree from the specified vector of objects.
JTree(Hashtable<?, ?> value) Creates a tree from the specified hashtable.
JTree(TreeModel model) Creates a tree using the specified data model.
Basic Swing Components
Common Methods:

Method Description
Swing Components

TreeModel getModel() Returns the current data model used by the tree.
void setModel(TreeModel model) Sets the data model for the tree.
TreePath getSelectionPath() Returns the path of the selected node.
TreePath[] getSelectionPaths() Returns the paths of all selected nodes.
void setSelectionPath(TreePath path) Sets the selection to the specified node path.
void expandPath(TreePath path) Expands the specified node path.
void collapsePath(TreePath path) Collapses the specified node path.
boolean isRootVisible() Checks if the root node is visible.
void setRootVisible(boolean flag) Sets whether the root node should be visible.
void addTreeSelectionListener(TreeSelectionListener
Adds a listener for selection changes in the tree.
listener)
Basic Swing Components
How to Populate a Jtree:

• Using a DefaultMutableTreeNode:
Nodes can be manually added using the DefaultMutableTreeNode class.
Swing Components

• Using a TreeModel:
A custom tree model can be created for dynamic data sources.
Basic Swing Components
Example 1: Basic JTree
Swing Components

The output:
Basic Swing Components
Example 2: JTree with Tree Selection Listener
Swing Components
Basic Swing Components
Example 2: JTree with Tree Selection Listener
Swing Components

The output:
Basic Swing Components
Example 3: Dynamic Tree Model
Swing Components

The output:
Basic Swing Components
Key Points
• JTree is used to display hierarchical data.

• Nodes can be managed using DefaultMutableTreeNode.


Swing Components

• Selection changes can be handled using TreeSelectionListener.

• Supports dynamic updates using DefaultTreeModel.


Any question ?

You might also like