0% found this document useful (0 votes)
21 views37 pages

APznzaa2z_YpI9Bzkm5VdmHC5EYOcQgH9C7EOZyaT4_DJyrCF-kY1RnWmojwFu3NEMhpGm4_YwQpmdSye_TGcSYRxVLBFykGLfBhaY-7_tLLfDzx3_1uDvGIWrHSCf3kFUge3bsT-YloQWWEeHt27GfvsCY5dXm3tX6imOXZMBMagye6hxjOTTWNOsB4RhlHSdMganlnq

The document provides a comprehensive overview of Swing, a Java GUI toolkit, detailing its key features, components, and containers. It includes example programs demonstrating various functionalities such as creating a simple application with buttons and labels, a calculator, mouse operations, image buttons, a JList for country selection, and a login form. Additionally, it explains the distinction between components and containers in Swing, emphasizing their roles in building user interfaces.
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)
21 views37 pages

APznzaa2z_YpI9Bzkm5VdmHC5EYOcQgH9C7EOZyaT4_DJyrCF-kY1RnWmojwFu3NEMhpGm4_YwQpmdSye_TGcSYRxVLBFykGLfBhaY-7_tLLfDzx3_1uDvGIWrHSCf3kFUge3bsT-YloQWWEeHt27GfvsCY5dXm3tX6imOXZMBMagye6hxjOTTWNOsB4RhlHSdMganlnq

The document provides a comprehensive overview of Swing, a Java GUI toolkit, detailing its key features, components, and containers. It includes example programs demonstrating various functionalities such as creating a simple application with buttons and labels, a calculator, mouse operations, image buttons, a JList for country selection, and a login form. Additionally, it explains the distinction between components and containers in Swing, emphasizing their roles in building user interfaces.
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/ 37

Tentative questions in Module 3

Q1. Explain the key features of Swing with a sample program for displaying the message
“Welcome to Swing ” through a label when the button “Click Me” is pressed.

Swing is a powerful and flexible GUI (Graphical User Interface) toolkit in Java that provides a
richer set of components than the earlier AWT (Abstract Window Toolkit). It is part of the Java
Foundation Classes (JFC) and allows developers to create window-based applications with an easier
and more visually appealing interface.

Here are some key features and concepts related to Swing in Java:

Key Features of Swing:

Lightweight Components:

Swing components are lightweight, meaning they are drawn entirely in Java rather than relying on the
native system’s GUI components. This provides a consistent look and feel across different platforms.
Pluggable Look and Feel:

Swing supports a pluggable look-and-feel system that allows developers to change the appearance of
their applications dynamically. You can choose from several built-in themes or create your own.
Rich Set of Components:

Swing provides a wide variety of components, including buttons, labels, text fields, tables, trees, and
more. This allows developers to create complex user interfaces.

Event Handling:

Swing includes a robust event handling mechanism, which lets developers respond to user interactions
(like clicks, keyboard input, etc.) easily using listeners.

Customizable and Extendable:

Swing components can be easily customized and extended to create new components that fit specific
application needs.

Support for MVC Architecture:

Swing follows the Model-View-Controller (MVC) design pattern, allowing for better separation
between the data (model), user interface (view), and the control logic (controller).

Basic Components of Swing:


JFrame: The main window that holds all other Swing components.
JPanel: A generic container used to organize components within a JFrame.
JButton: A clickable button that can perform actions.
JLabel: Displays a short string or an image icon.
JTextField: Allows for single-line text input.
JTextArea: Allows for multi-line text input.
JComboBox: A dropdown list from which users can select an option.
JMenuBar: A menu bar containing menus that can have items and sub-items.

Example of a Simple Swing Program:


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!");

// Add action listener to the button


button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("Button Clicked!");
}
});
// 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
Q2. Write a program to create a frame for a simple arithmetic calculator using swing
components and layout mangers.
package Swings;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator extends JFrame implements ActionListener {


private JTextField display;
private StringBuilder currentInput;
private double firstOperand;
private String operator;

public Calculator() {
setTitle("Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Create display field


display = new JTextField();
display.setEditable(false);
display.setFont(new Font("Arial", Font.PLAIN, 24));
display.setHorizontalAlignment(JTextField.RIGHT);
add(display, BorderLayout.NORTH);

// Create button panel


JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));

String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};

for (String text : buttons) {


JButton button = new JButton(text);
button.addActionListener(this);
buttonPanel.add(button);
}

add(buttonPanel, BorderLayout.CENTER);
// Initialize
currentInput = new StringBuilder();
operator = "";
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();

// Handle button clicks


if (command.charAt(0) >= '0' && command.charAt(0) <= '9') {
currentInput.append(command);
display.setText(currentInput.toString());
} else if (command.equals("C")) {
currentInput.setLength(0);
display.setText("");
operator = "";
} else if (command.equals("=")) {
handleEquals();
} else {
handleOperator(command);
}
}

