0% found this document useful (0 votes)
19 views47 pages

Java Swing Basics

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views47 pages

Java Swing Basics

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Java Swing Components

Course Outline:
• Topic 1 – Java Swing Overview
• Topic 2 – Java Swing JFrame
• Topic 3 – Java Swing JPanel
• Topic 4 – Java Swing JWindow
• Topic 5 – Java Swing JLabel
• Topic 6 – Java Swing JButton
• Topic 7 – Java Swing JCheckBox
• Topic 8 – Java Swing JTextField
• Topic 9 – Java Swing JTextArea
• Topic 10 – Java Swing JComboBox
• Topic 11 – Java Swing JRadioButton
• Topic 12 – Java Swing JList
• Topic 13 – Java Swing JOptionPane
• Topic 14 – Java Swing JPasswordField
Topic 1
Java Swing Overview
Swing is a powerful and widely used Java GUI (Graphical User Interface)
toolkit that provides a rich set of components to build interactive and
visually appealing applications. Unlike AWT, Swing components are pure
Java-based, which means they are not dependent on the native platform's
GUI components. This allows Swing to offer consistent appearance and
behavior across different operating systems.

Swing was introduced as part of the Java Foundation Classes (JFC) to


address the limitations of AWT and to provide more sophisticated GUI
components for Java applications. It is built on top of AWT but extends its
capabilities significantly.

Swing is highly customizable, lightweight, and provides a wide range of


components, including buttons, labels, text fields, tables, trees, and many
Java Swing Overview
Overview of Swing Components
Swing offers a rich set of components that can be used to create complex GUIs for Java
applications. Here are some commonly used Swing components:

1. JFrame: The JFrame class is a top-level container that represents the main application
window. It provides all the features of AWT's Frame but with additional
functionalities.

2. JPanel: The JPanel class is a lightweight container that is often used to group other
components together or create custom components.

3. JLabel: The JLabel class is used to display text or an image. It is commonly used for
headings, descriptions, or icons.

4. JButton: The JButton class is used to create a clickable button that triggers an action
when clicked.

5. JTextField: The JTextField class allows users to input single-line text.


Overview of Swing Components
6. JTextArea: The JTextArea class is used to display multi-line text.

7. JCheckBox: The JCheckBox class represents a checkbox that can


be selected or deselected.

8. JRadioButton: The JRadioButton class represents a radio button,


which allows only one option to be selected from a group.

9. JComboBox: The JComboBox class is a drop-down list that


allows the user to select one option from a list of choices.

10. JList: The JList class represents a scrollable list of items from
which the user can make multiple selections.
Swing Event Handling and Listener
Interfaces
Just like AWT, Swing also uses event handling to respond to user interactions. The
event handling mechanism in Swing is similar to AWT and involves implementing
various listener interfaces. Here are some commonly used listener interfaces in
Swing:

1. ActionListener: This interface is used to handle events generated by components


like buttons. It has a single method actionPerformed(ActionEvent e) that you
need to implement. The method is called when the event occurs.

2. MouseListener: This interface is used to handle mouse-related events, such as


mouse clicks and movements. It contains several methods like
mouseClicked(MouseEvent e), mousePressed(MouseEvent e), etc.

3. KeyListener: This interface is used to handle keyboard-related events, such as key


presses and releases. It contains methods like keyPressed(KeyEvent e),
keyReleased(KeyEvent e), etc.
Code Example: Simple Swing Application
Here's a simple example that demonstrates the usage of Swing components and
event handling in Java:
Conclusion
In this guide, we introduced you to Java Swing, a powerful GUI
toolkit that provides a wide range of components to create
interactive Java applications. We covered the basics of Swing
components, including JFrame, JPanel, JLabel, JButton, and
more. Additionally, we explained how to handle events using
Swing's listener interfaces, such as ActionListener,
MouseListener, and KeyListener.

Java Swing is a versatile toolkit that empowers developers to


build visually appealing and interactive applications. Its platform
independence and extensive customization options make it a
popular choice for desktop application development in Java.
Topic 2
Java Swing JFrame
JFrame is a class in the Java Swing library that
provides the foundation for creating and managing
graphical user interface (GUI) windows. It is a top-
level container that represents a window with
decorations such as a title bar, maximize and
minimize buttons, and borders. JFrame allows
developers to build interactive desktop
applications with graphical elements easily. It is an
essential component in many Java GUI
Creating and Displaying a JFrame
To create a JFrame, you need to follow these steps:

1. Import necessary packages: Before creating a JFrame,


import the required Swing packages.

import javax.swing.JFrame;

2. Create the JFrame object: Create an instance of JFrame


using the default constructor.

JFrame frame = new JFrame();


Creating and Displaying a JFrame
3. Set the window properties: You can customize the JFrame by setting its properties like title,
size, default close operation, etc.

frame.setTitle("My JFrame");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

4. Add components (optional): You can add other Swing components like buttons, labels, etc.,
to the JFrame.

// Example: Adding a label to the frame


