0% found this document useful (0 votes)
12 views64 pages

Java Unit 4 Swing

Uploaded by

rajkirannaidu123
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)
12 views64 pages

Java Unit 4 Swing

Uploaded by

rajkirannaidu123
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/ 64

1) Swing Introduction :

Swing is a graphical user interface (GUI) toolkit for Java.


It is a part of the Java Foundation Classes (JFC) and provides a set of lightweight components
to create rich desktop applications.
Platform Independence:
Swing is platform-independent, meaning Swing-based applications can run on any platform
that supports Java.
Components:
Swing provides a wide range of components such as buttons, text fields, labels, panels, and
more.
These components are customizable and can be extended to create complex user interfaces.
Lightweight Components:
Swing components are lightweight compared to the older Abstract Window Toolkit (AWT)
components.
Lightweight components are rendered directly by the Swing library, leading to improved
performance and a more consistent look across platforms.
Event-Driven Programming:
Swing follows the event-driven programming paradigm.
Interactions with Swing components are based on events, such as button clicks or mouse
movements, triggering corresponding event handlers.
Swing Containers:
Swing provides containers like JFrame, JPanel, and JDialog to organize and manage
components in a GUI application.
Layout Managers:
Layout managers in Swing help control the arrangement of components within containers.
They ensure that the components adapt to different screen sizes and resolutions.
Look and Feel:
Swing supports different "look and feel" options, allowing developers to change the
appearance of their applications to match the native look of the underlying operating system.
Double Buffering:
Swing uses double buffering to reduce flickering in graphical components, providing a
smoother user experience.
Threading:
Swing applications often involve multiple threads, with the Swing Event Dispatch Thread
(EDT) responsible for handling GUI events.
Extensibility:
Swing is extensible, and developers can create custom components by extending existing
Swing classes.
Advanced Features:
Swing supports advanced features like drag-and-drop, undo/redo mechanisms, and
accessibility features.
Integration with Other Java APIs:
Swing can be seamlessly integrated with other Java APIs and libraries, making it versatile for
various application requirements.
Community and Documentation:
Swing has a well-established community, and extensive documentation is available, making
it easier for developers to find support and resources.

Differences Between Awt and Swing:

Feature AWT Swing


Partially platform-independent.
Platform Some components rely on the Fully platform-independent. All
Independence underlying native windowing system. components are rendered using Java.
Components are heavyweight,
Lightweight vs. relying on the native platform for Components are lightweight, as they
Heavyweight rendering. are rendered by the Swing library.
Limited look and feel options. Supports various look and feel options,
Appearance may vary across providing a consistent appearance
Look and Feel platforms. across platforms.
More efficient as components are
Generally less efficient due to drawn by Java, allowing better
Performance reliance on native components. performance.
Rich set of components with advanced
Complexity and Simpler and may lack advanced features, making it more powerful and
Features features. flexible.

Highly customizable components,


Limited customization of allowing developers to create unique
Customization components. interfaces.
Feature AWT Swing
Offers a wide range of layout
Layout managers are present but managers, providing more control over
Layout Managers may be less flexible. component arrangement.
Community Well-established but may be less Active community support and
Support active compared to Swing. extensive documentation.
More feature-rich but requires a
Development Simpler to get started but may lack steeper learning curve due to
Complexity advanced capabilities. increased complexity.
Seamless integration with other Java
Integration with Integration with other Java APIs may APIs, providing a more comprehensive
Other APIs be more limited. development environment.

Swing Package:
The primary package for Swing is javax.swing. It contains a comprehensive set of classes and
interfaces for building graphical user interfaces.
The key components of the javax.swing package include:
JComponents:
The JComponent class is a base class for all Swing components.
Various components, such as JButton, JTextField, JLabel, and more, extend JComponent.
Containers:
Swing provides containers like JFrame, JPanel, JDialog, and JApplet for organizing and
managing components.
Layout Managers:
Layout managers, such as FlowLayout, BorderLayout, GridLayout, and GridBagLayout,
assist in arranging components within containers.
Events and Listeners:
Swing follows the event-driven programming model. Key event-related classes include
ActionEvent, ActionListener, MouseEvent, MouseListener, etc.
Models and Renderers:
Classes like DefaultListModel, DefaultTableCellRenderer, and others support data models
and custom rendering for components like lists and tables.
Dialogs and Option Panes:
Swing provides classes like JOptionPane for creating standard dialogs (message, input,
confirm) in a consistent manner.
Menus and Toolbars:
JMenuBar, JMenu, JMenuItem, and related classes are used for creating menus and toolbars.
Pluggable Look and Feel:
UIManager class enables developers to change the look and feel of the application.

