Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views78 pages

Explanation of Swing Programs

This document provides examples of simple Java Swing applications, demonstrating how to create GUI components such as frames, buttons, and labels. Each program showcases different functionalities, including event handling and customizations like fonts and colors. The explanations detail the steps involved in building these applications, emphasizing the use of Swing's components and layout management.

Uploaded by

4al22cs128
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)
10 views78 pages

Explanation of Swing Programs

This document provides examples of simple Java Swing applications, demonstrating how to create GUI components such as frames, buttons, and labels. Each program showcases different functionalities, including event handling and customizations like fonts and colors. The explanations detail the steps involved in building these applications, emphasizing the use of Swing's components and layout management.

Uploaded by

4al22cs128
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/ 78

Explanation of Swing programs

Example of a Simple Swing Program:


Program 1:
Here's a basic Swing application that creates a window with a button and a label.

package Swings;

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

public class SimpleSwingApp {


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

// Create a button
JButton button = new JButton("Click Me!");

// Create a label
// JLabel label = new JLabel("Welcome to Swing!");
JLabel label = new JLabel("Press button to display the message!");
// Add action listener to the button
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("Hello! VI A,B,C sec Students! Welcome to Swing!");
}
});

// Add the button and label to the frame


JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
frame.add(panel);

// Set frame visibility


frame.setVisible(true);
}
}

o/p
Explanation :

Step 1: Package and Import Statements

package Swings;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
package Swings;: This declares that the class SimpleSwingApp belongs to the package named Swings.
import javax.swing.*;: This imports all the classes from the javax.swing package, which is essential for
creating GUIs in Java.
import java.awt.event.ActionEvent;: Imports the ActionEvent class used to handle action events (like
button clicks).
import java.awt.event.ActionListener;: Imports the ActionListener interface that listens for action
events.

Step 2: Class Declaration

public class SimpleSwingApp {


This line defines a public class named SimpleSwingApp. It is the main class that will contain the Swing
application.

Step 3: main Method

public static void main(String[] args) {


This is the main entry point of the Java application. The main method is where the execution of the
program begins.

Step 4: Creating a Frame

JFrame frame = new JFrame("Simple Swing Application");


frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFrame frame = new JFrame("Simple Swing Application");: This creates a new window (frame) titled
"Simple Swing Application".
frame.setSize(300, 200);: This sets the size of the frame to 300 pixels wide and 200 pixels tall.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);: This specifies the operation to take
when the user closes the window. EXIT_ON_CLOSE means that the application will terminate.

Step 5: Creating a Button

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


This creates a button labeled "Click Me!". The button is an interactive component that users can click.

Step 6: Creating a Label

JLabel label = new JLabel("Press button to display the message!");


This creates a label that initially displays the text "Press button to display the message!". This label is
used to show messages to the user.

Step 7: Adding Action Listener to the Button

button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("Hello! VI A,B,C sec Students! Welcome to Swing!");
}
});
Here, an ActionListener is added to the button. This listener responds to action events (like a button
click).
actionPerformed method: This method is called when the button is clicked. Within this method:
The label's text is updated to "Hello! VI A,B,C sec Students! Welcome to Swing!", providing feedback
to the user when the button is clicked.

Step 8: Creating a Panel and Adding Components

JPanel panel = new JPanel();


panel.add(button);
panel.add(label);
frame.add(panel);
JPanel panel = new JPanel();: This creates a new panel, which is a container for organizing
components.
panel.add(button); and panel.add(label);: These lines add the button and label to the panel.
frame.add(panel);: This adds the panel to the frame, allowing the button and label to be displayed.

Step 9: Setting Frame Visibility

frame.setVisible(true);

This line makes the frame visible to the user. If it is not set to visible, the frame will not appear on the
screen.
Summary

In summary, this Java Swing application creates a simple GUI with a button and a label. When the
button is clicked, the text on the label changes to a greeting message. The application showcases the
fundamental elements of building interactive GUI applications in Java using the Swing library.

Program 2:

package Swings;

import java.awt.Color;
import java.awt.Font;

//A simple Swing application.


import javax.swing.*;
class SwingExample {
SwingExample () {
//Create a new JFrame container.
JFrame jfrm = new JFrame("A Simple Swing Application");
//jfrm.setFont("Serif",Font.BOLD,18);

//label = new JLabel("A label"); label.setFont(new Font("Serif", Font.PLAIN, 14));


//Give the frame an initial size.
jfrm.setSize(275, 100);
//Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create a text-based label.
JLabel jlab = new JLabel(" Hello! VI B , Welcome to Swing Programming!");
// set properties for label
jlab.setFont(new Font("Verdana", Font.PLAIN,32));
jlab.setForeground(new Color(0,0,255));

//Add the label to the content pane.


jfrm.add(jlab);
//Display the frame.
jfrm.setVisible(true);
}
public static void main(String args[]) {
//Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SwingExample();
}
});
}
}
Explanation :

simple Swing application.

Step 1: Package and Import Statements

package Swings
import java.awt.Color;
import java.awt.Font;
import javax.swing.*;

package Swings;: Declares that this class belongs to the Swings package.
import java.awt.Color;: Imports the Color class from the java.awt package, which is used to set colors
for components.
import java.awt.Font;: Imports the Font class from the java.awt package, which is used to set fonts for
components.
import javax.swing.*;: Imports all classes from the javax.swing package, which is used for creating
GUI applications in Java.

Step 2: Class Declaration

class SwingExample {
This defines a class named SwingExample. The class contains the main logic for the Swing application.

Step 3: Constructor

SwingExample() {
This is the constructor for the SwingExample class. It is called when an instance of SwingExample is
created.

Step 4: Creating a JFrame

JFrame jfrm = new JFrame("A Simple Swing Application");


This creates a new JFrame object named jfrm, which serves as the main window of the application. It is
titled "A Simple Swing Application".

Step 5: Setting Frame Size and Close Operation

jfrm.setSize(275, 100);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfrm.setSize(275, 100);: Sets the size of the frame to 275 pixels wide and 100 pixels tall.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);: Specifies that the application should
terminate when the window is closed.

Step 6: Creating a JLabel

JLabel jlab = new JLabel(" Hello! VI B , Welcome to Swing Programming!");


This creates a JLabel object named jlab, displaying the text " Hello! VI B, Welcome to Swing
Programming!".

Step 7: Setting Properties for the Label

jlab.setFont(new Font("Verdana", Font.PLAIN,32));


jlab.setForeground(new Color(0,0,255));
jlab.setFont(new Font("Verdana", Font.PLAIN,32));: Sets the font of the label to "Verdana", with a
plain style and a size of 32 points.
jlab.setForeground(new Color(0,0,255));: Sets the color of the text to blue. The Color object is created
using RGB values (0, 0, 255), which corresponds to blue.

Step 8: Adding the Label to the Frame

jfrm.add(jlab);
This adds the jlab label to the content pane of the jfrm frame, allowing it to be displayed within the
window.

Step 9: Displaying the Frame

jfrm.setVisible(true);
This line makes the frame visible to the user. The frame will not appear until it is set to visible.

Step 10: Main Method

public static void main(String args[]) {


This defines the main method, which is the entry point for the application.

Step 11: Event Dispatching Thread

SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SwingExample();
}
});

SwingUtilities.invokeLater(...): This schedules the creation of the SwingExample instance for


execution on the Event Dispatching Thread (EDT), which is responsible for managing the GUI in
Swing applications. This is important for ensuring thread safety in GUI applications.
new SwingExample();: This creates a new instance of SwingExample, which calls the constructor and
thus sets up the GUI.
Summary:

In summary, this Java code creates a simple Swing application with a frame that displays a welcome
message in blue text using a large font. The application demonstrates fundamental concepts of Swing,
including window creation with JFrame, text display using JLabel, customizing fonts and colors, and
proper use of the Event Dispatching Thread for GUI updates.

Program 3 :

package Swings;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ButtonExample{
JLabel l1;
ButtonExample(){
JFrame f=new JFrame("Button Example");

l1=new JLabel();
l1.setBounds(50,50, 700,100);
l1.setFont(new Font("Lucida Calligraphy",Font.BOLD,60));

JButton b1=new JButton(" India ");


JButton b2=new JButton(" Srilanka ");

b1.setBounds(100,200,100, 100);

b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
l1.setText("India is pressed");
}
});

b2.setBounds(400,200,100, 100);
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
l1.setText("SriLanka is pressed");
}
});

f.add(b1);
f.add(b2);
f.add(l1);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ButtonExample();
}
}

Explanation :

Step 1: Package and Import Statements

package Swings;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

package Swings;: This declares that the ButtonExample class belongs to the Swings package.
import java.awt.Font;: Imports the Font class from java.awt, which is used for setting font properties of
Swing components.
import java.awt.event.ActionEvent; and import java.awt.event.ActionListener;: These classes are used
to define actions that can occur in response to user interactions (like button clicks).
import javax.swing.*;: Imports all classes from the javax.swing package, which is used for building
graphical user interfaces.

Step 2: Class Declaration

public class ButtonExample {


This defines a public class named ButtonExample. The class contains all the code for the Swing
application.

Step 3: JLabel Declaration

JLabel l1;
This declares a JLabel instance variable l1 that will be used to display messages when buttons are
pressed.

Step 4: Constructor
ButtonExample() {
This is the constructor for the ButtonExample class. It is called when an instance of ButtonExample is
created, where the GUI components are initialized.

Step 5: Creating a JFrame

JFrame f = new JFrame("Button Example");


This creates a new JFrame object named f, which serves as the main window and is titled "Button
Example".

Step 6: Creating and Setting Up the JLabel

l1 = new JLabel();
l1.setBounds(50, 50, 700, 100);
l1.setFont(new Font("Lucida Calligraphy", Font.BOLD, 60));
l1 = new JLabel();: Creates a new JLabel instance.
l1.setBounds(50, 50, 700, 100);: This sets the position and size of the label. It starts at (50, 50) pixels,
with a width of 700 pixels and a height of 100 pixels.
l1.setFont(new Font("Lucida Calligraphy", Font.BOLD, 60));: Sets the font of the label to "Lucida
Calligraphy", with a bold style and size of 60 points.

Step 7: Creating Buttons

JButton b1 = new JButton(" India ");


JButton b2 = new JButton(" Srilanka ");
This creates two buttons: b1 labeled "India" and b2 labeled "SriLanka".

Step 8: Setting Bounds for Button 1

b1.setBounds(100, 200, 100, 100);


This sets the position and size of button b1. It starts at (100, 200) pixels, with a width of 100 pixels and
a height of 100 pixels.

Step 9: Adding ActionListener to Button 1

b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
l1.setText("India is pressed");
}
});
b1.addActionListener(new ActionListener() {...});: This adds an ActionListener to button b1, which
listens for button clicks.
actionPerformed method: This method is called when button b1 is pressed. Inside this method, the text
of label l1 is updated to "India is pressed".

Step 10: Setting Bounds for Button 2

b2.setBounds(400, 200, 100, 100);


This sets the position and size of button b2, starting at (400, 200) pixels, with a width of 100 pixels and
a height of 100 pixels.

Step 11: Adding ActionListener to Button 2

b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
l1.setText("SriLanka is pressed");
}
});

Similar to button b1, this adds an ActionListener to button b2. When b2 is pressed, the text of label l1 is
updated to "SriLanka is pressed".