JLabel label = new JLabel("Hello, JFrame!");
frame.add(label);

5. Display the JFrame: Finally, make the JFrame visible by setting its visibility to true.

frame.setVisible(true);
Example: Here's a complete example that
creates a simple JFrame with a label and
displays it:
JFrame Properties and Attributes
JFrame provides various properties and attributes that allow you
to control its behavior and appearance. Some commonly used
ones include:

• Title: Sets the title displayed on the title bar of the JFrame.
• Size: Sets the width and height of the JFrame window.
• DefaultCloseOperation: Defines the action to be performed
when the JFrame is closed (e.g., EXIT_ON_CLOSE to exit the
application).
• Resizable: Specifies whether the JFrame can be resized by the
user.
• IconImage: Sets the icon image displayed in the title bar of the
JFrame.
JFrame Layouts and Content Panes
JFrame uses a content pane to hold the GUI components added to it.
Layout managers are used to arrange these components within the content
pane. Layout managers handle how components are positioned and resized
as the window size changes.

Java provides several layout managers, including:

• FlowLayout: Arranges components in a left-to-right flow, wrapping to the


next row as needed.
• BorderLayout: Divides the container into five regions (north, south, east,
west, center) and places components accordingly.
• GridLayout: Organizes components in a grid with specified rows and
columns.
• BoxLayout: Arranges components either in a single line (X_AXIS) or a
JFrame Layouts and Content Panes
Handling JFrame Events
JFrame supports various events that can be handled to add
interactivity to your application. Some common events
include:

• ActionEvent: Triggered when an action is performed


(e.g., button click).
• WindowEvent: Related to JFrame window (e.g., open,
close, resize).

To handle events, you typically use listeners. For example,


to handle a button click event, you can use an
Example: Here's an example of handling a button
click event:
Conclusion
In this guide, we covered the fundamentals of working with
JFrames in Java. You learned how to create, display, and
customize JFrames with various properties and attributes. We
explored different layout managers to arrange components
efficiently and how to handle events for interactive user
experiences. Additionally, we saw how to customize the
JFrame appearance using look and feel settings.

Using JFrames, you can create rich and interactive graphical


user interfaces for your Java applications, making them user-
friendly and visually appealing.
Topic 3
Java Swing JPanel
JPanel is a Swing component in the Java
programming language that provides a container
for organizing and grouping other Swing
components, such as buttons, labels, text fields,
etc. It is used to create sections or regions within a
user interface to manage and organize controls
more efficiently. JPanels are lightweight and
versatile, making them a fundamental building
block for creating complex and visually appealing
Java GUI applications.
Creating and Adding JPanels
To use JPanels in your Java application, follow these steps:

1. Import necessary packages: Before creating JPanels,


import the required Swing packages.

import javax.swing.JPanel;

2. Create a JPanel object: Create an instance of JPanel


using the default constructor.

JPanel panel = new JPanel();


Creating and Adding JPanels
3. Add components to the JPanel: You can add other Swing
components to the JPanel using appropriate layout managers (e.g.,
FlowLayout, BorderLayout) for positioning and organization.

// Example: Adding a button to the panel


JButton button = new JButton("Click Me!");
panel.add(button);

4. Add the JPanel to a container: JPanels need to be added to a


container (e.g., JFrame, another JPanel) to be displayed on the GUI.

frame.add(panel); // Assuming "frame" is a JFrame or another


Example: Here's a simple example that creates a
JFrame and adds a JPanel with a button to it:
Organizing Controls with JPanels
JPanels are especially useful for organizing
controls in a Java GUI application. By using
layout managers, you can create a
structured and visually appealing user
interface.
Organizing Controls with JPanels
Example: Here's an example of using two JPanels with
different layout managers to organize controls:
JPanel Properties and Layout Managers
JPanels come with several properties and attributes that can be set to
customize their behavior and appearance:

• Background Color: Sets the background color of the panel.


• Border: Defines the border style around the panel.
• Layout Manager: Specifies how components are arranged within the panel.

Some common layout managers are:

• FlowLayout: Arranges components in a left-to-right flow, wrapping to the


next line if needed.
• BorderLayout: Divides the panel into five regions (north, south, east, west,
center) to place components accordingly.
• GridLayout: Organizes components in a grid with specified rows and
columns.
Customizing JPanel Appearance
You can customize the appearance of a JPanel by setting its properties,
such as background color and border, to match the design of your GUI
application.
Example: Here's an example of customizing the appearance of a JPanel:
Conclusion
JPanels are a crucial part of building Java Swing applications,
allowing you to organize and group components efficiently.
By using different layout managers, you can create a well-
structured and user-friendly graphical user interface.
Moreover, customizing the appearance of JPanels can
enhance the overall visual appeal of your application.

In summary, JPanels play a significant role in designing