private void handleOperator(String op) {


if (currentInput.length() > 0) {
firstOperand = Double.parseDouble(currentInput.toString());
operator = op;
currentInput.setLength(0);
}
}

private void handleEquals() {


if (currentInput.length() > 0 && operator.length() > 0) {
double secondOperand = Double.parseDouble(currentInput.toString());
double result = 0;

switch (operator) {
case "+":
result = firstOperand + secondOperand;
break;
case "-":
result = firstOperand - secondOperand;
break;
case "*":
result = firstOperand * secondOperand;
break;
case "/":
if (secondOperand != 0) {
result = firstOperand / secondOperand;
} else {
display.setText("Error");
return;
}
break;
}

display.setText(String.valueOf(result));
currentInput.setLength(0); // Clear input after calculation
operator = "";
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
Calculator calc = new Calculator();
calc.setVisible(true);
});
}
}

o/p

Q3. Develop a simple swing program for illustrating mouse operations such as mouse down, up
double click , single click with help of a button

package Swings;

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

public class MouseOperationsDemo1 extends JFrame {

private JButton button;


private JLabel statusLabel;

public MouseOperationsDemo1() {
// Set up the frame
setTitle("Mouse Operations Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(null);

// Create and set up the button


button = new JButton("Click Me!");
button.setBounds(150, 100, 100, 50); // Set position and size of button

// Create and set up the label to display status


statusLabel = new JLabel("Perform mouse operations on the button.");
statusLabel.setBounds(50, 180, 300, 20); // Set position and size of label

// Add mouse listeners to the button


button.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
statusLabel.setText("Mouse Down on Button");
}

@Override
public void mouseReleased(MouseEvent e) {
statusLabel.setText("Mouse Up on Button");
}

@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
statusLabel.setText("Double Click on Button");
} else if (e.getClickCount() == 1) {
statusLabel.setText("Single Click on Button");
}
}
});

// Add components to the frame


add(button);
add(statusLabel);
}

public static void main(String[] args) {


// Create the application and make it visible
SwingUtilities.invokeLater(() -> {
MouseOperationsDemo1 demo = new MouseOperationsDemo1();
demo.setVisible(true);
});
}
}
o/p

Q4. Develop a swing program for showing two image icons of hour glass and clock and when the
icon is pressed , the respective message like hour glass is pressed or clock is pressed should be
displayed on the console.

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

l1=new JLabel();
l1.setBounds(200,250, 700,100);
l1.setFont(new Font("Lucida Calligraphy",Font.BOLD,32));

JButton b=new JButton(new ImageIcon("//home//badhusha//Desktop//t2//digital.png"));


b.setBounds(150,150,100,100);
JButton b1=new JButton(new ImageIcon("//home//badhusha//Desktop//t2//hourglass.jpeg"));
b1.setBounds(500,150,100, 100);

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
l1.setText("You have pressed digital clock!");
}
});

b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
l1.setText("You have pressed hour glass!");
}
});
f.add(b);
f.add(l1);
f.setSize(300,400);
f.add(b1);
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 ImageButtonExample();
}
}

o/p

Q5. Elucidate Components and Containers in Swing with neat sketches

Components and Containers


A Swing GUI consists of two key items: components and containers. However, this distinction is
mostly conceptual because all containers are also components. The difference between the two is found
in their intended purpose: As the term is commonly used, a component is an
independent visual control, such as a push button or slider. A container holds a group of
components. Thus, a container is a special type of component that is designed to hold
other components. Furthermore, in order for a component to be displayed, it must be held
within a container. Thus, all Swing GUIs will have at least one container. Because containers
are components, a container can also hold other containers. This enables Swing to define
what is called a containment hierarchy, at the top of which must be a top-level container.
Let’s look a bit more closely at components and containers.

Components
In general, Swing components are derived from the JComponent class. (The only exceptions
to this are the four top-level containers, described in the next section.) JComponent provides
the functionality that is common to all components. For example, JComponent supports the
pluggable look and feel. JComponent inherits the AWT classes Container and Component.
Thus, a Swing component is built on and compatible with an AWT component.
All of Swing’s components are represented by classes defined within the package
javax.swing. The following table shows the class names for Swing components (including
those used as containers)

Notice that all component classes begin with the letter J. For example, the class for a label
is JLabel; the class for a push button is JButton; and the class for a scroll bar is JScrollBar.
Containers

Swing defines two types of containers. The first are top-level containers: JFrame, JApplet,
JWindow, and JDialog. These containers do not inherit JComponent. They do, however,
inherit the AWT classes Component and Container. Unlike Swing’s other components,
which are lightweight, the top-level containers are heavyweight. This makes the top-level
containers a special case in the Swing component library.
As the name implies, a top-level container must be at the top of a containment hierarchy.
A top-level container is not contained within any other container. Furthermore, every
containment hierarchy must begin with a top-level container. The one most commonly
used for applications is JFrame. The one used for applets is JApplet.