Step 12: Adding Components to the Frame

f.add(b1);
f.add(b2);
f.add(l1);
This adds buttons b1, b2, and label l1 to the frame f, which allows them to be displayed in the window.

Step 13: Setting Frame Properties

f.setSize(300, 400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300, 400);: Sets the size of the frame to 300 pixels wide and 400 pixels tall.
f.setLayout(null);: The layout manager is set to null, which allows for absolute positioning of
components on the frame (manual positioning using setBounds).
f.setVisible(true);: Makes the frame visible to the user.
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);: Specifies that the application should
terminate when the window is closed.

Step 14: Main Method

public static void main(String[] args) {


new ButtonExample();
}
This defines the main method, which is the entry point for the application. It creates a new instance of
ButtonExample,
triggering the constructor and setting up the GUI.

Summary

In summary, this code creates a simple Swing application with two buttons ("India" and "SriLanka")
and a label that updates its text based on which button is pressed. It demonstrates key concepts in
Swing, such as creating frames, buttons, labels, and handling user interactions with action listeners.
The layout is set to null, allowing for precise positioning of components using setBounds.
Program 4 :

package Swings;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

// This class extends JPanel and overrides paintComponent()


// to plot random lines in the panel
class PaintPanel extends JPanel {
private Insets ins; // holds the panel's insets
private Random rand; // used to generate random numbers

// Construct a panel
PaintPanel() {
// Put a border around the panel
setBorder(BorderFactory.createLineBorder(Color.RED, 5));
rand = new Random();
}

// Override the paintComponent() method


@Override
protected void paintComponent(Graphics g) {
// Always call the superclass method first
super.paintComponent(g);

int x, y, x2, y2;

// Get the height and width of the component


int height = getHeight();
int width = getWidth();

// Get the insets


ins = getInsets();

// Draw ten lines whose endpoints are randomly generated


for(int i = 0; i < 10; i++) {
// Obtain random coordinates that define
// the endpoints of each line
x = rand.nextInt(width - ins.left);
y = rand.nextInt(height - ins.bottom);
x2 = rand.nextInt(width - ins.left);
y2 = rand.nextInt(height - ins.bottom);

// Draw the line


g.drawLine(x, y, x2, y2);
}
}
}

// Demonstrate painting directly onto a panel


public class PaintDemo {
private JLabel jlab;
private PaintPanel pp;
private JFrame jfrm;

public PaintDemo() {
// Create a new JFrame container
jfrm = new JFrame("Paint Demo");

// Give the frame an initial size


jfrm.setSize(200, 150);

// Terminate the program when the user closes the application


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create the panel that will be painted


pp = new PaintPanel();

// Add the panel to the content pane. Because the default


// border layout is used, the panel will automatically be
// sized to fit the center region
jfrm.add(pp);

// Display the frame


jfrm.setVisible(true);
}

public static void main(String args[]) {


// Create the frame on the event dispatching thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new PaintDemo();
}
});
}
}
o/p

Explanation

Step 1: Package and Import Statements

package Swings;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
package Swings;: Declares the class package as Swings.
import java.awt.*;: Imports all the classes from the java.awt package, which includes graphics and
layout management classes.
import java.awt.event.*;: Imports all classes related to event handling.
import javax.swing.*;: Imports all classes from the javax.swing package, which is used for creating
GUI components.
import java.util.*;: Imports classes from the java.util package, including the Random class that will be
used for generating random numbers.

Step 2: PaintPanel Class Definition

class PaintPanel extends JPanel {


private Insets ins; // holds the panel's insets
private Random rand; // used to generate random numbers

// Construct a panel
PaintPanel() {
// Put a border around the panel
setBorder(BorderFactory.createLineBorder(Color.RED, 5));
rand = new Random();
}
class PaintPanel extends JPanel: Defines a new class PaintPanel that inherits from JPanel. JPanel is a
component that can be drawn on.
private Insets ins;: Declares an instance variable to hold the insets (margins) of the panel.
private Random rand;: Declares an instance variable for generating random numbers.
Constructor PaintPanel(): Initializes the PaintPanel, setting a red border with a thickness of 5 pixels and
creating a new Random object.

Step 3: Overriding the paintComponent Method

@Override
protected void paintComponent(Graphics g) {
// Always call the superclass method first
super.paintComponent(g);

int x, y, x2, y2;

// Get the height and width of the component


int height = getHeight();
int width = getWidth();

// Get the insets


ins = getInsets();

// Draw ten lines whose endpoints are randomly generated


for(int i = 0; i < 10; i++) {
// Obtain random coordinates that define the endpoints of each line
x = rand.nextInt(width - ins.left);
y = rand.nextInt(height - ins.bottom);
x2 = rand.nextInt(width - ins.left);
y2 = rand.nextInt(height - ins.bottom);

// Draw the line


g.drawLine(x, y, x2, y2);
}
}
protected void paintComponent(Graphics g): This method is overridden to define custom painting logic
for the panel. The Graphics object g is used to perform drawing operations.
super.paintComponent(g);: Always call this first to ensure that the panel is properly rendered before
executing custom drawing.
Retrieve dimensions: Get the current height and width of the component using getHeight() and
getWidth().
Get Insets: Use getInsets() to retrieve the panel's insets, which represent the space between the panel's
edges and its contents.
Draw random lines: A loop is executed ten times, generating random coordinates (x, y) and (x2, y2) for
the endpoints of lines. The lines are drawn using g.drawLine(x, y, x2, y2);.
Step 4: PaintDemo Class Definition

public class PaintDemo {


private JLabel jlab;
private PaintPanel pp;
private JFrame jfrm;
public class PaintDemo: This defines the main class of the application, which sets up the GUI.
Instance variables: jlab for a JLabel (not actually used in this code), pp for a PaintPanel, and jfrm for
the main JFrame.

Step 5: Constructor for PaintDemo

public PaintDemo() {
// Create a new JFrame container
jfrm = new JFrame("Paint Demo");

// Give the frame an initial size


jfrm.setSize(200, 150);

// Terminate the program when the user closes the application


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create the panel that will be painted


pp = new PaintPanel();

// Add the panel to the content pane. Because the default border layout is used, the panel will
automatically be sized to fit the center region
jfrm.add(pp);

// Display the frame


jfrm.setVisible(true);
}
jfrm = new JFrame("Paint Demo");: Creates a new JFrame titled "Paint Demo".
jfrm.setSize(200, 150);: Sets the size of the frame to 200 pixels wide and 150 pixels tall.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);: Specifies that the application should
terminate when the window is closed.
pp = new PaintPanel();: Creates an instance of the PaintPanel, which will handle its own drawing.
jfrm.add(pp);: Adds the PaintPanel to the JFrame. Since no layout manager is set (JFrame uses
BorderLayout by default), the panel will be centered in the frame.

jfrm.setVisible(true);: This makes the JFrame visible to the user once it's fully set up.

Step 6: Main Method

public static void main(String args[]) {


// Create the frame on the event dispatching thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new PaintDemo();
}
});
}
public static void main(String args[]): This is the entry point of the application.
SwingUtilities.invokeLater(...): Ensures that the GUI is created on the Event Dispatch Thread (EDT),
which is the correct thread for updating Swing components. This prevents potential threading issues.
new PaintDemo();: Creates a new instance of PaintDemo, triggering the GUI setup as defined in the
constructor.

Summary
The code creates a simple Swing GUI application that demonstrates how to draw graphical content
directly onto a panel. The PaintPanel class overrides the paintComponent method to draw ten random
lines each time the panel is repainted. The main application class, PaintDemo, sets up a JFrame and
adds the PaintPanel to it, displaying the random drawings when the application runs. The use of the
random number generator ensures that the lines will appear differently each time the panel is repainted
(e.g., if resized or uncovered).

Program 5 :

package Swings;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class JListExample extends JFrame {


private JList<String> countryList;
public JListExample() {
//create the model and add elements
DefaultListModel<String> listModel = new DefaultListModel<>();
listModel.addElement("USA");
listModel.addElement("India");
listModel.addElement("Vietnam");
listModel.addElement("Canada");
listModel.addElement("Denmark");
listModel.addElement("France");
listModel.addElement("Great Britain");
listModel.addElement("Japan");
listModel.addElement("Africa");
listModel.addElement("Greenland");
listModel.addElement("Singapore");
listModel.addElement("");
//create the list
countryList = new JList<>(listModel);
countryList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
final List<String> selectedValuesList = countryList.getSelectedValuesList();
System.out.println(selectedValuesList);
}
}
});
add(new JScrollPane(countryList));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("JList Example");
this.setSize(200, 200);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new JListExample();
}
}

Explanation

Step 1: Package and Import Statements

package Swings;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

package Swings;: Declares that the JListExample class is part of the Swings package.
Import Statements:
import java.util.List;: Imports the List interface from the Java Collections Framework, useful for
working with lists of objects.
import javax.swing.DefaultListModel;: Imports the DefaultListModel, which is the model that holds
the data for the JList.
import javax.swing.JFrame;: Imports the JFrame class, which provides a window for the GUI.
import javax.swing.JList;: Imports the JList class, which can display a list of items in a GUI.
import javax.swing.JScrollPane;: Imports the JScrollPane class, which provides scroll bars for a
component if the component is too large to fit in the visible area.
import javax.swing.event.ListSelectionEvent;: Imports the event class used for list selection.
import javax.swing.event.ListSelectionListener;: Imports the listener interface that receives events
when the selection in the list changes.

Step 2: JListExample Class Definition

public class JListExample extends JFrame {


private JList<String> countryList;
public class JListExample extends JFrame: Defines the JListExample class inheriting from JFrame,
meaning JListExample will be a window (frame) in the GUI.
private JList<String> countryList;: Declares an instance variable of type JList that will hold a list of
strings (in this case, country names).

Step 3: Constructor

public JListExample() {
This is the constructor for the JListExample class, where the GUI components are initialized.

Step 3.1: Model Creation and Population

// create the model and add elements


DefaultListModel<String> listModel = new DefaultListModel<>();
listModel.addElement("USA");
listModel.addElement("India");
listModel.addElement("Vietnam");
listModel.addElement("Canada");
listModel.addElement("Denmark");
listModel.addElement("France");
listModel.addElement("Great Britain");
listModel.addElement("Japan");
listModel.addElement("Africa");
listModel.addElement("Greenland");
listModel.addElement("Singapore");
listModel.addElement("");
DefaultListModel<String> listModel = new DefaultListModel<>();: Creates a new DefaultListModel,
which is a model that maintains a list of items (in this case, country names).
listModel.addElement(...): Adds various country names to the list model. Each call adds a string to the
model.

Step 3.2: Creating the JList

// create the list


countryList = new JList<>(listModel);
countryList = new JList<>(listModel);: Initializes the JList countryList using the listModel created
earlier. This links the list to the model containing the country names.

Step 3.3: Adding a List Selection Listener

countryList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
final List<String> selectedValuesList = countryList.getSelectedValuesList();
System.out.println(selectedValuesList);
}
}
});
countryList.addListSelectionListener(...): Attaches an event listener to the countryList to handle
selection changes.
Anonymous inner class: Implements the ListSelectionListener interface.
valueChanged(ListSelectionEvent e): This method is called whenever the selection in the list changes.
!e.getValueIsAdjusting(): This checks if the selection is still being adjusted (meaning it’s not yet final).
If it’s not adjusting, it proceeds to get the selected items.
final List<String> selectedValuesList = countryList.getSelectedValuesList();: Gets the list of selected
values from countryList.
System.out.println(selectedValuesList);: Prints the list of selected countries to the console.