interactive and visually appealing Java GUI applications, and
mastering their usage is essential for any Java GUI developer.
Topic 4
Java Swing JWindow
JWindow is a Swing component in the Java
programming language that represents a top-level
window without decorations such as title bars,
borders, or control buttons (e.g., minimize, maximize,
close). It provides a lightweight container that can be
used for various purposes, including displaying pop-
up windows, splash screens, or custom-shaped
windows. Unlike JFrame, JWindow does not have
built-in decorations, making it ideal for creating
borderless and custom-designed windows.
Creating and Displaying a JWindow
To use JWindow in your Java application, follow these steps:

1. Import necessary packages: Before working with


JWindow, import the required Swing packages.

import javax.swing.JWindow;

2. Create a JWindow object: Create an instance of JWindow


using the default constructor.

JWindow window = new JWindow();


Creating and Displaying a JWindow
3. Add components (optional): You can add other Swing
components to the JWindow using layout managers for
organizing them.

// Example: Adding a label to the window


JLabel label = new JLabel("Welcome to JWindow!");
window.add(label);

4. Display the JWindow: Finally, make the JWindow visible


by setting its visibility to true.
Example: Here's a simple example that creates a
JWindow with a label and displays it:
JWindow Properties and Attributes
JWindow provides properties and attributes that allow you to
customize its behavior and appearance:

• Background Color: Sets the background color of the


JWindow.
• Opacity: Adjusts the transparency of the window, making
it partially transparent.
• Position: Sets the position of the JWindow on the screen.
• Focusable: Specifies whether the JWindow can receive
focus.
Refer to the official documentation for a complete list of
properties and methods.
Handling JWindow Events
JWindow supports various events that can be handled to add
interactivity to your application. Some common events include:

• ComponentListener: Used to monitor resizing and


repositioning of the JWindow.
• MouseListener: Allows you to respond to mouse clicks and
movements within the JWindow.
• KeyListener: Enables capturing keyboard input when the
JWindow has focus.
To handle events, you typically use listeners. For example, to
respond to mouse clicks on the JWindow, you can use a
MouseListener.
Customizing JWindow Appearance
As JWindow lacks built-in decorations, you can
fully customize its appearance to suit your
application's design. For example, you can
create a custom-shaped window using alpha
values to define transparency.
Example: Here's an example of a custom-shaped
JWindow with a partially transparent
background:
Conclusion
In this guide, we covered the fundamentals of working with
JWindow in Java Swing applications. JWindow provides a
versatile container for creating custom-designed,
borderless windows. You learned how to create and display
a JWindow, customize its appearance, and handle events to
make your application more interactive.

JWindow is a valuable component for creating unique and


visually appealing graphical user interfaces. Its flexibility
and customization options make it a powerful tool for
creating modern and engaging Java GUI applications.
Topic 5
Java Swing JLabel
JLabel is a Swing component in the Java
programming language that is used to display
text or an image on a graphical user interface
(GUI). It provides a simple way to add
descriptive text or visual content to your Java
applications. JLabels are commonly used to
show static text, icons, or images that provide
information to the user or enhance the overall
appearance of the user interface.
Creating and Displaying JLabels
To use JLabel in your Java application, follow these steps:

1. Import necessary packages: Before creating JLabels, import the required Swing
packages.

import javax.swing.JLabel;

2. Create a JLabel object: Create an instance of JLabel with the desired text or
icon using the appropriate constructor.

JLabel label = new JLabel("Hello, JLabel!");

3. Add the JLabel to a container: JLabels need to be added to a container (e.g.,


JFrame, JPanel) to be displayed on the GUI.
Example: Here's a simple example that creates
a JFrame and adds a JLabel to it:
JLabel Properties and Text Formatting
JLabel provides properties and attributes to customize its
appearance and format the displayed text. Some common
properties include:

• Text: Sets the text content of the label.


• Font: Defines the font used to display the text.
• Foreground Color: Sets the color of the text.
• Background Color: Sets the background color of te
label.
You can use HTML tags within the label's text to format it,
allowing you to apply different font styles, colors, or insert
Example: Here's an example that
demonstrates using HTML tags to format the
JLabel's text:
JLabel Alignment and Positioning
JLabel allows you to specify the alignment and
positioning of its content. The most common
alignment options are:

• LEFT: Aligns the text or icon to the left.


• CENTER: Centers the text or icon within the label.
• RIGHT: Aligns the text or icon to the right.
You can also use a combination of horizontal and
vertical alignment options to position the content
precisely within the label.
Example: Here's an example that
demonstrates aligning and positioning the
JLabel's text:
Customizing JLabel Appearance
You can customize the appearance of a
JLabel by setting its properties, such as the
font, text color, and background color, to
match the design of your GUI application.
Example: Here's an example that customizes
the appearance of a JLabel:
Conclusion
In this guide, we covered the fundamentals of working with
JLabel in Java Swing applications. JLabel is a versatile
component that allows you to add text or images to your
user interface, providing important information or enhancing
the visual appeal of your application. You learned how to
create and display JLabels, customize their appearance, and
format the displayed text.

JLabel plays a significant role in creating informative and


visually appealing graphical user interfaces. Its simplicity and
flexibility make it an essential tool for any Java GUI developer.

You might also like