NOTE:

In AWT , we are able to add all GUI components to frame directly.


In SWING , we are able to add all the GUI components to the pane
There are four types of panes in SWING
1. RootPane
2. LayeredPane
3. ContentPane
4. GlassPane

1. RootPane:
Purpose: The RootPane is the top-level container that holds all other Swing components
within a JFrame.
Components: It includes the ContentPane, LayeredPane, and optional decorations such as the
title bar, menu bar, and status bar.
Usage:
Developers typically interact with the RootPane indirectly through the JFrame class.
Customization of the RootPane is often done for special layout or behavior requirements.
2. LayeredPane:
Purpose: The LayeredPane is used to manage the layering or stacking of components within a
JFrame.
Components: Components added to the LayeredPane can be positioned at different layers,
allowing for overlapping and depth arrangement.
Usage:
Useful when you need to overlay components or create complex visual effects.
Components are added to specific layers using the setLayer() method.
3. ContentPane:
Purpose: The ContentPane is the primary container where application components are added
for display within a JFrame.
Components: All standard user interface components (buttons, labels, panels, etc.) are
typically added to the ContentPane.
Usage:
Most of the GUI development occurs by adding components to the ContentPane.
Layout managers are used to organize and manage the placement of components within the
ContentPane.
4. GlassPane:
Purpose: The GlassPane is an invisible pane that sits on top of all other panes and
components.
Components: Components added to the GlassPane are rendered above all other components,
intercepting mouse and keyboard events.
Usage:
Useful for creating custom overlays, modal dialogs, or blocking user input during certain
operations.
It allows developers to intercept events before they reach other components.

NOTE:
In Java Swing, the contentPane is a container where you typically add your components
(like panels, buttons, etc.) when creating a JFrame. By default, the JFrame has a content
pane, so you don't need to explicitly add it. However, if you want to be explicit, you can use
the getContentPane() method.
Containers :
JFrame , JPanel , JApplet , JDialog

2) JFrame :

JFrame Class:
JFrame is a class in the javax.swing package that represents the main window or frame of a
Swing application.
Top-Level Container:
It serves as a top-level container, providing a space to organize and display other Swing
components.
Window Features:
JFrame includes features such as a title bar, borders, and buttons for minimizing, maximizing,
and closing the window.
Extending JFrame:
To create a Swing application, developers often extend the JFrame class and customize its
behavior.
Constructor:
JFrame has several constructors, allowing customization of the frame's title, size, and other
properties.
Layout Manager:
It can use layout managers such as FlowLayout, BorderLayout, or others to manage the
arrangement of components within the frame.
Adding Components:
Other Swing components like buttons, labels, and panels can be added to a JFrame to create a
user interface.
Visibility:
The setVisible(boolean) method is used to make the frame visible or invisible.
Default Close Operation:
The setDefaultCloseOperation(int) method is used to define the default close operation when
the user clicks the close button.
Event Handling:
JFrame can handle events through various methods, including event listeners, to respond to
user interactions.
Resizing and Resizable:
Developers can set whether a JFrame is resizable or not using the setResizable(boolean)
method.
Icon Image:
The setIconImage(Image) method allows setting the icon image for the frame that appears in
the taskbar or window manager.
Layout and Design:
Developers often set the layout manager and customize the frame's appearance to create a
visually appealing user interface.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SwingJFrameExample extends JFrame