Step 3.4: Adding the JScrollPane

add(new JScrollPane(countryList));
add(new JScrollPane(countryList));: Wraps the countryList inside a JScrollPane and adds it to the
frame. This allows for scrolling if there are too many items to display in the visible area of the list.

Step 4: Setting JFrame Properties

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("JList Example");
this.setSize(200, 200);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);: Sets the operation that will happen by
default when the user closes the frame. Here, it will exit the application.
this.setTitle("JList Example");: Sets the title of the JFrame to "JList Example".
this.setSize(200, 200);: Sets the size of the JFrame to 200 pixels wide and 200 pixels tall.
this.setLocationRelativeTo(null);: Centers the window on the screen.
this.setVisible(true);: Makes the JFrame visible to the user.

Step 5: Main Method

public static void main(String[] args) {


new JListExample();
}

public static void main(String[] args): This is the entry point of the Java application.
new JListExample();: Creates an instance of JListExample, which triggers the constructor and sets up
the GUI.

Summary

Overall, this code creates a simple Swing application that displays a list of countries in a scrollable
JList. Users can select a country, and the selected value(s) will be printed to the console. It uses a
DefaultListModel to manage the list data, a JList to display it, and a JScrollPane to allow scrolling
through the list. The application is structured to ensure it exits cleanly when the window is closed.

Login Form

package Swings;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class login {

public static void main(String[] args) {


// Creating instance of JFrame
JFrame frame = new JFrame("My First Swing Example");
// Setting the width and height of frame
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

/* Creating panel. This is same as a div tag in HTML


* We can create several panels and add them to specific
* positions in a JFrame. Inside panels we can add text
* fields, buttons and other components.
*/
JPanel panel = new JPanel();
// adding panel to frame
frame.add(panel);

/* calling user defined method for adding components


* to the panel.
*/
placeComponents(panel);

// Setting the frame visibility to true


frame.setVisible(true);
}

private static void placeComponents(JPanel panel) {

/* We will discuss about layouts in the later sections


* of this tutorial. For now we are setting the layout
* to null
*/
panel.setLayout(null);

// Creating JLabel
JLabel userLabel = new JLabel("User");
JLabel jl= new JLabel();
jl.setBounds(30,130,400,40);
jl.setFont(new Font("Arial", Font.BOLD, 24));

/* This method specifies the location and size


* of component. setBounds(x, y, width, height)
* here (x,y) are coordinates from the top left
* corner and remaining two arguments are the width
* and height of the component.
*/
userLabel.setBounds(10,20,80,25);
panel.add(userLabel);

/* Creating text field where user is supposed to


* enter user name.
*/
JTextField userText = new JTextField(20);
userText.setBounds(100,20,165,25);
panel.add(userText);

// Same process for password label and text field.


JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10,50,80,25);
panel.add(passwordLabel);

/*This is similar to text field but it hides the user


* entered data and displays dots instead to protect
* the password like we normally see on login screens.
*/
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);

// Creating login button


JButton loginButton = new JButton("login");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
panel.add(jl);
loginButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
jl.setText("you have successfully logged in!");
}
});
}

}
Explanation

Step 1: Package Declaration

package Swings;
This line declares that the class login belongs to the package Swings. Grouping related classes in
packages helps in organizing the code.

Step 2: Import Statements

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
These lines import necessary classes from the AWT and Swing libraries:
Font is used for setting text fonts.
ActionEvent and ActionListener are used to handle events, like button clicks.
JButton, JFrame, JLabel, JPanel, JPasswordField, JTextField are GUI components from the Swing
library.

Step 3: The Main Class Declaration

public class login {


Here we define a public class named login. By convention, class names in Java should start with an
uppercase letter; it’s better to name this class Login.

Step 4: The Main Method

public static void main(String[] args) {


The main method is the entry point for the program. When the application is run, this method is
executed.

Step 5: Creating a JFrame

JFrame frame = new JFrame("My First Swing Example");


An instance of JFrame is created, representing the main window of the application. The string argument
passed to the constructor sets the window title.
CopyReplit
frame.setSize(350, 200);
This sets the width to 350 pixels and height to 200 pixels.
CopyReplit
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
This line ensures that the application exits when the JFrame window is closed.

Step 6: Creating a JPanel

JPanel panel = new JPanel();


frame.add(panel);
A JPanel is created, which serves as a container for other components. After creating the panel, it is
added to the JFrame.

Step 7: Adding Components to the Panel

placeComponents(panel);
The method placeComponents is called, and the panels are populated with various components such as
labels, text fields, and buttons.

Step 8: Setting Frame Visibility

frame.setVisible(true);
This line makes the JFrame visible, allowing the user to see the GUI.

Step 9: Defining the placeComponents Method

private static void placeComponents(JPanel panel) {


This method is where various GUI components are created and positioned within the panel.

Step 9.1: Setting the Layout

panel.setLayout(null);
This sets the layout of the panel to null, allowing absolute positioning of components. (Note: It's often
better to use layout managers for flexibility and responsiveness.)

Step 9.2: Creating and Positioning Components

JLabel userLabel = new JLabel("User");


A label for the username field is created.

userLabel.setBounds(10,20,80,25);
panel.add(userLabel);
The label's position and size are set using setBounds, and then added to the panel.
Similarly, the username text field:

JTextField userText = new JTextField(20);


userText.setBounds(100,20,165,25);
panel.add(userText);
The password label and field are added similarly.

JLabel passwordLabel = new JLabel("Password");


passwordLabel.setBounds(10,50,80,25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);

Step 9.3: Creating and Configuring the Button

JButton loginButton = new JButton("login");


loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
A login button is created, positioned, and added to the panel.

Step 9.4: Adding Action Listener to the Button

loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jl.setText("you have successfully logged in!");
}
});
An ActionListener is added to the login button. When the button is clicked, the actionPerformed
method is executed, which will display a confirmation message in the JLabel jl (defined earlier).

Step 10: Final Notes

The program creates a basic UI for logging in but lacks actual authentication functionality. The
message displayed after clicking the login button is static and does not check user credentials.

Tabbed Pane Example

package Swings;
import java.awt.Color;

import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame();

JPanel p1=new JPanel();

JPanel p2=new JPanel();


JPanel p3=new JPanel();
p1.setBackground(Color.BLUE);
p2.setBackground(Color.RED);
p3.setBackground(Color.GREEN);
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("BLUE",p1);
tp.add("RED",p2);
tp.add("GREEN",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new TabbedPaneExample();
}}

Explanation

Step 1: Package Declaration

package Swings;
This line indicates that the class TabbedPaneExample belongs to the Swings package. This helps in
organizing Java classes logically.

Step 2: Import Statements

import java.awt.Color;
import javax.swing.*;
These lines import necessary classes from the AWT and Swing libraries:
Color is used for setting background colors of the panels.
JFrame, JPanel, and JTabbedPane are used to create and manage the GUI components.

Step 3: Class Declaration

public class TabbedPaneExample {


Defines a public class named TabbedPaneExample. This is the main class that contains the GUI logic.
Step 4: Instance Variable Declaration

JFrame f;
An instance variable f of type JFrame is declared. This variable will hold the main window of the
application.

Step 5: Constructor Method

TabbedPaneExample() {
The constructor for the TabbedPaneExample class is defined here. It initializes the GUI components
when an object of this class is created.

Step 6: JFrame Initialization

f = new JFrame();
A new instance of JFrame is created and assigned to the variable f. This serves as the main application
window.

Step 7: Creating Panels

JPanel p1 = new JPanel();


JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
Three different JPanel instances are created: p1, p2, and p3. These panels will be added to the tabbed
pane.

Step 8: Setting Panel Background Colors

p1.setBackground(Color.BLUE);
p2.setBackground(Color.RED);
p3.setBackground(Color.GREEN);
The background colors of the three panels are set using predefined Color constants:
p1 is set to blue.
p2 is set to red.
p3 is set to green.
Step 9: Creating and Configuring the JTabbedPane

JTabbedPane tp = new JTabbedPane();


A new instance of JTabbedPane is created and assigned to the variable tp. This component allows for
multiple tabs within the main window.

Step 10: Setting TabbedPane Size

tp.setBounds(50, 50, 200, 200);


The position and size of the tabbed pane are set using setBounds(x, y, width, height). It specifies the
upper-left corner (50, 50) and the size (200x200 pixels) of the tabbed pane.

Step 11: Adding Panels to the TabbedPane


tp.add("BLUE", p1);
tp.add("RED", p2);
tp.add("GREEN", p3);

The three previously created panels are added to the tabbed pane with labels:
The first panel (p1) is associated with the tab labeled "BLUE."
The second panel (p2) with the tab labeled "RED."
The third panel (p3) with the tab labeled "GREEN."
Step 12: Adding the TabbedPane to the JFrame

f.add(tp);
The JTabbedPane is added to the JFrame f so that it will be displayed.
Step 13: Setting JFrame Properties
CopyReplit
f.setSize(400, 400);
The size of the JFrame is set to 400 pixels wide and 400 pixels high.

f.setLayout(null);
The layout manager for the JFrame is set to null, allowing manual positioning of components (in this
case, the tabbed pane).

f.setVisible(true);
This line makes the JFrame visible, allowing the user to see the user interface.

Step 14: Main Method

public static void main(String[] args) {


new TabbedPaneExample();
}

The main method is the entry point of the application. It creates a new instance of
TabbedPaneExample, which runs the constructor and initializes the GUI.

Summary
This Java program creates a simple Swing application with a tabbed pane containing three tabs, each
associated with a JPanel of different colors (blue, red, and green). The GUI is initialized when a new
instance of TabbedPaneExample is created in the main method.

SimpleAnimation

package Swings;
import javax.swing.*;

import java.awt.*;

final public class SimpleAnimation {


private JFrame frame;
private DrawPanel drawPanel;
private int oneX = 7;
private int oneY = 7;
private boolean up = false;
private boolean down = true;
private boolean left = false;
private boolean right = true;
private volatile boolean running = true;

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new SimpleAnimation().go());
}

private void go() {


frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel = new DrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(300, 300);
frame.setLocation(375, 55);
frame.setResizable(true);
frame.setVisible(true);

// Start animation in a separate thread


Thread animationThread = new Thread(this::moveIt);
animationThread.start();
}

class DrawPanel extends JPanel {


@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

Graphics g1=getGraphics();
g.setColor(Color.blue);
g.fillOval(oneX, oneY,20,20);
//g.fillRect(oneX, oneY, 6, 6);
}
}

private void moveIt() {


while(running) {
if(oneX >= 283) {
right = false;
left = true;
}
if(oneX <= 7) {
right = true;
left = false;
}
if(oneY >= 265) {
up = true;
down = false;
}
if(oneY <= 7) {
up = false;
down = true;
}
if(up) oneY--;
if(down) oneY++;
if(left) oneX--;
if(right) oneX++;

try {
Thread.sleep(10);
SwingUtilities.invokeLater(() -> frame.repaint());
} catch (InterruptedException exc) {
Thread.currentThread().interrupt();
break;
}
}
}
}
Explanation

Step 1: Package Declaration

package Swings;
This indicates that the SimpleAnimation class is part of a package named Swings, helping in organizing
related classes.