The second type of containers supported by Swing are lightweight containers. Lightweight
containers do inherit JComponent. An example of a lightweight container is JPanel, which
is a general-purpose container. Lightweight containers are often used to organize and manage
groups of related components because a lightweight container can be contained within
another container. Thus, you can use lightweight containers such as JPanel to create
subgroups of related controls that are contained within an outer container.

The Top-Level Container Panes

Each top-level container defines a set of panes. At the top of the hierarchy is an instance
of JRootPane. JRootPane is a lightweight container whose purpose is to manage the other
panes. It also helps manage the optional menu bar. The panes that comprise the root pane
are called the glass pane, the content pane, and the layered pane.

The glass pane is the top-level pane. It sits above and completely covers all other panes.
By default, it is a transparent instance of JPanel. The glass pane enables you to manage
mouse events that affect the entire container (rather than an individual control) or to paint
over any other component, for example. In most cases, you won’t need to use the glass
pane directly, but it is there if you need it.

The layered pane is an instance of JLayeredPane. The layered pane allows components
to be given a depth value. This value determines which component overlays another. (Thus,
the layered pane lets you specify a Z-order for a component, although this is not something
that you will usually need to do.) The layered pane holds the content pane and the (optional)
menu bar.
Although the glass pane and the layered panes are integral to the operation of a top-level
container and serve important purposes, much of what they provide occurs behind the scene.
The pane with which your application will interact the most is the content pane, because
this is the pane to which you will add visual components. In other words, when you add a
component, such as a button, to a top-level container, you will add it to the content pane.
By default, the content pane is an opaque instance of JPanel.

The Swing Packages

Swing is a very large subsystem and makes use of many packages. At the time of this writing,
these are the packages defined by Swing.

The main package is javax.swing. This package must be imported into any program that
uses Swing. It contains the classes that implement the basic Swing components, such as
push buttons, labels, and check boxes.

Q6. Develop a Swing program for displaying JList which contains names of countries . If the
country is selected from JList by clicking the country by mouse , it should display the name of the
country in the display

JList Example

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();
}
}
Q7 . Develop a login form for getting user name and password using swing program

package Swings;
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");
/* This method specifies the location and size
* of component. setBounds(x, y, width, height)
* here (x,y) are cordinates 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);
loginButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//panel.add(loginButton);
}
});
}
}

Q8. Develop a tabbedpane for displaying red, green and blue colors in the pane by selecting the
respective tab.

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();
}}

Q9. Develop an animated program using swing for displaying ball bouncing within a frame.

Simple Animation

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(false);
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);
g.setColor(Color.BLUE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.RED);
g.fillRect(3, 3, this.getWidth()-6, this.getHeight()-6);
g.setColor(Color.WHITE);
g.fillRect(6, 6, this.getWidth()-12, this.getHeight()-12);
g.setColor(Color.BLACK);
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 >= 259) {
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;
}
}
}
}

Q10 Develop a swing program to display table with data

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();
}
}

Q11 . Develop a Swing program to find factorial of a number by getting a number through text
field and display the result by pressing Compute button

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);
}
});
}
}
Q12. Develop a swing program to get a string through text field and convert it into upper case,
lower case , reverse and find the length of the string.

Text Case Convertor

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);
}
});
}
}
Q13 Develop Swing program to get a number and check whether it is Palindrome Number or not

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);
}
});
}
}
14. Develop a swing program to switch on or off the light panel by changing color (gray when
off, yellow when on) using 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

Q 15. Develop a swing program to display checkboxes with the prices of pizza topping .
Calculate the total amount of the pizza topping when the check boxes are checked.

. 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
Q16 . Develop a swing program by selecting the pizzas by its sizes with radio buttons and display
the total of the all selected items by pressing Compute button

Here's what the application does:


1. Allows selection of pizza size using radio buttons (only one size can be selected)
2. Allows selection of crust type using radio buttons (only one type can be selected)
3. Shows the current selection and updates the total price automatically
4. Includes a place order button with confirmation dialog
5. Uses proper layout management and spacing
6. Groups related radio buttons using ButtonGroup
Key features demonstrated:
 Creating and grouping radio buttons
 Handling radio button events
 Maintaining selections across button groups
 Price calculations based on selections
 Dialog boxes for user feedback
 Proper UI organization with panels and layouts
To run the application:
1. Save the code as RadioButtonDemo.java
2. Compile it: javac RadioButtonDemo.java
3. Run it: java RadioButtonDemo

Would you like me to add any additional features or modify the existing functionality? For example, I
could:
 Add more customization options
 Include a delivery/pickup option
 Add a quantity selector
 Include special instructions input

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);
});
}
}

o/p

You might also like