{

// Components
private JLabel nameLabel;
private JTextField nameTextField;
private JLabel genderLabel;
private JComboBox<String> genderComboBox;
private JCheckBox subscribeCheckBox;
private JButton submitButton;
// Constructor
public SwingJFrameExample()
{
// Set the title for the JFrame
setTitle(" Jframe ");

// Create components
nameLabel = new JLabel("Enter your name:");
nameTextField = new JTextField(20);
genderLabel = new JLabel("Select your gender:");
String[] genders = {"Male", "Female", "Other"};
genderComboBox = new JComboBox<>(genders);
subscribeCheckBox = new JCheckBox("Subscribe to our newsletter");
submitButton = new JButton("Submit");

// Set layout manager


setLayout(new javax.swing.BoxLayout(getContentPane(),
javax.swing.BoxLayout.Y_AXIS));

// Add components to the JFrame


add(nameLabel);
add(nameTextField);
add(genderLabel);
add(genderComboBox);
add(subscribeCheckBox);
add(submitButton);

// Add ActionListener to the button


submitButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String enteredName = nameTextField.getText();
String selectedGender = (String) genderComboBox.getSelectedItem();
boolean isSubscribed = subscribeCheckBox.isSelected();

// Display a message with the entered information


String message = "Name: " + enteredName + "\nGender: " + selectedGender +
"\nSubscribed: " + (isSubscribed ? "Yes" : "No");
JOptionPane.showMessageDialog(SwingJFrameExample.this,
message, "User Information", JOptionPane.INFORMATION_MESSAGE);
}
});

// Set default close operation and size


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(350, 250);

// Center the JFrame on the screen


setLocationRelativeTo(null);

// Make the JFrame visible


setVisible(true);
}

// Main method to run the application


public static void main(String[] args)
{
// Create an instance of the JFrame
new SwingJFrameExample();
}
}

Output:
3) JApplet:
JApplet Class:
JApplet is a class in the javax.swing package that represents a Swing applet.
Applet in Swing:
An applet is a small Java program that runs within a web browser.
Extending JApplet:
To create a Swing applet, developers often extend the JApplet class.
Lifecycle Methods:
JApplet provides methods such as init(), start(), stop(), and destroy(), representing the applet's
lifecycle.
init() Method:
The init() method is used for applet initialization. It is called once when the applet is first
loaded.
start() Method:
The start() method is called when the applet becomes visible or starts running after being
paused.
stop() Method:
The stop() method is called when the applet is no longer visible or when it is paused.
destroy() Method:
The destroy() method is called when the applet is about to be unloaded.
Swing Components in Applets:
Like JFrame, JApplet can include various Swing components such as buttons, labels, and
panels.
Displaying in a Web Browser:
To display a JApplet in a web browser, an HTML file is typically used with the <applet> tag.
Swing Components in Applets:
Swing components can be added to a JApplet using the same principles as with a JFrame.
Layout Managers:
Layout managers such as FlowLayout, BorderLayout, or others can be used to organize
components within the applet.
Event Handling:
Event handling in applets in Swing applications, using listeners for user interactions.
Graphics and Drawing:
JApplet provides methods for custom drawing using the Graphics class, allowing developers
to create graphical content.
Applet Tag in HTML:
To embed a JApplet in an HTML page, the <applet> tag is used, specifying attributes like
code, width, height, and parameters.
Applet Life Cycle:
The applet life cycle is managed by the browser or applet viewer, calling the appropriate
methods at different stages.
Deprecated Usage:
While Swing applets were popular in the past, modern web development has shifted away
from using Java applets due to security concerns.

import javax.swing.JApplet;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyApplet extends JApplet


{

@Override
public void init()
{
// Initialization code (similar to a constructor)
JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Action to perform when the button is clicked
System.out.println("Button Clicked!");
}
});
add(button);
}

@Override
public void start()
{
// Called when the applet is started
}

@Override
public void stop()
{
// Called when the applet is stopped
}

@Override
public void destroy()
{
// Called when the applet is destroyed
}
}
Embedded with html :

<!DOCTYPE html>
<html>
<head>
<title>My Applet</title>
</head>
<body>
<applet code="MyApplet.class" width="300" height="200"></applet>
</body>
</html>

4) JPanel :

JPanel Class:
JPanel is a class in the javax.swing package that serves as a container to hold and organize
other Swing components.
Lightweight Container:
JPanel is a lightweight container, making it a versatile component for organizing and
grouping other Swing components.
Extending JPanel:
Developers can create custom panels by extending the JPanel class and adding their own
functionality.
Layout Managers:
JPanel can use layout managers, such as FlowLayout, BorderLayout, GridLayout, etc., to
manage the arrangement of components within the panel.
Adding Components:
Other Swing components like buttons, labels, and text fields can be added to a JPanel to
create a composite user interface.

Custom Drawing:
Developers can override the paintComponent(Graphics g) method to perform custom drawing
within a JPanel.
Event Handling:
JPanel can handle events using event listeners, allowing it to respond to user interactions or
other events.
Common Use:
JPanel is commonly used for grouping related components together, creating reusable and
modular UI elements