Step 2: Import Statements

import javax.swing.*;
import java.awt.*;
These lines import necessary classes from the javax.swing and java.awt packages:
Swing Components: Classes for GUI components (JFrame, JPanel, etc.).
Graphics: Classes for handling graphics (Color, etc.).

Step 3: Class Declaration

final public class SimpleAnimation {


The class SimpleAnimation is declared as final, meaning it cannot be inherited. This class contains the
functionality for the animation.

Step 4: Instance Variables Declaration

private JFrame frame;


private DrawPanel drawPanel;
private int oneX = 7;
private int oneY = 7;
private boolean up = false;
private boolean down = true;
private boolean left = false;
private boolean right = true;
private volatile boolean running = true;
frame: An instance of JFrame that serves as the main window for the application.
drawPanel: An instance of DrawPanel, a custom panel where the animation will occur.
oneX, oneY: Coordinates for the animated circle’s position.
Directional Booleans (up, down, left, right): Variables to control the movement direction of the circle.
running: A volatile boolean that signals whether the animation should continue running.

Step 5: Main Method

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new SimpleAnimation().go());
}
The main method is the entry point of the program. It uses SwingUtilities.invokeLater() to ensure that
the GUI is initialized on the Event Dispatch Thread (EDT), which is crucial for thread safety in Swing
applications. The go() method is called to set up the GUI.
Step 6: Setting Up the GUI

private void go() {


frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel = new DrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(300, 300);
frame.setLocation(375, 55);
frame.setResizable(true);
frame.setVisible(true);
The go method initializes the GUI components:
A JFrame with the title "Test" is created.
The default close operation is set to JFrame.EXIT_ON_CLOSE, which allows the application to
terminate when the window is closed.
An instance of DrawPanel is created and added to the center of the frame.
The size of the frame is set to 300x300 pixels.
The frame is positioned on the screen (375 pixels from the left and 55 pixels from the top).
The frame is made resizable and then set to be visible.

Step 7: Starting the Animation Thread

// Start animation in a separate thread


Thread animationThread = new Thread(this::moveIt);
animationThread.start();
A new thread is created to handle the animation by invoking the moveIt() method. This allows the
animation to run concurrently without freezing the GUI.

Step 8: DrawPanel Class

class DrawPanel extends JPanel {


@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
The DrawPanel class is an inner class that extends JPanel. It overrides the paintComponent(Graphics g)
method for custom drawing.
The call super.paintComponent(g) is made to ensure that the panel is properly rendered before custom
drawing is executed.

Step 9: Drawing the Circle

g.setColor(Color.BLUE);
g.fillOval(oneX, oneY, 20, 20);
//g.fillRect(oneX, oneY, 6, 6);
}
}
Inside paintComponent, the graphics context g is used to draw:
A blue circle with a diameter of 20 pixels, using the current coordinates (oneX, oneY) for its position.
The commented-out line g.fillRect(oneX, oneY, 6, 6); could be used to draw a rectangle at the same
position, but it is commented out and not currently in use.

Step 10: Animation Logic

private void moveIt() {


while(running) {
if(oneX >= 283) {
right = false;
left = true;
}
if(oneX <= 7) {
right = true;
left = false;
}
if(oneY >= 265) {
up = true;
down = false;
}
if(oneY <= 7) {
up = false;
down = true;
}

The moveIt method contains the logic for moving the circle:
The method enters a loop that runs as long as running is true.
It checks the oneX and oneY coordinates against predefined boundaries (for the width and height of the
panel). When the boundaries are exceeded, it changes the corresponding direction flags:
If oneX exceeds 283, it changes direction to left.
If oneX is less than or equal to 7, it changes direction to right.
Similarly for oneY, it adjusts the up and down direction based on top and bottom boundaries.
Step 11: Updating Position and Repainting

if(up) oneY--;
if(down) oneY++;
if(left) oneX--;
if(right) oneX++;

try {
Thread.sleep(10);
SwingUtilities.invokeLater(() -> frame.repaint());
} catch (InterruptedException exc) {
Thread.currentThread().interrupt();
break;
}
}
}
After determining the direction, the position of the circle is updated. The circle moves one pixel at a
time based on its direction flags.
The thread sleeps for 10 milliseconds to control the speed of the animation.
After sleeping, SwingUtilities.invokeLater() is used to call the frame.repaint() method, which triggers
the paintComponent method where the circle is redrawn in its new position. The use of invokeLater
ensures that GUI updates happen safely on the EDT.

Summary

The SimpleAnimation class creates an animated blue circle that bounces around within the bounds of a
resizable window. The animation is controlled via a separate thread that continuously updates the
position of the circle and repaints the panel. The logic handles direction changes to create the bouncing
effect.

Mouse Listener Example

package Swings;
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample2 extends Frame implements MouseListener
{
Label l;
MouseListenerExample2(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,400,20);
l.setFont(new Font("Arial", Font.BOLD, 24));
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}

public void mouseEntered(MouseEvent e) {


l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
//public void mouseEntered(MouseEvent e) {}
//public void mouseExited(MouseEvent e) {}
//public void mousePressed(MouseEvent e) {}
//public void mouseReleased(MouseEvent e) {}

public static void main(String[] args) {


new MouseListenerExample2();
}
}

Explanation

Import Statements:

import java.awt.*;
import java.awt.event.*;
java.awt.*: This imports the Abstract Window Toolkit (AWT) classes, which contain the components
for building graphical user interfaces (GUIs) in Java.
java.awt.event.*: This imports classes for handling events, such as mouse clicks and movements.

Class Declaration:
public class MouseListenerExample2 extends Frame implements MouseListener
This line defines a public class named MouseListenerExample2 that extends Frame (meaning it inherits
properties and methods from the Frame class, which represents a window).
It also implements MouseListener, which is an interface in Java that allows the class to respond to
mouse events (like clicks, movements etc.).
Instance Variables:

Label l;
This declares a Label object l that will be used to display text messages in the GUI.
Constructor:

MouseListenerExample2(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,400,20);
l.setFont(new Font("Arial", Font.BOLD, 24));
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
addMouseListener(this);: Registers the current instance (this) as a listener for mouse events.
l=new Label();: Initializes the Label object.
l.setBounds(20,50,400,20);: Sets the position (x=20, y=50) and size (width=400, height=20) of the
label.
l.setFont(new Font("Arial", Font.BOLD, 24));: Sets the font of the label to Arial, bold, with a size of 24
points.
add(l);: Adds the label to the Frame.
setSize(300,300);: Sets the dimensions of the window to be 300 pixels wide and 300 pixels tall.
setLayout(null);: Disables the default layout manager, allowing absolute positioning of components.
setVisible(true);: Makes the Frame visible on the screen.
Mouse Event Methods:

Each of these methods are required to implement the MouseListener interface. They define what action
to take when specific mouse events occur.

public void mouseClicked(MouseEvent e) {


Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
mouseClicked(MouseEvent e): This method is called when the mouse button is clicked. It retrieves the
graphics context (g) and draws a blue oval (circle) at the location of the mouse click (e.getX() and
e.getY() determine the coordinates of the click) with a width and height of 30 pixels.

public void mouseEntered(MouseEvent e) {


l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
mouseEntered(MouseEvent e): Updates the label to "Mouse Entered" when the mouse pointer enters
the Frame.
mouseExited(MouseEvent e): Updates the label to "Mouse Exited" when the mouse pointer exits the
Frame.
mousePressed(MouseEvent e): Updates the label to "Mouse Pressed" when the mouse button is pressed
down.
mouseReleased(MouseEvent e): Updates the label to "Mouse Released" when the mouse button is
released.
Main Method:

public static void main(String[] args) {


new MouseListenerExample2();
}
The main method is the entry point of the program. It creates a new instance of
MouseListenerExample2, which in turn opens the window and sets up the event listening.

Conclusion

This program demonstrates the basics of AWT in Java to create a simple GUI application that responds
to mouse events. It uses event handling through the MouseListener interface to customize the GUI's
behavior and display graphics based on user interactions with the mouse. When you run this program,
you'll see a window where mouse events update the label with corresponding messages and draw a blue
circle where you click.

Table Example

package Swings;
import java.awt.Color;
import java.awt.Font;

//Table example using swing


import javax.swing.*;
import javax.swing.plaf.FontUIResource;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
FontUIResource font = new FontUIResource("Arial", Font.BOLD,16);
UIManager.put("Table.font", font);
UIManager.put("Table.foreground", Color.BLUE);
String data[][]={ {"101","Amit","670000","12000","10000"},
{"102","Jai","780000","12000","10000"},
{"103","Sachin","700000","12000","10000"},
{"104","Amot","670000","12000","10000"},
{"105","Jaiganesh","780000","12000","10000"},
{"106","Sanjay","700000","12000","10000"}
};
String column[]={"ID","NAME","SALARY","BONUS","TRAVELLING ALLOWANCE"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,300,400);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}

Explanation

Package Declaration:

package Swings;
This line declares that the class belongs to the Swings package. This is a way to organize classes in
Java.
Import Statements:

import java.awt.Color;
import java.awt.Font;
import javax.swing.*;
import javax.swing.plaf.FontUIResource;
java.awt.Color and java.awt.Font: These classes are imported for setting colors and fonts in the GUI.
javax.swing.*: This imports the Swing components needed for building GUI applications.
javax.swing.plaf.FontUIResource: This class is specifically imported to create a font resource that can
be used across UI components.
Class Declaration:

public class TableExample {


This line defines a public class named TableExample. This is the main class of the application.
Instance Variable:

JFrame f;
Here, an instance variable f of type JFrame is declared. JFrame is a top-level container used to create a
window.
Constructor:

TableExample() {
f = new JFrame();
...
}
This is the constructor for the TableExample class. It initializes the JFrame object when an instance of
this class is created.
Setting Font and Color:

FontUIResource font = new FontUIResource("Arial", Font.BOLD, 16);


UIManager.put("Table.font", font);
UIManager.put("Table.foreground", Color.BLUE);
A FontUIResource object named font is created, specifying the font style (Arial, bold, 16-point size).
The font for JTable components is set in the UIManager to be the font created above. This affects all
tables.
The foreground color (text color) of the JTable is set to blue.
Data Initialization:

String data[][] = {
{"101", "Amit", "670000", "12000", "10000"},
{"102", "Jai", "780000", "12000", "10000"},
{"103", "Sachin", "700000", "12000", "10000"},
{"104", "Amot", "670000", "12000", "10000"},
{"105", "Jaiganesh", "780000", "12000", "10000"},
{"106", "Sanjay", "700000", "12000", "10000"}
};
String column[] = {"ID", "NAME", "SALARY", "BONUS", "TRAVELLING ALLOWANCE"};
This initializes a 2D array data containing strings that represent employee records. Each sub-array
corresponds to one row of the table.
The column array defines the names of the columns of the table: ID, Name, Salary, Bonus, and
Travelling Allowance.
Creating the JTable:

JTable jt = new JTable(data, column);


A JTable object jt is created using the data and column headers defined earlier. The table will display
the specified data in a structured format.
Setting Bounds for the JTable:

jt.setBounds(30, 40, 300, 400);


Sets the position and size of the table within its parent container (in this case the JScrollPane).
Creating JScrollPane:

JScrollPane sp = new JScrollPane(jt);


A JScrollPane object sp is created to allow scrolling through the table. Adding the JTable to a
JScrollPane lets you scroll if the table's content is larger than the visible area.
Adding JScrollPane to JFrame:

f.add(sp);
The scroll pane containing the table is added to the JFrame.
Setting JFrame Properties:

f.setSize(300, 400);
f.setVisible(true);
Sets the size of the JFrame to a width of 300 pixels and a height of 400 pixels.
Sets the JFrame to be visible on the screen, meaning it will appear when the program runs.

Main Method:

public static void main(String[] args) {


new TableExample();
}

This is the entry point of the program. When the program runs, it creates a new instance of
TableExample, which triggers the constructor, thereby displaying the window with the table.

Conclusion

The code creates a simple GUI application with Swing that displays a table of employee data in a
window. It showcases how to customize font and color properties for the table and utilizes JScrollPane
to enable scrolling for larger tables. When executed, the program opens a window displaying the table
with the specified data and formatting.
Factorial Calculation

package Swings;

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

public class FactorialCalculator extends JFrame {


private JTextField inputField;
private JTextField resultField;
private JButton computeButton;

public FactorialCalculator() {
// Set up the frame
setTitle("Factorial Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

// Create components
JLabel inputLabel = new JLabel("Enter a number: ");
inputField = new JTextField(10);
JLabel resultLabel = new JLabel("Factorial: ");
resultField = new JTextField(15);
resultField.setEditable(false);
computeButton = new JButton("Compute");

// Add components with GridBagLayout


gbc.insets = new Insets(5, 5, 5, 5);

gbc.gridx = 0;
gbc.gridy = 0;
add(inputLabel, gbc);

gbc.gridx = 1;
gbc.gridy = 0;
add(inputField, gbc);

gbc.gridx = 0;
gbc.gridy = 1;
add(resultLabel, gbc);

gbc.gridx = 1;
gbc.gridy = 1;
add(resultField, gbc);

gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(computeButton, gbc);

// Add action listener to the button


computeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int number = Integer.parseInt(inputField.getText());
if (number < 0) {
JOptionPane.showMessageDialog(null,
"Please enter a non-negative number",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
long result = calculateFactorial(number);
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null,
"Please enter a valid integer",
"Error",
JOptionPane.ERROR_MESSAGE);
} catch (ArithmeticException ex) {
JOptionPane.showMessageDialog(null,
"Number too large to calculate factorial",
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
});

// Pack and display


pack();
setLocationRelativeTo(null);
}

private long calculateFactorial(int n) {


if (n > 20) {
throw new ArithmeticException("Number too large");
}
if (n == 0 || n == 1) {
return 1;
}
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FactorialCalculator().setVisible(true);
}
});
}
}

Explanation

Package Declaration:

package Swings;
This declares that the class belongs to the Swings package, which organizes the Java classes.
Import Statements:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
javax.swing.*: Imports all classes from the Swing library, which is used for creating graphical user
interfaces (GUIs).
java.awt.*: Imports classes from the Abstract Window Toolkit, primarily for geometric layout and GUI
features.
java.awt.event.*: Imports classes that handle events such as button clicks or key presses.
Class Declaration:

public class FactorialCalculator extends JFrame {


Declares a public class named FactorialCalculator that extends JFrame, meaning it creates a window by
inheriting properties and methods from JFrame.
Instance Variables:

private JTextField inputField;


private JTextField resultField;
private JButton computeButton;
Declares private instance variables for the input field, result field, and compute button. These will be
used to interact with the user.
Constructor:

public FactorialCalculator() {
This constructor initializes the graphical components and behavior of the application.
Setting Up the Frame:

setTitle("Factorial Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
setTitle("Factorial Calculator"): Sets the title of the window.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures the application exits when the window
is closed.
setLayout(new GridBagLayout()): Uses the GridBagLayout for arranging components in a grid. This
flexible layout allows for precise placement of components.
GridBagConstraints gbc = new GridBagConstraints(): Creates an instance of GridBagConstraints to
specify constraints for the components.
Creating Components:

JLabel inputLabel = new JLabel("Enter a number: ");


inputField = new JTextField(10);
JLabel resultLabel = new JLabel("Factorial: ");
resultField = new JTextField(15);
resultField.setEditable(false);
computeButton = new JButton("Compute");
Creates a label for the input field, a text field (inputField) where users can enter a number, a label for
the result, a read-only text field (resultField) for displaying the calculated factorial, and a button
(computeButton) that the user will click to compute the factorial.
Adding Components Using GridBagLayout:

Each section adds components to the frame using the GridBagConstraints instance gbc.

gbc.insets = new Insets(5, 5, 5, 5);


Sets the padding for each component's grid cell.

The subsequent lines use gbc.gridx and gbc.gridy to position the components in the grid:

gbc.gridx = 0; gbc.gridy = 0; add(inputLabel, gbc);


gbc.gridx = 1; gbc.gridy = 0; add(inputField, gbc);
gbc.gridx = 0; gbc.gridy = 1; add(resultLabel, gbc);
gbc.gridx = 1; gbc.gridy = 1; add(resultField, gbc);
gbc.gridx = 0; gbc.gridy = 2; gbc.gridwidth = 2; gbc.fill = GridBagConstraints.HORIZONTAL;
add(computeButton, gbc);
This specifies the position of each component in the grid. The button spans two columns.
Adding Action Listener to the Button:

computeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Here, an ActionListener is added to computeButton to handle user interactions.

Within the actionPerformed method, the code:

try {
int number = Integer.parseInt(inputField.getText());
if (number < 0) {
JOptionPane.showMessageDialog(null,
"Please enter a non-negative number",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
long result = calculateFactorial(number);
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null,
"Please enter a valid integer",
"Error",
JOptionPane.ERROR_MESSAGE);
} catch (ArithmeticException ex) {
JOptionPane.showMessageDialog(null,
"Number too large to calculate factorial",
"Error",
JOptionPane.ERROR_MESSAGE);
}
Attempts to parse the input as an integer and checks if it's non-negative.
Calls the calculateFactorial method to compute the factorial if the input is valid.
Displays error messages through JOptionPane if input is invalid (e.g., negative number or non-integer
input).
Calculate Factorial Method:

private long calculateFactorial(int n) {


if (n > 20) {
throw new ArithmeticException("Number too large");
}
if (n == 0 || n == 1) {
return 1;
}
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
This private method calculates the factorial of a given integer n. It:
Throws an ArithmeticException if n is greater than 20 (as factorials larger than that will overflow a
long integer).
Returns 1 for the base cases (0! and 1!).
Iterates from 2 to n, multiplying the result by each integer to calculate the factorial.
Main Method:

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FactorialCalculator().setVisible(true);
}
});
}
The main method is the entry point of the program. It schedules the creation of the FactorialCalculator
GUI for the Event Dispatch Thread (EDT) using SwingUtilities.invokeLater(), ensuring thread safety in
Swing.
A new FactorialCalculator instance is created and made visible.

Conclusion

The FactorialCalculator program provides a user interface for calculating the factorial of a non-
negative integer. It performs input validation and performs the calculation while using event-driven
programming. The use of GridBagLayout allows for flexible arrangement of components, while
JOptionPane is used for displaying error messages. When correctly executed, this program presents a
clean, functional GUI that takes user input and computes the desired result.

package Swings;

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

public class TextCaseConvertor extends JFrame {


private JTextField inputField;
private JTextField upperCaseField;
private JTextField lowerCaseField;
private JTextField reverseField;
private JTextField lengthField;
private JButton processButton;

public TextCaseConvertor() {
// Set up the frame
setTitle("String Manipulator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
// Create components
JLabel inputLabel = new JLabel("Enter a string: ");
inputField = new JTextField(20);

JLabel upperCaseLabel = new JLabel("Uppercase: ");


upperCaseField = new JTextField(20);
upperCaseField.setEditable(false);

JLabel lowerCaseLabel = new JLabel("Lowercase: ");


lowerCaseField = new JTextField(20);
lowerCaseField.setEditable(false);

JLabel reverseLabel = new JLabel("Reverse: ");


reverseField = new JTextField(20);
reverseField.setEditable(false);

JLabel lengthLabel = new JLabel("Length: ");


lengthField = new JTextField(20);
lengthField.setEditable(false);

processButton = new JButton("Process String");

// Layout components using GridBagLayout


gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;

// Input row
gbc.gridx = 0;
gbc.gridy = 0;
add(inputLabel, gbc);

gbc.gridx = 1;
add(inputField, gbc);

// Uppercase row
gbc.gridx = 0;
gbc.gridy = 1;
add(upperCaseLabel, gbc);

gbc.gridx = 1;
add(upperCaseField, gbc);

// Lowercase row
gbc.gridx = 0;
gbc.gridy = 2;
add(lowerCaseLabel, gbc);

gbc.gridx = 1;
add(lowerCaseField, gbc);
// Reverse row
gbc.gridx = 0;
gbc.gridy = 3;
add(reverseLabel, gbc);

gbc.gridx = 1;
add(reverseField, gbc);

// Length row
gbc.gridx = 0;
gbc.gridy = 4;
add(lengthLabel, gbc);

gbc.gridx = 1;
add(lengthField, gbc);

// Button row
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 2;
add(processButton, gbc);

// Add action listener to the button


processButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
processString();
}
});

// Add key listener to input field


inputField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
processString();
}
}
});

// Pack and display


pack();
setLocationRelativeTo(null);
}

private void processString() {


String input = inputField.getText();

// Process the string


upperCaseField.setText(input.toUpperCase());
lowerCaseField.setText(input.toLowerCase());
reverseField.setText(new StringBuilder(input).reverse().toString());
lengthField.setText(String.valueOf(input.length()));
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TextCaseConvertor().setVisible(true);
}
});
}
}

Explanation

Package Declaration:

package Swings;
This code snippet declares that the class is part of the Swings package, which is used to organize
classes.

Import Statements:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
javax.swing.*: Imports all classes from the Swing package for GUI components.
java.awt.*: Imports classes related to layout and event handling.
java.awt.event.*: Imports classes related to handling events such as button clicks and key presses.
Class Declaration:

public class TextCaseConvertor extends JFrame {


Declares a public class named TextCaseConvertor that extends JFrame, meaning it represents a window
that users can interact with.
Instance Variables:

private JTextField inputField;


private JTextField upperCaseField;
private JTextField lowerCaseField;
private JTextField reverseField;
private JTextField lengthField;
private JButton processButton;
These variables are declared for input and output text fields and a button. The text fields will display
the processed string data.

Constructor:

public TextCaseConvertor() {
This constructor initializes the GUI components and sets up the behavior of the application.
Setting Up the Frame:

setTitle("String Manipulator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
setTitle("String Manipulator"): Sets the title of the window.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures the application exits when the window
is closed.
setLayout(new GridBagLayout()): Uses GridBagLayout for flexible and precise placement of
components.
GridBagConstraints gbc = new GridBagConstraints(): Creates an instance to specify the position and
attributes of components added to the layout.
Creating Components:

Components such as input fields, labels, and a button are created:

JLabel inputLabel = new JLabel("Enter a string: ");


inputField = new JTextField(20);

JLabel upperCaseLabel = new JLabel("Uppercase: ");


upperCaseField = new JTextField(20);
upperCaseField.setEditable(false);

JLabel lowerCaseLabel = new JLabel("Lowercase: ");


lowerCaseField = new JTextField(20);
lowerCaseField.setEditable(false);

JLabel reverseLabel = new JLabel("Reverse: ");


reverseField = new JTextField(20);
reverseField.setEditable(false);

JLabel lengthLabel = new JLabel("Length: ");


lengthField = new JTextField(20);
lengthField.setEditable(false);

processButton = new JButton("Process String");


Each label provides instructions or information about the associated text field.
Editable fields are set to false for output fields to prevent user modification.
Layout Components Using GridBagLayout:

gbc.insets = new Insets(5, 5, 5, 5);


gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets: Defines the padding around components, making the layout visually appealing.

gbc.fill: Specifies how a component should be resized within its allocated space.

The following lines position the components in a grid:

// Input row
gbc.gridx = 0; gbc.gridy = 0; add(inputLabel, gbc);
gbc.gridx = 1; add(inputField, gbc);

// Uppercase row
gbc.gridx = 0; gbc.gridy = 1; add(upperCaseLabel, gbc);
gbc.gridx = 1; add(upperCaseField, gbc);

// Lowercase row
gbc.gridx = 0; gbc.gridy = 2; add(lowerCaseLabel, gbc);
gbc.gridx = 1; add(lowerCaseField, gbc);

// Reverse row
gbc.gridx = 0; gbc.gridy = 3; add(reverseLabel, gbc);
gbc.gridx = 1; add(reverseField, gbc);

// Length row
gbc.gridx = 0; gbc.gridy = 4; add(lengthLabel, gbc);
gbc.gridx = 1; add(lengthField, gbc);

// Button row
gbc.gridx = 0; gbc.gridy = 5; gbc.gridwidth = 2; add(processButton, gbc);
The above sections outline each of the labeled rows and input fields, ensuring a structured layout.
Action Listener for the Button:

processButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
processString();
}
});
Here, an ActionListener is added to processButton. When the button is clicked, it triggers the
processString() method which will handle string processing.
Key Listener for Input Field:

inputField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
processString();
}
}
});
This part of the code allows users to press the "Enter" key to process the string automatically,
enhancing usability.
String Processing Method:

private void processString() {


String input = inputField.getText();

// Process the string


upperCaseField.setText(input.toUpperCase());
lowerCaseField.setText(input.toLowerCase());
reverseField.setText(new StringBuilder(input).reverse().toString());
lengthField.setText(String.valueOf(input.length()));
}
The method reads the string from inputField and processes it:
Converts it to uppercase and displays it in upperCaseField.
Converts it to lowercase in lowerCaseField.
Reverses the string using StringBuilder and sets it in reverseField.
Computes the length of the input string and updates lengthField.
Main Method:

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TextCaseConvertor().setVisible(true);
}
});
}
This main method serves as the entry point of the application. It uses SwingUtilities.invokeLater to
ensure that the GUI is created on the Event Dispatch Thread (EDT), promoting thread safety.
A new instance of TextCaseConvertor is instantiated and displayed.

Conclusion

The TextCaseConvertor application uses Java Swing to provide a user interface for manipulating text
input. It allows users to input a string and process it to show its uppercase, lowercase, reversed form,
and length. It demonstrates fundamental aspects of Swing, including layout management, event
handling, and user input processing, making it a practical example for understanding Java GUI
programming.

Palindrome Number Checker

package Swings;

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

public class NumberPalindromeChecker extends JFrame {


private JTextField inputField;
private JTextField reverseField;
private JTextField statusField;
private JButton checkButton;

public NumberPalindromeChecker() {
// Set up the frame
setTitle("Number Palindrome Checker");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

// Create components
JLabel inputLabel = new JLabel("Enter a number: ");
inputField = new JTextField(15);

JLabel reverseLabel = new JLabel("Reverse: ");


reverseField = new JTextField(15);
reverseField.setEditable(false);

JLabel statusLabel = new JLabel("Status: ");


statusField = new JTextField(15);
statusField.setEditable(false);

checkButton = new JButton("Check Palindrome");


// Layout components using GridBagLayout
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;

// Input row
gbc.gridx = 0;
gbc.gridy = 0;
add(inputLabel, gbc);

gbc.gridx = 1;
add(inputField, gbc);

// Reverse row
gbc.gridx = 0;
gbc.gridy = 1;
add(reverseLabel, gbc);

gbc.gridx = 1;
add(reverseField, gbc);

// Status row
gbc.gridx = 0;
gbc.gridy = 2;
add(statusLabel, gbc);

gbc.gridx = 1;
statusField.setBackground(new Color(240, 240, 240));
add(statusField, gbc);

// Button row
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
add(checkButton, gbc);

// Add action listener to the button


checkButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
checkPalindrome();
}
});

// Add key listener to input field


inputField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
checkPalindrome();
}
}
});

// Pack and display


pack();
setLocationRelativeTo(null);
}

private void checkPalindrome() {


try {
String input = inputField.getText().trim();
if (input.isEmpty()) {
JOptionPane.showMessageDialog(this,
"Please enter a number",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}

long number = Long.parseLong(input);


String reversed = new StringBuilder(String.valueOf(number)).reverse().toString();
reverseField.setText(reversed);

boolean isPalindrome = input.equals(reversed);


if (isPalindrome) {
statusField.setText("It's a Palindrome!");
statusField.setForeground(new Color(0, 128, 0)); // Green color
} else {
statusField.setText("Not a Palindrome");
statusField.setForeground(new Color(178, 34, 34)); // Red color
}

} catch (NumberFormatException ex) {


JOptionPane.showMessageDialog(this,
"Please enter a valid number",
"Error",
JOptionPane.ERROR_MESSAGE);
inputField.setText("");
reverseField.setText("");
statusField.setText("");
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new NumberPalindromeChecker().setVisible(true);
}
});
}
}

Explanation

Package Declaration:

package Swings;
This line indicates that the class belongs to the Swings package.
Import Statements:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
javax.swing.*: Imports all classes in the Swing library for building the GUI.
java.awt.*: Imports classes related to layout and graphic components.
java.awt.event.*: Imports interfaces and classes for dealing with events like mouse clicks and key
presses.
Class Declaration:

public class NumberPalindromeChecker extends JFrame {


This code declares a public class named NumberPalindromeChecker that extends JFrame, meaning it
will serve as a window for user interaction.
Instance Variables:

private JTextField inputField;


private JTextField reverseField;
private JTextField statusField;
private JButton checkButton;
These variables are defined as instance variables to hold the text fields and button used in the GUI.
Constructor:

public NumberPalindromeChecker() {
The constructor initializes the GUI components and sets up the window's behavior.
Setting Up the Frame:

setTitle("Number Palindrome Checker");


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
setTitle("Number Palindrome Checker"): Sets the title of the application window.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures the application exits when the window
is closed.
setLayout(new GridBagLayout()): Sets the layout manager to GridBagLayout, allowing flexible
positioning of components.
GridBagConstraints gbc = new GridBagConstraints(): Instantiates a GridBagConstraints object to
define component placement parameters.
Creating Components:

Various labels, text fields, and a button are created:

JLabel inputLabel = new JLabel("Enter a number: ");


inputField = new JTextField(15);

JLabel reverseLabel = new JLabel("Reverse: ");


reverseField = new JTextField(15);
reverseField.setEditable(false);

JLabel statusLabel = new JLabel("Status: ");


statusField = new JTextField(15);
statusField.setEditable(false);

checkButton = new JButton("Check Palindrome");


inputField allows users to enter a number, while reverseField and statusField are a non-editable text
field showing the reversed number and the result of the palindrome check, respectively.
checkButton initiates the palindrome checking.
Layout Components Using GridBagLayout:

gbc.insets = new Insets(5, 5, 5, 5);


gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets: Defines the space between components, enhancing visual appearance.

gbc.fill: Specifies that components will expand horizontally to fill their allocated space.

The components are then added to the frame using the grid bag constraints:

// Input row
gbc.gridx = 0; gbc.gridy = 0; add(inputLabel, gbc);
gbc.gridx = 1; add(inputField, gbc);

// Reverse row
gbc.gridx = 0; gbc.gridy = 1; add(reverseLabel, gbc);
gbc.gridx = 1; add(reverseField, gbc);
// Status row
gbc.gridx = 0; gbc.gridy = 2; add(statusLabel, gbc);
gbc.gridx = 1;
statusField.setBackground(new Color(240, 240, 240)); // Light gray background
add(statusField, gbc);

// Button row
gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = 2;
add(checkButton, gbc);
Each of these lines specifies the position of the labels and text fields in the grid layout by changing
gbc.gridx and gbc.gridy.
The button spans two columns in the fourth row.
Add action listener to the button:

checkButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
checkPalindrome();
}
});
An ActionListener is attached to the checkButton, which calls the checkPalindrome() method when the
button is clicked.
Add key listener to the input field:

inputField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
checkPalindrome();
}
}
});
This allows users to press the "Enter" key after typing a number, triggering the checkPalindrome()
method.
Palindrome Checking Method:

private void checkPalindrome() {


try {
String input = inputField.getText().trim();
if (input.isEmpty()) {
JOptionPane.showMessageDialog(this,
"Please enter a number",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}

long number = Long.parseLong(input);


String reversed = new StringBuilder(String.valueOf(number)).reverse().toString();
reverseField.setText(reversed);
boolean isPalindrome = input.equals(reversed);
if (isPalindrome) {
statusField.setText("It's a Palindrome!");
statusField.setForeground(new Color(0, 128, 0)); // Green color
} else {
statusField.setText("Not a Palindrome");
statusField.setForeground(new Color(178, 34, 34)); // Red color
}

} catch (NumberFormatException ex) {


JOptionPane.showMessageDialog(this,
"Please enter a valid number",
"Error",
JOptionPane.ERROR_MESSAGE);
inputField.setText("");
reverseField.setText("");
statusField.setText("");
}
}
This method checks if the given number is a palindrome:
It retrieves and trims the input string.
If the input is empty, an error message is shown using JOptionPane.
It attempts to convert the trimmed string to a long. If the input is not a number, a
NumberFormatException will be caught, and an error message is displayed.
The StringBuilder class is used to reverse the number.
It compares the original input and the reversed string to determine if it is a palindrome.
Appropriate messages are set in statusField, and their text color is adjusted based on the result.
Main Method:

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new NumberPalindromeChecker().setVisible(true);
}
});
}
The main method serves as the entry point for the application.
It uses SwingUtilities.invokeLater() to ensure that the GUI is created on the Event Dispatch Thread
(EDT), helping with thread safety.
A new instance of NumberPalindromeChecker is created and made visible.

Conclusion

The NumberPalindromeChecker application is a simple and effective Java Swing GUI program that
allows users to check if a number is a palindrome. It demonstrates fundamental concepts in GUI
programming such as layout management, event handling, and user input validation. The use of
JOptionPane for error messages enhances the user experience by providing feedback in case of invalid
input. Overall, it serves as a practical example of building interactive applications in Java.
ToggleButton

This application creates a simple light switch simulator using a JToggleButton. Here's what the code
does:
1. Creates a window with a toggle button, a status label, and a panel representing a light
2. When the toggle button is clicked:
 The status label updates to show whether the light is ON or OFF
 The light panel changes color (gray when off, yellow when on)