In Java Swing, a JPanel is a lightweight container that is typically used to organize and hold
other Swing components. However, to display a JPanel, it needs to be added to a top-level
container, such as a JFrame. A JFrame provides the main window or application frame
where Swing components, including JPanels, can be placed.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SwingJPanelExample extends JFrame


{

// Custom JPanel class


static class CustomPanel extends JPanel
{
private JButton button;

public CustomPanel()
{
// Create components
button = new JButton("Click me!");

// Add ActionListener to the button


button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// Display a message when the button is clicked
JOptionPane.showMessageDialog(CustomPanel.this,
"Button Clicked!", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
});

// Add components to the JPanel


add(button);
}
}

// Constructor for the main JFrame


public SwingJPanelExample()
{
// Set the title for the JFrame
super("Custom JPanel Example");

// Create a custom JPanel instance


CustomPanel customPanel = new CustomPanel();

// Set layout manager (FlowLayout for simplicity)


getContentPane().setLayout(new FlowLayout());

// Add the custom panel to the content pane of the JFrame


getContentPane().add(customPanel);

// Set default close operation and size


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);

// Center the JFrame on the screen


setLocationRelativeTo(null);

// Make the JFrame visible


setVisible(true);
}

// Main method to run the application


public static void main(String[] args)
{
// Create an instance of the JFrame

new SwingJPanelExample();
}
}

Output:
JDIALOG:

JDialog is a top-level container in Swing used to create dialogs or secondary windows in a


graphical user interface.

Purpose:
A JDialog is used to create pop-up dialogs or secondary windows that can contain various
components and user interface elements.
Extending JDialog:
Developers can create custom dialog boxes by extending the JDialog class.
Modality:
A JDialog can be modal or modeless. Modal dialogs block input to other application
windows until the dialog is closed.
Title:
A JDialog can have a title that is displayed in the title bar of the window.
Close Operation:
Developers can specify the default close operation, such as DISPOSE_ON_CLOSE or
DO_NOTHING_ON_CLOSE.
Size and Position:
The size and position of a JDialog can be set using methods like setSize() and
setLocationRelativeTo().
Visibility:
The setVisible() method is used to make the dialog visible or invisible.
Event Handling:
Event handling in a JDialog is similar to that in a JFrame, using listeners for user interactions.
Parent-Child Relationship:
A JDialog can be associated with a parent component, such as another JFrame. The dialog is
typically centered relative to its parent.
Customization:
Developers can customize the appearance and behavior of a JDialog to suit the requirements
of the application.

JDIALOG WITH OUT FRAME AS A PARENT :

import javax.swing.*;
import java.awt.*;

public class SimpleDialogExample extends JDialog {

public SimpleDialogExample() {
// ContentPane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(new JLabel("This is a simple dialog."));

// Configure JDialog
setTitle("Simple Dialog Example");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setSize(250, 150);
setLocationRelativeTo(null); // Center the dialog on the screen
setModalityType(ModalityType.APPLICATION_MODAL); // Make the dialog modal
setVisible(true);
}

public static void main(String[] args)


{

new SimpleDialogExample();
}

Output:

From Output :
There is no icons for minimize , maximize , hide in JDialog.
So to get all these icons JDialog need to maintain a parent-child relationship with JFrame.

JDIALOG WITH PARENT AS A FRAME :

import javax.swing.*;
import java.awt.*;

public class SimpleDialogExample2 extends JDialog


{
public SimpleDialogExample2(JFrame parent)
{
// ContentPane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(new JLabel("This is a simple dialog."));

// Configure JDialog
setTitle("Simple Dialog Example");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setSize(250, 150);
setLocationRelativeTo(parent);
setModalityType(ModalityType.APPLICATION_MODAL); // Make the dialog modal
setVisible(true);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
JFrame parentFrame = new JFrame("Parent Frame");
parentFrame.setSize(400, 300);
parentFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton showDialogButton = new JButton("Show Dialog");


showDialogButton.addActionListener(e -> {
new SimpleDialogExample2(parentFrame);
});

parentFrame.getContentPane().setLayout(new FlowLayout());
parentFrame.getContentPane().add(showDialogButton);
parentFrame.setLocationRelativeTo(null);
parentFrame.setVisible(true);
});
}
}

Output:

When click on “ show dialog “ button :

JCANVAS:

import javax.swing.*;
import java.awt.*;
class DrawingCanvas extends Canvas
{

@Override
public void paint(Graphics g)
{
// Draw on the canvas
g.setColor(Color.BLUE);
g.fillRect(50, 50, 100, 100);

g.setColor(Color.RED);
g.drawLine(200, 50, 300, 150);
}
}

public class SwingJCanvas extends JFrame


{

public SwingJCanvas()
{
setTitle("Simple Canvas Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a DrawingCanvas for drawing


DrawingCanvas drawingCanvas = new DrawingCanvas();

// Add the DrawingCanvas to the frame


add(drawingCanvas);
setVisible(true);
}

public static void main(String[] args)


{
new SwingJCanvas();
}
}

Output:

5. COMPONENTS IN SWINGS :

A) JBUTTON:
import javax.swing.JButton;
import javax.swing.JFrame;

public class JButtonExample extends JFrame


{
public JButtonExample()
{
setTitle("JButton Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton button = new JButton("Click Me");


getContentPane().add(button);

setVisible(true);
}

public static void main(String[] args)


{
new JButtonExample();
}
}
B) JTEXTFIELD:

import javax.swing.JFrame;
import javax.swing.JTextField;

public class JTextFieldExample extends JFrame


{
public JTextFieldExample()
{
setTitle("JTextField Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

JTextField textField = new JTextField("");


getContentPane().add(textField);

setVisible(true);
}

public static void main(String[] args)


{
new JTextFieldExample();
}
}

C) JTEXTAREA :

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class JTextAreaExample extends JFrame


{
public JTextAreaExample()
{
setTitle("JTextArea Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JTextArea textArea = new JTextArea(" ");


getContentPane().add(textArea);

setVisible(true);
}

public static void main(String[] args)


{
new JTextAreaExample();
}
}

Output:

D) JCHECKBOX:

import javax.swing.JCheckBox;
import javax.swing.JFrame;

public class JCheckBoxExample extends JFrame


{
public JCheckBoxExample()
{
setTitle("JCheckBox Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JCheckBox checkBox = new JCheckBox("Check Me");


getContentPane().add(checkBox);
setVisible(true);
}

public static void main(String[] args)


{
new JCheckBoxExample();
}
}

Output:

E) JRADIO BUTTON:
import javax.swing.JRadioButton;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
public class JRadioButtonExample extends JFrame
{
public JRadioButtonExample()
{
setTitle("JRadioButton Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout());

JRadioButton radioButton = new JRadioButton("Select csmb");


getContentPane().add(radioButton);
JRadioButton radioButton2 = new JRadioButton("Select csmc");
getContentPane().add(radioButton2);

setVisible(true);
}

public static void main(String[] args)


{
new JRadioButtonExample();
}
}

Output:
F) JCOMBOBOX:

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class JComboBoxExample extends JFrame


{
public JComboBoxExample()
{
setTitle("JComboBox Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

String[] options = {"Option 1", "Option 2", "Option 3"};


JComboBox<String> comboBox = new JComboBox<>(options);
getContentPane().add(comboBox);

setVisible(true);
}

public static void main(String[] args)


{
new JComboBoxExample();
}
}

Output:

When click on the scrollbar it will drag the options , then when select the option2 it
displayed.

G) JLABEL:

import javax.swing.JFrame;
import javax.swing.JLabel;

public class JLabelExample extends JFrame


{
public JLabelExample()
{
setTitle("JLabel Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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


getContentPane().add(label);

setVisible(true);
}

public static void main(String[] args)


{
new JLabelExample();
}
}

Output:

H) JFILECHOOSER
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

public class JFileChooserExample extends JFrame


{

public JFileChooserExample()
{
super("JFileChooser Example");

// Create a button to open the file chooser


JButton openButton = new JButton("Open File Chooser");
openButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
openFileChooser();
}
});

// Create a panel to hold the button


JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);

// Add components to the frame


add(buttonPanel);

// Set the default close operation and size


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setVisible(true);
}
private void openFileChooser()
{
JFileChooser fileChooser = new JFileChooser();

// Show the file chooser dialog


int result = fileChooser.showOpenDialog(this);

// Check if a file was selected


if (result == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
JOptionPane.showMessageDialog(this, "Selected File: " +
selectedFile.getAbsolutePath());
}
else
{
JOptionPane.showMessageDialog(this, "No file selected.");
}
}