3. Uses proper layout management with BoxLayout and spacing
4. Follows Swing best practices like running on the Event Dispatch Thread
To run this application:
1. Copy the code into a file named ToggleButtonDemo.java
2. Compile it: javac ToggleButtonDemo.java
3. Run it: java ToggleButtonDemo

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

public class ToggleButtonDemo extends JFrame {


private JToggleButton toggleButton;
private JLabel statusLabel;
private JPanel lightPanel;

public ToggleButtonDemo() {
// Set up the frame
setTitle("Toggle Button Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
setSize(300, 200);

// Create main panel with padding


JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

// Create toggle button


toggleButton = new JToggleButton("Light Switch");
toggleButton.setAlignmentX(Component.CENTER_ALIGNMENT);

// Create status label


statusLabel = new JLabel("Light is OFF");
statusLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

// Create light panel


lightPanel = new JPanel();
lightPanel.setPreferredSize(new Dimension(100, 100));
lightPanel.setBackground(Color.GRAY);
lightPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

// Add action listener to toggle button


toggleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (toggleButton.isSelected()) {
statusLabel.setText("Light is ON");
lightPanel.setBackground(Color.YELLOW);
} else {
statusLabel.setText("Light is OFF");
lightPanel.setBackground(Color.GRAY);
}
}
});

// Add components to main panel


mainPanel.add(toggleButton);
mainPanel.add(Box.createRigidArea(new Dimension(0, 10)));
mainPanel.add(statusLabel);
mainPanel.add(Box.createRigidArea(new Dimension(0, 10)));
mainPanel.add(lightPanel);

// Add main panel to frame


add(mainPanel);

// Center the frame on screen


setLocationRelativeTo(null);
}

public static void main(String[] args) {


// Run the application on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ToggleButtonDemo().setVisible(true);
}
});
}
}

o/p
Step-by-Step Explanation
Import Statements:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
javax.swing.*: Imports classes for building the graphical user interface (GUI) components, such as
frames, buttons, and labels.
java.awt.*: Imports classes related to layout and other components.
java.awt.event.ActionEvent and java.awt.event.ActionListener: Imports classes for handling action
events, such as button clicks.
Class Declaration:

public class ToggleButtonDemo extends JFrame {


This line declares a public class named ToggleButtonDemo that extends JFrame. This means that
ToggleButtonDemo will have all the properties of a JFrame window.
Instance Variables:

private JToggleButton toggleButton;


private JLabel statusLabel;
private JPanel lightPanel;
These variables are declared to hold a toggle button, a status label, and a panel that visually represents
the "light".
Constructor:

public ToggleButtonDemo() {
The constructor sets up the GUI components and defines the behavior of the application.
Setting Up the Frame:

setTitle("Toggle Button Demo");


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
setSize(300, 200);
setTitle("Toggle Button Demo"): Sets the title of the window.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures that the application exits when the
window is closed.
setLayout(new BorderLayout(10, 10)): Uses BorderLayout for the main layout, with gaps of 10 pixels
for horizontal and vertical spacing.
setSize(300, 200): Sets the size of the window to 300 pixels wide and 200 pixels tall.
Creating the Main Panel:

JPanel mainPanel = new JPanel();


mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
A new JPanel named mainPanel is created.
setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)): Sets the layout of the panel to a vertical
BoxLayout, which aligns components in a single column.
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)): Applies a padding of 20 pixels around
the edges of the panel.
Creating the Components:

Toggle Button:

toggleButton = new JToggleButton("Light Switch");


toggleButton.setAlignmentX(Component.CENTER_ALIGNMENT);
A toggle button named "Light Switch" is created.

setAlignmentX(Component.CENTER_ALIGNMENT): Centers the toggle button within the parent


container in the horizontal direction.

Status Label:

statusLabel = new JLabel("Light is OFF");


statusLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
A label displaying the current status of the light is created, initialized to "Light is OFF", and centered.

Light Panel:

lightPanel = new JPanel();


lightPanel.setPreferredSize(new Dimension(100, 100));
lightPanel.setBackground(Color.GRAY);
lightPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
A panel representing the light is created with a preferred size of 100x100 pixels.
It is initially set with a gray background and a black border.
Adding Action Listener to the Toggle Button:

toggleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (toggleButton.isSelected()) {
statusLabel.setText("Light is ON");
lightPanel.setBackground(Color.YELLOW);
} else {
statusLabel.setText("Light is OFF");
lightPanel.setBackground(Color.GRAY);
}
}
});
An ActionListener is added to the toggle button.
Inside the actionPerformed method:
If the button is selected (pressed), the label updates to "Light is ON", and the background color of
lightPanel changes to yellow.
If the button is not selected (not pressed), the label updates to "Light is OFF", and the background
returns to gray.
Adding Components to the Main Panel:

mainPanel.add(toggleButton);
mainPanel.add(Box.createRigidArea(new Dimension(0, 10))); // Spacing
mainPanel.add(statusLabel);
mainPanel.add(Box.createRigidArea(new Dimension(0, 10))); // Spacing
mainPanel.add(lightPanel);
The toggle button, status label, and light panel are added sequentially to the mainPanel.
Box.createRigidArea(new Dimension(0, 10)): Adds a rigid area of space (10 pixels) between the
components for better visual spacing.
Adding the Main Panel to the Frame:

add(mainPanel);
The mainPanel is added to the frame.
Centering the Frame on Screen:

setLocationRelativeTo(null);
Centers the application window on the user's screen.
Main Method:

public static void main(String[] args) {


// Run the application on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ToggleButtonDemo().setVisible(true);
}
});
}
The main method serves as the entry point for the application.
SwingUtilities.invokeLater(...) ensures that the GUI is created on the Event Dispatch Thread (EDT),
which is the proper practice for any Swing application to avoid potential threading issues.
A new instance of ToggleButtonDemo is instantiated and made visible.

Conclusion

The ToggleButtonDemo application effectively demonstrates how to use a toggle button in a Swing
application to simulate a light switch. It provides an interactive experience by allowing the user to
toggle between "on" and "off" states, updating both a label and a panel's background color to visually
indicate the state of the light. This application showcases fundamental concepts in Swing, including
event handling, component layout, and UI design practices such as padding and alignment.

Check Boxes

atures. Here's what the application does:


1. Displays a list of pizza toppings as checkboxes with their prices
2. Updates the total price automatically when checkboxes are selected/deselected
3. Includes a reset button to clear all selections
4. Uses proper layout management and spacing
5. Follows Swing best practices
Key features demonstrated:
 Creating and styling checkboxes
 Handling checkbox events
 Maintaining a running total
 Resetting multiple checkboxes
 Proper UI organization with panels and layouts
 Price formatting
To run the application:
1. Save the code as CheckboxDemo.java
2. Compile it: javac CheckboxDemo.java
3. Run it: java CheckboxDemo

Would you like me to add any additional features or modify the existing functionality? For example, I
could:
 Add a submit order button
 Include a quantity selector for each topping
 Add more styling options
 Include a base pizza price
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CheckboxDemo extends JFrame {


private JPanel toppingsPanel;
private JLabel totalLabel;
private double totalPrice = 0.0;

// Checkbox prices
private final double CHEESE_PRICE = 1.50;
private final double PEPPERONI_PRICE = 2.00;
private final double MUSHROOM_PRICE = 1.75;
private final double OLIVES_PRICE = 1.25;

public CheckboxDemo() {
// Set up the frame
setTitle("Pizza Toppings Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
setSize(400, 300);

// Create main panel with padding


JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

// Create title label


JLabel titleLabel = new JLabel("Select Your Pizza Toppings");
titleLabel.setFont(new Font("Arial", Font.BOLD, 16));
titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

// Create toppings panel


toppingsPanel = new JPanel();
toppingsPanel.setLayout(new BoxLayout(toppingsPanel, BoxLayout.Y_AXIS));
toppingsPanel.setBorder(BorderFactory.createTitledBorder("Available Toppings"));

// Create checkboxes with prices


JCheckBox cheeseBox = createTopping("Extra Cheese", CHEESE_PRICE);
JCheckBox pepperoniBox = createTopping("Pepperoni", PEPPERONI_PRICE);
JCheckBox mushroomBox = createTopping("Mushrooms", MUSHROOM_PRICE);
JCheckBox olivesBox = createTopping("Olives", OLIVES_PRICE);

// Add checkboxes to toppings panel


toppingsPanel.add(cheeseBox);
toppingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
toppingsPanel.add(pepperoniBox);
toppingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
toppingsPanel.add(mushroomBox);
toppingsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
toppingsPanel.add(olivesBox);

// Create total price label


totalLabel = new JLabel("Total Price: $0.00");
totalLabel.setFont(new Font("Arial", Font.BOLD, 14));
totalLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

// Create reset button


JButton resetButton = new JButton("Reset Selection");
resetButton.setAlignmentX(Component.CENTER_ALIGNMENT);
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resetSelections();
}
});

// Add components to main panel


mainPanel.add(titleLabel);
mainPanel.add(Box.createRigidArea(new Dimension(0, 20)));
mainPanel.add(toppingsPanel);
mainPanel.add(Box.createRigidArea(new Dimension(0, 20)));
mainPanel.add(totalLabel);
mainPanel.add(Box.createRigidArea(new Dimension(0, 10)));
mainPanel.add(resetButton);

// Add main panel to frame


add(mainPanel);

// Center the frame on screen


setLocationRelativeTo(null);
}

private JCheckBox createTopping(String name, double price) {


JCheckBox checkbox = new JCheckBox(String.format("%s ($%.2f)", name, price));
checkbox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateTotal();
}
});
return checkbox;
}

private void updateTotal() {


totalPrice = 0.0;
Component[] components = toppingsPanel.getComponents();

for (Component component : components) {


if (component instanceof JCheckBox) {
JCheckBox checkbox = (JCheckBox) component;
if (checkbox.isSelected()) {
if (checkbox.getText().contains("Cheese")) totalPrice += CHEESE_PRICE;
if (checkbox.getText().contains("Pepperoni")) totalPrice += PEPPERONI_PRICE;
if (checkbox.getText().contains("Mushrooms")) totalPrice += MUSHROOM_PRICE;
if (checkbox.getText().contains("Olives")) totalPrice += OLIVES_PRICE;
}
}
}

totalLabel.setText(String.format("Total Price: $%.2f", totalPrice));


}

private void resetSelections() {


Component[] components = toppingsPanel.getComponents();
for (Component component : components) {
if (component instanceof JCheckBox) {
((JCheckBox) component).setSelected(false);
}
}
updateTotal();
}

public static void main(String[] args) {


// Run the application on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new CheckboxDemo().setVisible(true);
}
});
}
}
o/p
Explanation

This Java program creates a simple graphical user interface (GUI) application for selecting pizza
toppings using checkboxes. It utilizes the Swing framework to create the GUI components. Below, I'll
explain the program step by step.

1. Import Statements

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
These imports are necessary for using Swing components (JFrame, JPanel, JCheckBox, etc.), layout
management (BorderLayout, BoxLayout), and handling events (ActionEvent, ActionListener).

2. Class Definition