public static void main(String[] args)


{
new JFileChooserExample();
}
}

Output:
When click on the “open file chooser “
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class JFileChooserExample2 extends JFrame {

private JTextArea textArea;

public JFileChooserExample2() {
super("JFileChooser Example");

// Create a JTextArea
textArea = new JTextArea();
textArea.setEditable(false);

// Create a button to open the file chooser


JButton fileButton = new JButton("Choose File");
fileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
chooseFile();
}
});
// Add components to the frame
add(new JScrollPane(textArea), BorderLayout.CENTER);
add(fileButton, BorderLayout.SOUTH);

// Set frame properties


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
//setLocationRelativeTo(null);
//the frame will be centered on the screen when displayed.
//If you leave it commented, the frame might appear at the top-left corner.
setVisible(true);
}

private void chooseFile() {


JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choose a File");
fileChooser.setFileFilter(new FileNameExtensionFilter("Text Files (*.txt)", "txt"));

int result = fileChooser.showOpenDialog(this);

if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
readFile(selectedFile);
}
}

private void readFile(File file) {


try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}

textArea.setText(content.toString());
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Error reading the file", "Error",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}

public static void main(String[] args) {

new JFileChooserExample2();
}
}

Output:
I) JCOLORCHOOSER:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JColorChooserExample extends JFrame


{

public JColorChooserExample()
{
super("JColorChooser Example");

// Create a button to open the color chooser


JButton openButton = new JButton("Open Color Chooser");
openButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
openColorChooser();
}
});

// Create a panel to hold the button


JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);

// Add components to the frame


add(buttonPanel);

// Set the default close operation and size


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setVisible(true);
}

private void openColorChooser()


{
Color initialColor = Color.BLACK; // Default initial color

// Show the color chooser dialog


Color selectedColor = JColorChooser.showDialog(this, "Choose a Color", initialColor);

// Check if a color was selected


if (selectedColor != null)
{
JOptionPane.showMessageDialog(this, "Selected Color: " + selectedColor);
}
else
{
JOptionPane.showMessageDialog(this, "No color selected.");
}
}

public static void main(String[] args)


{
new JColorChooserExample();
}
}

Output:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TextFieldColorChooserExample extends JFrame {

private JTextField textField;

public TextFieldColorChooserExample() {
super("TextField Color Chooser Example");

// Create a JTextField
textField = new JTextField("Type Here");
textField.setPreferredSize(new Dimension(200, 30));

// Create a button to open the color chooser


JButton colorButton = new JButton("Choose Color");
colorButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
chooseColor();
}
});

// Add components to the frame


add(textField, BorderLayout.CENTER);
add(colorButton, BorderLayout.SOUTH);

// Set frame properties


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}

private void chooseColor() {


// Show the color chooser dialog
Color chosenColor = JColorChooser.showDialog(this, "Choose a Color",
textField.getBackground());

// Update the background color of the text field


if (chosenColor != null) {
textField.setBackground(chosenColor);
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TextFieldColorChooserExample();
}
});
}
}

Output:
J) JTABLE:

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//DefaultTableModel class simplifies the management of tabular data in the JTable,


//providing methods to add, remove, and manipulate rows and columns dynamically.

public class JTableExample extends JFrame


{

private DefaultTableModel tableModel;


//A member variable tableModel of type DefaultTableModel
//is declared to hold the data for the JTable.

public JTableExample()
{
super("JTable Example");

// Create a table model with columns: Name, Age, Occupation


tableModel = new DefaultTableModel();
tableModel.addColumn("Name");
tableModel.addColumn("Age");
tableModel.addColumn("Occupation");

// Create a JTable with the table model


JTable table = new JTable(tableModel);

// Create a scroll pane and add the table to it


JScrollPane scrollPane = new JScrollPane(table);

// Create a button to add a new row


JButton addButton = new JButton("Add Row");
addButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
addRow();
}
});
// Create a panel to hold the button
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);

// Add components to the frame


add(scrollPane, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);

// Set the default close operation and size


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
}

private void addRow()


{
// Prompt the user for input
String name = JOptionPane.showInputDialog(this, "Enter Name:");
String age = JOptionPane.showInputDialog(this, "Enter Age:");
String occupation = JOptionPane.showInputDialog(this, "Enter Occupation:");

// Add a new row to the table


tableModel.addRow(new Object[]{name, age, occupation});
}