public class CheckboxDemo extends JFrame {


CheckboxDemo class extends JFrame, making it a window that can contain components. It represents
the main application window.

3. Instance Variables

private JPanel toppingsPanel;


private JLabel totalLabel;
private double totalPrice = 0.0;

private final double CHEESE_PRICE = 1.50;


private final double PEPPERONI_PRICE = 2.00;
private final double MUSHROOM_PRICE = 1.75;
private final double OLIVES_PRICE = 1.25;
These variables store:
toppingsPanel: A panel to hold the topping checkboxes.
totalLabel: A label to display the total price.
totalPrice: A variable to keep current total price based on selected toppings.
Price constants for each topping.

4. Constructor

public CheckboxDemo() {
The constructor initializes the GUI components.

5. Setting Up the Frame

setTitle("Pizza Toppings Selector");


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
setSize(400, 300);
Sets the title, default close operation, layout manager (with padding), and size of the window.

6. Creating Main Panel

JPanel mainPanel = new JPanel();


mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
A main panel is created to hold all the components vertically, with padding around it.

7. Title Label

JLabel titleLabel = new JLabel("Select Your Pizza Toppings");


titleLabel.setFont(new Font("Arial", Font.BOLD, 16));
titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
A title label is created with bold font and centered alignment.

8. Toppings Panel

toppingsPanel = new JPanel();


toppingsPanel.setLayout(new BoxLayout(toppingsPanel, BoxLayout.Y_AXIS));
toppingsPanel.setBorder(BorderFactory.createTitledBorder("Available Toppings"));
A panel for toppings is created and titled "Available Toppings".

9. Creating Checkboxes

JCheckBox cheeseBox = createTopping("Extra Cheese", CHEESE_PRICE);


JCheckBox pepperoniBox = createTopping("Pepperoni", PEPPERONI_PRICE);
JCheckBox mushroomBox = createTopping("Mushrooms", MUSHROOM_PRICE);
JCheckBox olivesBox = createTopping("Olives", OLIVES_PRICE);
Checkbox components for each topping are created using a helper method createTopping.

10. Adding Checkboxes to the Panel

toppingsPanel.add(cheeseBox);
toppingsPanel.add(Box.createRigidArea(new Dimension(0, 5))); // Adds spacing
toppingsPanel.add(pepperoniBox);
...
Each checkbox is added to the toppingsPanel. Rigid areas are used for vertical spacing.

11. Total Price Label

totalLabel = new JLabel("Total Price: $0.00");


totalLabel.setFont(new Font("Arial", Font.BOLD, 14));
totalLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
A label is created to display the total price, initially set to $0.00.

12. Reset Button


JButton resetButton = new JButton("Reset Selection");
resetButton.setAlignmentX(Component.CENTER_ALIGNMENT);
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resetSelections();
}
});
A button is created to reset the selections. It has an action listener that calls resetSelections when
clicked.

13. Adding Components to Main Panel

mainPanel.add(titleLabel);
...
All the components (title, toppings panel, total label, reset button) are added to the mainPanel.

14. Adding Main Panel to Frame

add(mainPanel);
The mainPanel is added to the frame.

15. Centering the Frame

setLocationRelativeTo(null);
Center the application window on the screen.

16. Creating the Checkbox Method

private JCheckBox createTopping(String name, double price) {


This method creates a checkbox for a given topping and adds an action listener to update the total price
when the checkbox state changes.

17. Updating Total Price

private void updateTotal() {


This method calculates the total price based on the selected toppings and updates the totalLabel. It
iterates through the checkboxes in the toppingsPanel, checking which are selected and adding their
prices to totalPrice.

18. Resetting Selections

private void resetSelections() {


This method unchecks all checkboxes in the toppings panel and updates the total price to reflect the
changes.

19. Main Method

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new CheckboxDemo().setVisible(true);
}
});
}
This is the entry point of the application. It ensures that the GUI is created and updated on the Event
Dispatch Thread to keep the GUI responsive.

Summary

Overall, this Java program provides users with a simple interface where they can select pizza toppings,
see the total price automatically update, and reset their selections if needed. The use of checkboxes for
selections and dynamically updating price showcases the power of event-driven programming in Java
Swing.

Radio Buttons

package Swings;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Enumeration;

class RadioButtonDemo extends JFrame {


private JLabel selectionLabel;
private ButtonGroup sizeGroup;

public RadioButtonDemo() {
setTitle("Pizza Size Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);

// Create main panel


JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

// Create title
JLabel titleLabel = new JLabel("Select Pizza Size");
titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
mainPanel.add(titleLabel);
mainPanel.add(Box.createVerticalStrut(20));

// Create radio button panel


JPanel radioPanel = new JPanel();
radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
radioPanel.setBorder(BorderFactory.createEtchedBorder());

// Create button group


sizeGroup = new ButtonGroup();

// Create radio buttons


String[] sizes = {"Small - $8.99", "Medium - $10.99", "Large - $12.99", "Extra Large - $14.99"};
for (String size : sizes) {
JRadioButton rb = new JRadioButton(size);
rb.setAlignmentX(Component.LEFT_ALIGNMENT);
rb.addActionListener(e -> updateSelection());
sizeGroup.add(rb);
radioPanel.add(rb);
radioPanel.add(Box.createVerticalStrut(5));
}

mainPanel.add(radioPanel);
mainPanel.add(Box.createVerticalStrut(20));

// Create selection label


selectionLabel = new JLabel("Your selection: None");
selectionLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
mainPanel.add(selectionLabel);

// Add order button


JButton orderButton = new JButton("Place Order");
orderButton.setAlignmentX(Component.CENTER_ALIGNMENT);
orderButton.addActionListener(e -> {
if (getSelectedSize() != null) {
JOptionPane.showMessageDialog(this,
"Order placed: " + getSelectedSize(),
"Order Confirmation",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this,
"Please select a size first!",
"Selection Required",
JOptionPane.WARNING_MESSAGE);
}
});

mainPanel.add(Box.createVerticalStrut(20));
mainPanel.add(orderButton);
// Add main panel to frame
add(mainPanel);
}

private String getSelectedSize() {


for (Enumeration<AbstractButton> buttons = sizeGroup.getElements();
buttons.hasMoreElements();) {
AbstractButton button = buttons.nextElement();
if (button.isSelected()) {
return button.getText();
}
}
return null;
}

private void updateSelection() {


String selected = getSelectedSize();
if (selected != null) {
selectionLabel.setText("Your selection: " + selected);
} else {
selectionLabel.setText("Your selection: None");
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
RadioButtonDemo frame = new RadioButtonDemo();
frame.setVisible(true);
});
}
}
Explanation

1. Package Declaration

package Swings;
This line declares that the class RadioButtonDemo belongs to the package named Swings.

2. Import Statements

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Enumeration;
These imports allow access to the Swing classes for creating GUI components (JFrame, JPanel,
JRadioButton, etc.), layout management (BoxLayout), event handling (ActionListener, ActionEvent),
and enumerating button groups (Enumeration).

3. Class Definition

class RadioButtonDemo extends JFrame {


The class RadioButtonDemo extends JFrame, allowing it to function as the main application window.

4. Instance Variables

private JLabel selectionLabel;


private ButtonGroup sizeGroup;
selectionLabel: A label that displays the current pizza size selected by the user.
sizeGroup: A ButtonGroup that manages the radio buttons for pizza sizes to ensure only one button can
be selected at a time.

5. Constructor

public RadioButtonDemo() {
This constructor initializes the GUI components and sets up the layout.

6. Frame Setup

setTitle("Pizza Size Selector");


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
Sets the title of the window, defines its close operation, specifies its size, and centers the window on the
screen.

7. Creating the Main Panel

JPanel mainPanel = new JPanel();


mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
A main panel is created with a vertical box layout and padding around it.

8. Title Label

JLabel titleLabel = new JLabel("Select Pizza Size");


titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
mainPanel.add(titleLabel);
mainPanel.add(Box.createVerticalStrut(20));
A title label is created to prompt the user to select a pizza size. It is centered in the main panel and has
vertical spacing added after it.

9. Radio Button Panel

JPanel radioPanel = new JPanel();


radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
radioPanel.setBorder(BorderFactory.createEtchedBorder());
A separate panel for the radio buttons is created, also using a vertical box layout. It has a border to
differentiate it from the main panel.

10. Button Group Creation

sizeGroup = new ButtonGroup();


A button group is created to group the radio buttons so that only one can be selected at a time.

11. Creating Radio Buttons

String[] sizes = {"Small - $8.99", "Medium - $10.99", "Large - $12.99", "Extra Large - $14.99"};
for (String size : sizes) {
JRadioButton rb = new JRadioButton(size);
rb.setAlignmentX(Component.LEFT_ALIGNMENT);
rb.addActionListener(e -> updateSelection());
sizeGroup.add(rb);
radioPanel.add(rb);
radioPanel.add(Box.createVerticalStrut(5));
}
An array of strings contains different pizza sizes.
A loop creates a JRadioButton for each size:
Each radio button is aligned to the left and an action listener is added to call updateSelection() when the
button is selected.
The radio button is added to the sizeGroup and to the radioPanel, with vertical spacing added.

12. Adding Radio Panel to Main Panel

mainPanel.add(radioPanel);
mainPanel.add(Box.createVerticalStrut(20));
The radio button panel is added to the main panel with vertical spacing below it.
13. Selection Label

selectionLabel = new JLabel("Your selection: None");


selectionLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
mainPanel.add(selectionLabel);
A label to display the user's selection is created and centered in the main panel.

14. Order Button

JButton orderButton = new JButton("Place Order");


orderButton.setAlignmentX(Component.CENTER_ALIGNMENT);
orderButton.addActionListener(e -> {
if (getSelectedSize() != null) {
JOptionPane.showMessageDialog(this,
"Order placed: " + getSelectedSize(),
"Order Confirmation",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this,
"Please select a size first!",
"Selection Required",
JOptionPane.WARNING_MESSAGE);
}
});
A button with the text "Place Order" is created, aligned to the center.
An action listener is added to handle order placement. If a size is selected, it shows a confirmation
dialog; if not, it prompts the user to make a selection.

15. Adding Order Button to Main Panel

mainPanel.add(Box.createVerticalStrut(20));
mainPanel.add(orderButton);
The order button is added to the main panel with vertical spacing above it.

16. Adding Main Panel to Frame

add(mainPanel);
The complete main panel is added to the JFrame.

17. Getting Selected Size

private String getSelectedSize() {


for (Enumeration<AbstractButton> buttons = sizeGroup.getElements();
buttons.hasMoreElements();) {
AbstractButton button = buttons.nextElement();
if (button.isSelected()) {
return button.getText();
}
}
return null;
}
This method iterates through the buttons in the sizeGroup and checks which button is selected. If
found, it returns the text of the selected button. Otherwise, it returns null.
18. Updating Selection Label

private void updateSelection() {


String selected = getSelectedSize();
if (selected != null) {
selectionLabel.setText("Your selection: " + selected);
} else {
selectionLabel.setText("Your selection: None");
}
}
This method updates the selectionLabel with the currently selected pizza size. If no size is selected, it
sets the label to indicate no selection.

19. Main Method

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
RadioButtonDemo frame = new RadioButtonDemo();
frame.setVisible(true);
});
}

This is the entry point of the application. It uses SwingUtilities.invokeLater to ensure that the GUI is
created and updated on the Event Dispatch Thread, keeping the application responsive. It creates an
instance of RadioButtonDemo and makes the frame visible.

Summary

The RadioButtonDemo application provides a simple interface for selecting a pizza size using radio
buttons. The selected size is displayed in a label, and the user can place an order, receiving feedback
based on their selection. The use of radio buttons ensures that the user can only select one size at a
time, enhancing the user experience.

You might also like