public static void main(String[] args)


{
new JTableExample();
}
}
Output:
K) JTREE:

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

public class MyJTreeExample2 extends JFrame {

public MyJTreeExample2(DefaultMutableTreeNode rootNode) {


super("JTree Example");

// Create a JTree with the given root node


JTree tree = new JTree(rootNode);

// Create a scroll pane and add the tree to it


JScrollPane scrollPane = new JScrollPane(tree);

// Add the scroll pane to the frame


getContentPane().add(scrollPane);

// Add a tree selection listener to detect node selection


tree.addTreeSelectionListener(new TreeSelectionListener()
{
@Override
public void valueChanged(TreeSelectionEvent e)
{
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
if (selectedNode != null)
{
// Perform actions based on the selected node
String nodeName = selectedNode.toString();
JOptionPane.showMessageDialog(MyJTreeExample2.this, "Selected Node: " +
nodeName);
}
}
});

// Set the default close operation to exit on close


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Set the frame size and make it visible


setSize(400, 300);
setVisible(true);
}

public static void main(String[] args) {


// Create a root node for the JTree
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");

// Create child nodes


DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Node 1");
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Node 2");

// Add child nodes to the root node


rootNode.add(node1);
rootNode.add(node2);

// Create an instance of MyJTreeExample with the root node


new MyJTreeExample2(rootNode);
}
}

Output:
L) 6) JLIST:
import javax.swing.JList;
import javax.swing.JFrame;

public class JListExample extends JFrame


{
public JListExample()
{
setTitle("JList Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

String[] items = {"Apple" , "orange","papaya","custurd apple", "pineapple" , "grape"};


JList<String> list = new JList<>(items);
getContentPane().add(list);

setVisible(true);
}

public static void main(String[] args)


{
new JListExample();
}
}
Output:
M) 7) JSCROLLPANE:

import javax.swing.*;

public class SwingJScrollPane


{
public static void main(String[] args)
{
// Create a JFrame
JFrame frame = new JFrame("JScrollPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);

// Create a JTextArea
JTextArea textArea = new JTextArea();
textArea.setText("This is a JTextArea with a JScrollPane.\nTry scrolling!");

// Create a JScrollPane and add the JTextArea to it


JScrollPane scrollPane = new JScrollPane(textArea);

// Add the JScrollPane to the JFrame


frame.add(scrollPane);

// Make the JFrame visible


frame.setVisible(true);
}
}
Output:

N) 8) SPLLITPANE:

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;

public class SwingJSplitPane extends JFrame


{
private JList<String> itemList;
private JTextArea textArea;

public SwingJSplitPane()
{
setTitle("JSplitPane Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] items = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7",
"Item 8"};
itemList = new JList<>(items);

textArea = new JTextArea();

// Add a ListSelectionListener to the JList


itemList.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
if (!e.getValueIsAdjusting()) {
// Get the selected item from the JList
String selectedValue = itemList.getSelectedValue();

// Display the selected item in the JTextArea


textArea.append("Selected Item: " + selectedValue + "\n");
}
}
});

// Create a JSplitPane with the JList on the left and JTextArea on the right
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new
JScrollPane(itemList), new JScrollPane(textArea));
splitPane.setDividerLocation(150); // Set initial divider location

getContentPane().add(splitPane);
setVisible(true);
}

public static void main(String[] args)


{
new SwingJSplitPane();
}
}

Output:

O) 9) JTABBEDPANE:

import javax.swing.*;
import java.awt.*;

public class SwingJTabbedPane extends JFrame


{
private JButton buttonTab1;
private JButton buttonTab2;
private JTextArea textAreaTab2;
private JTabbedPane tabbedPane;
public SwingJTabbedPane()
{
setTitle("Simple JTabbedPane Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

tabbedPane = new JTabbedPane();

// Create components for Tab 1


buttonTab1 = new JButton("Click me in Tab 1!");
buttonTab1.addActionListener(e -> showMessage("Button Clicked in Tab 1"));
tabbedPane.addTab("Tab 1", buttonTab1);

// Create components for Tab 2


textAreaTab2 = new JTextArea();
buttonTab2 = new JButton("Click me in Tab 2!");
buttonTab2.addActionListener(e -> showMessage("Button Clicked in Tab 2"));

JPanel tab2Panel = new JPanel(new BorderLayout());


tab2Panel.add(new JScrollPane(textAreaTab2), BorderLayout.CENTER);
tab2Panel.add(buttonTab2, BorderLayout.SOUTH);
tabbedPane.addTab("Tab 2", tab2Panel);

getContentPane().setLayout(new BorderLayout());
getContentPane().add(tabbedPane, BorderLayout.CENTER);

setVisible(true);
}
private void showMessage(String message) {
JOptionPane.showMessageDialog(this, message, "Message",
JOptionPane.INFORMATION_MESSAGE);
}

public static void main(String[] args) {


new SwingJTabbedPane();
}
}

Output:

10) DIALOG BOX:

import javax.swing.*;
import java.awt.*;
public class SimpleDialogExample2 extends JDialog
{

public SimpleDialogExample2(JFrame parent)


{
// ContentPane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(new JLabel("This is a simple dialog."));

// Configure JDialog
setTitle("Simple Dialog Example");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setSize(250, 150);
setLocationRelativeTo(parent);
setModalityType(ModalityType.APPLICATION_MODAL); // Make the dialog modal
setVisible(true);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
JFrame parentFrame = new JFrame("Parent Frame");
parentFrame.setSize(400, 300);
parentFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton showDialogButton = new JButton("Show Dialog");


showDialogButton.addActionListener(e -> {
new SimpleDialogExample2(parentFrame);
});
parentFrame.getContentPane().setLayout(new FlowLayout());
parentFrame.getContentPane().add(showDialogButton);

parentFrame.setLocationRelativeTo(null);
parentFrame.setVisible(true);
});
}
}

Output:

JOptionPane in Swing:

1. Usage:
 JOptionPane is a class in Swing that provides a standard way to prompt users
for input or inform them about an event in a GUI.
 It simplifies the creation and display of dialog boxes with consistent
appearance.
2. Creating Dialog Boxes:
 You can create various types of dialog boxes, including message, input,
confirm, and option dialogs.
 JOptionPane.showMessageDialog(null, "Hello, this is a message
dialog", "Message", JOptionPane.INFORMATION_MESSAGE);
3. Message Types:
 JOptionPane supports different message types such as
INFORMATION_MESSAGE, WARNING_MESSAGE, ERROR_MESSAGE,
QUESTION_MESSAGE, and PLAIN_MESSAGE .
4. Input Dialog:
 JOptionPane.showInputDialog creates an input dialog that prompts the user
for input.
String userInput = JOptionPane.showInputDialog("Enter your name:"); ;
5. Confirm Dialog:
 JOptionPane.showConfirmDialog creates a dialog with options like
Yes/No/Cancel and returns the user's choice.
 int result = JOptionPane.showConfirmDialog(null, "Do you want to
proceed?", "Confirmation", JOptionPane.YES_NO_CANCEL_OPTION);
6. Custom Buttons:
 You can customize buttons in option dialogs using an array of objects
representing the button names.
 Object[] options = {"Option 1", "Option 2", "Option 3"};
 int result = JOptionPane.showOptionDialog(null, "Choose an option",
"Custom Buttons", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
7. Icons:
 You can display icons in JOptionPane dialogs to visually represent the type of
message.
.ERROR_MESS JOptionPane.showMessageDialog(null, "Error Message",
"Error", JOptionPane.ERROR_MESSAGE); AGE);
8. Custom Icons:
 Custom icons can be added to dialogs using ImageIcon or other Icon
implementations.
 ImageIcon customIcon = new ImageIcon("path/to/custom-icon.png");
 JOptionPane.showMessageDialog(null, "Custom Icon Message",
"Custom Icon", JOptionPane.INFORMATION_MESSAGE, customIcon);
9. Default Button:
 You can set the default button in a dialog, which is activated when the user
presses Enter.
 int result = JOptionPane.showConfirmDialog(null, "Choose Yes or No",
"Default Button", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null,
JOptionPane.YES_OPTION);
10. Option Dialog Return Values:
 The return value of an option dialog depends on the user's choice and can be
used to determine the selected option.
11. if (result == JOptionPane.YES_OPTION) {
12. // User chose Yes
13. } else if (result == JOptionPane.NO_OPTION) {
14. // User chose No
15. } else if (result == JOptionPane.CANCEL_OPTION) {
16. // User chose Cancel

You might also like