0% found this document useful (0 votes)
28 views27 pages

Java Practical Codes

coding

Uploaded by

ivedant8.8.8
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
28 views27 pages

Java Practical Codes

coding

Uploaded by

ivedant8.8.8
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 27

1.

class Point {
protected int x, y;

public Point() {
this.x = 0;
this.y = 0;
}

public Point(int x, int y) {


this.x = x;
this.y = y;
}

public void display() {


System.out.println("Point Coordinates: (" + x + ", " + y + ")");
}
}

r
class ColorPoint extends Point {
private String color;

public ColorPoint() {
super();
this.color = "undefined";
}

public ColorPoint(int x, int y, String color) {


super(x, y);
this.color = color;
}

public void display() {


System.out.println("ColorPoint Coordinates: (" + x + ", " + y + "), Color:
" + color);
}
}

// Subclass Point3D with additional member z


class Point3D extends Point {
protected int z;

public Point3D() {
super();
this.z = 0;
}

public Point3D(int x, int y, int z) {


super(x, y);
this.z = z;
}

public void display() {


System.out.println("Point3D Coordinates: (" + x + ", " + y + ", " + z +
")");
}
}

public class PointTest {


public static void main(String[] args) {

Point p = new Point(2, 3);


ColorPoint cp = new ColorPoint(5, 6, "Red");
Point3D p3d = new Point3D(1, 4, 7);

p.display();
cp.display();
p3d.display();
}
}

-----------------------------------------------------------------------------------
------------------------------------------------------------------

2.

class Fibonacci
{

public void printFibonacci(int n)


{
int a = 0, b = 1;
System.out.print("Fibonacci Series: " + a + " " + b);
for (int i = 2; i < n; i++) {
int next = a + b;
System.out.print(" " + next);
a = b;
b = next;
}
System.out.println();
}
}

class Cube {

public void printCubes(int n) {


System.out.print("Cubes: ");
for (int i = 1; i <= n; i++) {
System.out.print((i * i * i) + " ");
}
System.out.println();
}
}
class Square {

public void printSquares(int n) {


System.out.print("Squares: ");
for (int i = 1; i <= n; i++) {
System.out.print((i * i) + " ");
}
System.out.println();
}
}

public class TestSeries {


public static void main(String[] args) {
int n = 5; // Example input

Fibonacci fib = new Fibonacci();


Cube cube = new Cube();
Square square = new Square();

fib.printFibonacci(n);
cube.printCubes(n);
square.printSquares(n);
}
}

-----------------------------------------------------------------------------------
-------------------------------------------------------

3.

import java.util.Scanner;

class Employee {
protected int id;
protected String name;
protected double salary;

public Employee() {
this.id = 0;
this.name = "";
this.salary = 0.0;
}

public void accept() {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter Employee ID: ");
id = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter Employee Name: ");
name = scanner.nextLine();
System.out.print("Enter Employee Salary: ");
salary = scanner.nextDouble();
}

public void display() {


System.out.println("ID: " + id + ", Name: " + name + ", Salary: " +
salary);
}
}

class Manager extends Employee {


private double bonus;

public Manager() {
super(); // Call the base class (Employee) constructor
this.bonus = 0.0;
}

public void accept() {


super.accept(); // Call the accept method of Employee class
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Manager Bonus: ");
bonus = scanner.nextDouble();
}

public void display() {


double totalSalary = salary + bonus;
System.out.println("ID: " + id + ", Name: " + name + ", Salary: " + salary
+ ", Bonus: " + bonus + ", Total Salary: " + totalSalary);
}

public double getTotalSalary() {


return salary + bonus;
}
}

public class ManagerProgram {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of managers: ");
int n = scanner.nextInt();

Manager[] managers = new Manager[n];

for (int i = 0; i < n; i++) {


System.out.println("\nEnter details for Manager " + (i + 1) + ":");
managers[i] = new Manager();
managers[i].accept();
}
Manager maxManager = managers[0];
for (int i = 1; i < n; i++) {
if (managers[i].getTotalSalary() > maxManager.getTotalSalary()) {
maxManager = managers[i];
}
}

System.out.println("\nManager with the maximum total salary:");


maxManager.display();

}
}

-----------------------------------------------------------------------------------
---------------------------------------------------------

4.

class CapitalString {

public static String capitalizeFirstLetter(String str) {


if (str == null || str.isEmpty()) {
return str;
}

return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();


}
}

class Person {
private String name;
private String city;

public Person(String name, String city) {


this.name = name;
this.city = city;
}

public void display() {

String capitalizedName = CapitalString.capitalizeFirstLetter(name);


System.out.println("Person Name: " + capitalizedName + ", City: " + city);
}
}

public class Main {


public static void main(String[] args) {

Person person = new Person("john", "new york");

person.display();
}
}

-----------------------------------------------------------------------------------
------------------------------------------

SET B :

1.Define an interface “Operation” which has methods area(),volume(). Define a


constant PI having a value 3.142. Create a class circle (member – radius), cylinder
(members – radius, height) which implements this interface. Calculate and display
the area and volume

->

interface Operation {
double PI = 3.142;

double area();

double volume();
}

class Circle implements Operation {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

public double area() {


return PI * radius * radius;
}

public double volume() {


return 0;
}
}

class Cylinder implements Operation {


private double radius;
private double height;

public Cylinder(double radius, double height) {


this.radius = radius;
this.height = height;
}

public double area() {


return 2 * PI * radius * (radius + height);
}

public double volume() {


return PI * radius * radius * height;
}
}

public class Main {


public static void main(String[] args) {
Circle circle = new Circle(5);

System.out.println("Circle Area: " + circle.area());


System.out.println("Circle Volume: " + circle.volume());

Cylinder cylinder = new Cylinder(5, 10);

System.out.println("Cylinder Area: " + cylinder.area());


System.out.println("Cylinder Volume: " + cylinder.volume());
}
}

2. Write a Java program to create a super class Employee (members – name, salary).
Derive a sub-class as Developer (member – projectname). Derive a sub-class
Programmer (member – proglanguage) from Developer. Create object of Developer and
display the details of it. Implement this multilevel inheritance with appropriate
constructor and methods.s

->

class Employee {
protected String name;
protected double salary;

public Employee(String name, double salary) {


this.name = name;
this.salary = salary;
}

public void displayDetails() {


System.out.println("Name: " + name);
System.out.println("Salary: $" + salary);
}
}

class Developer extends Employee {


protected String projectName;

public Developer(String name, double salary, String projectName) {


super(name, salary);
this.projectName = projectName;
}

public void displayDetails() {


super.displayDetails();
System.out.println("Project Name: " + projectName);
}
}

class Programmer extends Developer {


private String progLanguage;
public Programmer(String name, double salary, String projectName, String
progLanguage) {
super(name, salary, projectName);
this.progLanguage = progLanguage;
}

public void displayDetails() {


super.displayDetails();
System.out.println("Programming Language: " + progLanguage);
}
}

public class Main {


public static void main(String[] args) {
Developer developer = new Developer("Alice", 80000, "AI Project");

developer.displayDetails();
}
}

3 . Define an abstract class Staff with members name and address. Define two sub-
classes of this class – FullTimeStaff (members - department, salary, hra - 8% of
salary, da – 5% of salary) and PartTimeStaff (members - number-of-hours, rate-per-
hour). Define appropriate constructors. Write abstract method as calculateSalary()
in Staff class. Implement this method in subclasses. Create n objects which could
be of either FullTimeStaff or PartTimeStaff class by asking the user‘s choice.
Display details of all FullTimeStaff objects and all PartTimeStaff objects along
with their salary.

->

import java.util.Scanner;

abstract class Staff {


protected String name;
protected String address;

public Staff(String name, String address) {


this.name = name;
this.address = address;
}

public abstract double calculateSalary();

public abstract void displayDetails();


}

class FullTimeStaff extends Staff {


private String department;
private double salary;
private double hra;
private double da;

public FullTimeStaff(String name, String address, String department, double


salary) {
super(name, address);
this.department = department;
this.salary = salary;
this.hra = 0.08 * salary; // 8% of salary
this.da = 0.05 * salary; // 5% of salary
}

public double calculateSalary() {


return salary + hra + da;
}

public void displayDetails() {


System.out.println("Full-Time Staff:");
System.out.println("Name: " + name);
System.out.println("Address: " + address);
System.out.println("Department: " + department);
System.out.println("Basic Salary: $" + salary);
System.out.println("HRA: $" + hra);
System.out.println("DA: $" + da);
System.out.println("Total Salary: $" + calculateSalary());
System.out.println();
}
}

class PartTimeStaff extends Staff {


private int numberOfHours;
private double ratePerHour;

public PartTimeStaff(String name, String address, int numberOfHours, double


ratePerHour) {
super(name, address);
this.numberOfHours = numberOfHours;
this.ratePerHour = ratePerHour;
}

public double calculateSalary() {


return numberOfHours * ratePerHour;
}

public void displayDetails() {


System.out.println("Part-Time Staff:");
System.out.println("Name: " + name);
System.out.println("Address: " + address);
System.out.println("Number of Hours: " + numberOfHours);
System.out.println("Rate per Hour: $" + ratePerHour);
System.out.println("Total Salary: $" + calculateSalary());
System.out.println();
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the number of staff members:");


int n = scanner.nextInt();
scanner.nextLine(); // Consume newline

Staff[] staffArray = new Staff[n];


for (int i = 0; i < n; i++) {
System.out.println("Enter details for staff member " + (i + 1));
System.out.println("Is this staff member Full-Time (enter 'f') or Part-
Time (enter 'p')?");
char type = scanner.nextLine().charAt(0);

if (type == 'f') {
// Input details for FullTimeStaff
System.out.println("Enter name:");
String name = scanner.nextLine();
System.out.println("Enter address:");
String address = scanner.nextLine();
System.out.println("Enter department:");
String department = scanner.nextLine();
System.out.println("Enter basic salary:");
double salary = scanner.nextDouble();
scanner.nextLine(); // Consume newline

staffArray[i] = new FullTimeStaff(name, address, department,


salary);
} else if (type == 'p') {
System.out.println("Enter name:");
String name = scanner.nextLine();
System.out.println("Enter address:");
String address = scanner.nextLine();
System.out.println("Enter number of hours:");
int numberOfHours = scanner.nextInt();
System.out.println("Enter rate per hour:");
double ratePerHour = scanner.nextDouble();
scanner.nextLine();

staffArray[i] = new PartTimeStaff(name, address, numberOfHours,


ratePerHour);
} else {
System.out.println("Invalid type entered. Please enter 'f' for
Full-Time or 'p' for Part-Time.");
i--;
}
}

System.out.println("\nStaff Details:");
for (int i = 0; i < staffArray.length; i++) {
if (staffArray[i] != null) {
staffArray[i].displayDetails();
}
}

}
}

-----------------------------------------------------------------------------------
----------------------------------------------------------
ASSIGNMENT 3
SET A :

1.
Accept n integers from the user and store them in a collection. Display them in the
sorted order.
The collection should not accept duplicate elements. (Use a suitable collection).
Search for a
particular element using predefined search method in the Collection framework.

->

import java.util.Scanner;
import java.util.TreeSet;

public class Collection


{
public static void main(String[] args)
{
TreeSet<Integer> numbers = new TreeSet<>();
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of integers you want to input: ");


int n = scanner.nextInt();

System.out.println("Enter " + n + " integers:");


for (int i = 0; i < n; i++) {
int number = scanner.nextInt();
numbers.add(number);
}

System.out.println("Sorted elements: " + numbers);

System.out.print("Enter the element to search for: ");


int searchElement = scanner.nextInt();

if (numbers.contains(searchElement))
{
System.out.println("Element " + searchElement + " is found in the
collection.");
}
else
{
System.out.println("Element " + searchElement + " is not found in the
collection.");
}

}
}

----------------------------------------------------------

2.
Create a Hash table containing Employee name and Salary. Display the details of the
hash table. Also search for a specific Employee and display Salary of that
Employee.

=>

import java.util.HashMap;
import java.util.Scanner;

public class Collection1


{
public static void main(String[] args)
{
HashMap<String, Double> employeeSalaries = new HashMap<>();
Scanner scanner = new Scanner(System.in);

employeeSalaries.put("John", 50000.0);
employeeSalaries.put("Jane", 60000.0);
employeeSalaries.put("Emily", 70000.0);
employeeSalaries.put("Michael", 80000.0);
employeeSalaries.put("Sophia", 75000.0);

System.out.println("Employee Salaries:");
for (String employee : employeeSalaries.keySet())
{
System.out.println("Employee: " + employee + ", Salary: $" +
employeeSalaries.get(employee));
}

System.out.print("\nEnter the name of the employee to search for their


salary: ");
String searchName = scanner.nextLine();

if (employeeSalaries.containsKey(searchName))
{
double salary = employeeSalaries.get(searchName);
System.out.println("Salary of " + searchName + " is: $" + salary);
}
else
{
System.out.println("Employee " + searchName + " is not found in the
record.");
}
}
}

-----------------------------

3.
Write a java program to accept a number from the user, if number is zero then throw
userdefined exception ―Number is 0, otherwise check whether no is prime or not.

=>

import java.util.Scanner;

class ZeroNumberException extends Exception


{
public ZeroNumberException(String message)
{
super(message);
}
}
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);

try
{
System.out.print("Enter a number: ");
int number = scanner.nextInt();

if (number == 0)
{
throw new ZeroNumberException("Number is 0");
}

if (isPrime(number))
{
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}

}
catch (ZeroNumberException e)
{
System.out.println("Exception: " + e.getMessage());
}
catch (Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
}
finally
{
scanner.close();
}
}

public static boolean isPrime(int num)


{
if (num <= 1) {
return false;
}

for (int i = 2; i * i <= num; i++)


{
if (num % i == 0)
{
return false;
}
}

return true;
}
}

-------------------
4.Write a java program that displays the number of characters, lines and words of a
file.

->

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileInfo {

public static void main(String[] args) {


String fileName = "info.txt";
int charCount = 0;
int wordCount = 0;
int lineCount = 0;

try (BufferedReader br = new BufferedReader(new FileReader(fileName)))


{
String line;

while ((line = br.readLine()) != null) {


lineCount++;
charCount += line.length(); // Count characters in the current
line
String[] words = line.split("\\s+"); // Split the line into words
wordCount += words.length; // Increment word count by the number
of words in the current line
}
} catch (IOException e)
{
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}

System.out.println("Number of characters: " + charCount);


System.out.println("Number of words: " + wordCount);
System.out.println("Number of lines: " + lineCount);
}
}

--------------------------------------

-----------------------------------------------------------------------------

SET B :

1. Construct a linked List containing names of colours: red, blue, yellow and
orange. Then
extend your program to do the following:
i. Display the contents of the List using an Iterator
ii. Display the contents of the List in reverse order using a ListIterator
iii. Create another list containing pink and green. Insert the elements of this
list
between blue and yellow.

—>

import java.util.LinkedList;
import java.util.Iterator;
import java.util.ListIterator;

public class ColorList {

public static void main(String[] args) {

LinkedList<String> colors = new LinkedList<>();


colors.add("red");
colors.add("blue");
colors.add("yellow");
colors.add("orange");

System.out.println("Displaying colors using Iterator:");


Iterator<String> iterator = colors.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

// ii. Display the contents of the List in reverse order using a


ListIterator
System.out.println("\nDisplaying colors in reverse order using
ListIterator:");
ListIterator<String> listIterator = colors.listIterator(colors.size()); //
Start at the end of the list
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}

// iii. Create another list containing pink and green, insert between blue
and yellow
LinkedList<String> newColors = new LinkedList<>();
newColors.add("pink");
newColors.add("green");

// Insert the new list between blue and yellow


int index = colors.indexOf("yellow"); // Find the position of yellow
colors.addAll(index, newColors); // Add newColors before yellow

// Display the modified list


System.out.println("\nModified color list:");
for (String color : colors) {
System.out.println(color);
}
}
}

----------------------------
2.Write a java program to accept Doctor Name from the user and check whether it is
valid
or not. (It should not contain digits and special symbol) If it is not valid then
throw user
defined Exception - Name is Invalid -- otherwise display it.

->

import java.util.Scanner;

// User-defined exception class


class InvalidNameException extends Exception
{
public InvalidNameException(String message)
{
super(message);
}
}

public class DoctorNameValidation


{

public static void validateName(String name) throws InvalidNameException


{

if (!name.matches("[a-zA-Z\\s]+")) {
throw new InvalidNameException("Name is Invalid");
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter Doctor's Name: ");


String doctorName = scanner.nextLine();

try {

validateName(doctorName);

System.out.println("Doctor's Name is valid: " + doctorName);


} catch (InvalidNameException e) {
// If invalid, display the custom exception message
System.out.println(e.getMessage());
}
}
}

--------------------------

3.Write a java program to accept details of n customers (c_id, cname, address,


mobile_no)
from user and store it in a file (Use DataOutputStream class). Display the details
of
customers by reading it from file.(Use DataInputStream class)

->

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;

public class CustomerDetails


{

public static void main(String[] args)


{
Scanner scanner = new Scanner(System.in);

try {

FileOutputStream fos = new FileOutputStream("customers.txt");


DataOutputStream dos = new DataOutputStream(fos);

// Accept the number of customers


System.out.print("Enter the number of customers: ");
int n = scanner.nextInt();
scanner.nextLine(); // Consume newline

// Loop to accept customer details and write them to the file


for (int i = 1; i <= n; i++) {
System.out.println("Enter details for customer " + i + ":");

System.out.print("Customer ID: ");


int c_id = scanner.nextInt();
scanner.nextLine(); // Consume newline

System.out.print("Customer Name: ");


String cname = scanner.nextLine();

System.out.print("Address: ");
String address = scanner.nextLine();

System.out.print("Mobile Number: ");


String mobile_no = scanner.nextLine();

// Write the details to the file


dos.writeInt(c_id);
dos.writeUTF(cname);
dos.writeUTF(address);
dos.writeUTF(mobile_no);
}

dos.close();

FileInputStream fis = new FileInputStream("customers.txt");


DataInputStream dis = new DataInputStream(fis);

System.out.println("\nCustomer Details from the file:");


for (int i = 1; i <= n; i++) {
int c_id = dis.readInt();
String cname = dis.readUTF();
String address = dis.readUTF();
String mobile_no = dis.readUTF();

System.out.println("\nCustomer " + i + ":");


System.out.println("Customer ID: " + c_id);
System.out.println("Customer Name: " + cname);
System.out.println("Address: " + address);
System.out.println("Mobile Number: " + mobile_no);
}

dis.close();

} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
}

scanner.close();
}
}

-----------------------------------------------------------------------------------
---------------------------------------------------------------------

Assignment 4 :
Set A :

1.

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

public class LoginPage extends JFrame implements ActionListener {

// Components of the Form


private Container container;
private JLabel title;
private JLabel userLabel;
private JTextField userTextField;
private JLabel passwordLabel;
private JPasswordField passwordField;
private JButton loginButton;
private JButton resetButton;
private JLabel minimizeLabel;
private JLabel maximizeLabel;
private JLabel closeLabel;

// Constructor
public LoginPage() {
setTitle("Login Page");
setBounds(300, 90, 400, 300); // Window position and size
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false); // Disable resizing

container = getContentPane();
container.setLayout(null);

// Labels for minimize, maximize, close


minimizeLabel = new JLabel("_");
minimizeLabel.setBounds(300, 10, 20, 20);
container.add(minimizeLabel);

maximizeLabel = new JLabel("O");


maximizeLabel.setBounds(330, 10, 20, 20);
container.add(maximizeLabel);

closeLabel = new JLabel("X");


closeLabel.setBounds(360, 10, 20, 20);
container.add(closeLabel);

// Title Label
title = new JLabel("Login Page");
title.setFont(new Font("Arial", Font.PLAIN, 20));
title.setSize(300, 30);
title.setLocation(120, 30);
container.add(title);

// Username Label and TextField


userLabel = new JLabel("Username:");
userLabel.setFont(new Font("Arial", Font.PLAIN, 15));
userLabel.setSize(100, 20);
userLabel.setLocation(50, 80);
container.add(userLabel);

userTextField = new JTextField();


userTextField.setFont(new Font("Arial", Font.PLAIN, 15));
userTextField.setSize(150, 20);
userTextField.setLocation(150, 80);
container.add(userTextField);

// Password Label and PasswordField


passwordLabel = new JLabel("Password:");
passwordLabel.setFont(new Font("Arial", Font.PLAIN, 15));
passwordLabel.setSize(100, 20);
passwordLabel.setLocation(50, 120);
container.add(passwordLabel);

passwordField = new JPasswordField();


passwordField.setFont(new Font("Arial", Font.PLAIN, 15));
passwordField.setSize(150, 20);
passwordField.setLocation(150, 120);
container.add(passwordField);

// Login Button
loginButton = new JButton("Login");
loginButton.setFont(new Font("Arial", Font.PLAIN, 15));
loginButton.setSize(100, 20);
loginButton.setLocation(70, 180);
loginButton.addActionListener(this);
container.add(loginButton);

// Reset Button
resetButton = new JButton("Reset");
resetButton.setFont(new Font("Arial", Font.PLAIN, 15));
resetButton.setSize(100, 20);
resetButton.setLocation(200, 180);
resetButton.addActionListener(this);
container.add(resetButton);

setVisible(true);
}

// Actions on buttons click


public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String username = userTextField.getText();
String password = String.valueOf(passwordField.getPassword());
JOptionPane.showMessageDialog(this, "Login Attempted with Username: " +
username + " and Password: " + password);
} else if (e.getSource() == resetButton) {
userTextField.setText("");
passwordField.setText("");
}
}

public static void main(String[] args) {


new LoginPage();
}
}

—----------------------------------------------------------------------------------
----------------------------------------+++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++

Q1. ComboBox Example (Programming Language)

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

public class ComboBoxExample {


public static void main(String[] args)
{
// Create a new JFrame (window)
JFrame frame = new JFrame("ComboBox Example"); // This creates a new
window titled "ComboBox Example."

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // This ensures


that the program will terminate when the user closes the window.

frame.setSize(400, 200); // Sets the size of the window to 400 pixels


wide and 200 pixels high.

frame.setLayout(new FlowLayout()); // The FlowLayout manager arranges


components in a left-to-right flow, much like words on a page. It ensures the
components (combo box, button, label) are positioned in a simple layou
// Create components (label, combo box, button)
JLabel label = new JLabel("Programming language Selected: "); // Creates
a label to display the selected programming language. Initially, it just displays
the text "Programming language Selected: ".

String[] languages = {"C", "C++", "C#", "Java", "PHP"}; // Defines an


array of strings representing the options (programming languages) to be shown in
the combo box.

JComboBox<String> comboBox = new JComboBox<>(languages); // Creates a


combo box using the languages array. The user can select one of these languages.

JButton showButton = new JButton("Show"); // Creates a button labeled


"Show." When clicked, it will display the selected language.

// Add action listener to the button . Adds an ActionListener to the


"Show" button. This allows the button to respond to clicks.

showButton.addActionListener(new ActionListener()
{

// This method is executed when the button is clicked. The ActionEvent e


contains information about the button click.
public void actionPerformed(ActionEvent e)
{
String selectedLanguage = (String) comboBox.getSelectedItem();
label.setText("Programming language Selected: " +
selectedLanguage); // Updates the text of the label to display the selected
programming language. For example, if "Java" is selected, the label will show
"Programming language Selected: Java."
}
});

// Add components to the frame. These lines add the combo box, button, and
label to the frame (window). Swing components are typically added to a container
like JFrame.

frame.add(comboBox);
frame.add(showButton);
frame.add(label);

// Set frame to be visible . This makes the window visible to the user.
Without this, the window would not appear on the screen.

frame.setVisible(true);
}
}

—-------++++++++++-------

Q2.New User Register

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

public class RegisterGUI {


public static void main(String[] args) {
// Create a new JFrame (window)
JFrame frame = new JFrame("New User Register");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setLayout(new GridBagLayout()); // Using GridBagLayout for flexible
positioning

// Create GridBagConstraints for setting component positions


GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5); // Spacing between components
gbc.fill = GridBagConstraints.HORIZONTAL; // Fill components horizontally

// Create components (labels, text fields, buttons)


JLabel titleLabel = new JLabel("New User Register", JLabel.CENTER);
titleLabel.setFont(new Font("Serif", Font.BOLD, 20));

JLabel firstNameLabel = new JLabel("First name:");


JTextField firstNameText = new JTextField(10);

JLabel lastNameLabel = new JLabel("Last name:");


JTextField lastNameText = new JTextField(10);

JLabel emailLabel = new JLabel("Email address:");


JTextField emailText = new JTextField(10);

JLabel usernameLabel = new JLabel("Username:");


JTextField usernameText = new JTextField(10);

JLabel passwordLabel = new JLabel("Password:");


JPasswordField passwordText = new JPasswordField(10);

JLabel mobileLabel = new JLabel("Mobile number:");


JTextField mobileText = new JTextField(10);

JButton registerButton = new JButton("Register");

// Add components to frame with positions


gbc.gridwidth = 2; // Title spans two columns
gbc.gridx = 0;
gbc.gridy = 0;
frame.add(titleLabel, gbc);

gbc.gridwidth = 1; // Reset for labels and fields


gbc.gridx = 0;
gbc.gridy = 1;
frame.add(firstNameLabel, gbc);
gbc.gridx = 1;
frame.add(firstNameText, gbc);

gbc.gridx = 0;
gbc.gridy = 2;
frame.add(lastNameLabel, gbc);
gbc.gridx = 1;
frame.add(lastNameText, gbc);

gbc.gridx = 0;
gbc.gridy = 3;
frame.add(emailLabel, gbc);
gbc.gridx = 1;
frame.add(emailText, gbc);

gbc.gridx = 2;
gbc.gridy = 1;
frame.add(usernameLabel, gbc);
gbc.gridx = 3;
frame.add(usernameText, gbc);

gbc.gridx = 2;
gbc.gridy = 2;
frame.add(passwordLabel, gbc);
gbc.gridx = 3;
frame.add(passwordText, gbc);

gbc.gridx = 2;
gbc.gridy = 3;
frame.add(mobileLabel, gbc);
gbc.gridx = 3;
frame.add(mobileText, gbc);

gbc.gridwidth = 4; // Register button spans all columns


gbc.gridx = 0;
gbc.gridy = 4;
frame.add(registerButton, gbc);

// Set frame to be visible


frame.setVisible(true);
}
}

—--------------++++++++++++++------------

Q3.LoginGUI

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

public class LoginGUI {


public static void main(String[] args) {
// Create a new JFrame (window)
JFrame frame = new JFrame("Login");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 150);
frame.setLayout(new GridLayout(3, 2));

// Create components (labels, text fields, buttons)


JLabel userLabel = new JLabel("Username:");
JTextField userText = new JTextField();
JLabel passLabel = new JLabel("Password:");
JPasswordField passText = new JPasswordField();
JButton loginButton = new JButton("Login");
JButton resetButton = new JButton("Reset");

// Add components to the frame


frame.add(userLabel);
frame.add(userText);
frame.add(passLabel);
frame.add(passText);
frame.add(loginButton);
frame.add(resetButton);

// Action listener for login button


loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = userText.getText();
String password = new String(passText.getPassword());

// Check if username and password are "admin"


if (username.equals("admin") && password.equals("admin")) {
JOptionPane.showMessageDialog(frame, "Login Successful!");
} else {
JOptionPane.showMessageDialog(frame, "Invalid Username or
Password");
}
}
});

// Action listener for reset button


resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
userText.setText("");
passText.setText("");
}
});

// Set frame to be visible


frame.setVisible(true);
}
}

—-------------++++++++++++++++=-----------

Q4.Customer Details

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

public class CustomerDetailsForm {


public static void main(String[] args) {
// Create the frame
JFrame frame = new JFrame("Customer Account Details");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 100);

// Create a panel with a GridLayout to arrange labels and text fields


JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 2, 10, 10)); // 5 rows, 2 columns, with
10px gaps
// Add labels and text fields
JLabel nameLabel = new JLabel("Name of Customer:");
JTextField nameField = new JTextField(20);

JLabel bankLabel = new JLabel("Name of Bank:");


JTextField bankField = new JTextField(20);

JLabel accountLabel = new JLabel("Account No.:");


JTextField accountField = new JTextField(20);

JLabel panLabel = new JLabel("Pan Number:");


JTextField panField = new JTextField(20);

// Add the components to the panel


panel.add(nameLabel);
panel.add(nameField);
panel.add(bankLabel);
panel.add(bankField);
panel.add(accountLabel);
panel.add(accountField);
panel.add(panLabel);
panel.add(panField);

// Create a label for error messages


JLabel messageLabel = new JLabel("");
messageLabel.setForeground(Color.RED);

// Add a submit button


JButton submitButton = new JButton("Submit");
panel.add(submitButton);

// Add the message label below the submit button


panel.add(messageLabel);

// Add the panel to the frame


frame.add(panel);

// Set the frame visible


frame.setVisible(true);

// Add action listener to the submit button


submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Get the text from the fields
String name = nameField.getText();
String bank = bankField.getText();
String account = accountField.getText();
String pan = panField.getText();

// Check if any field is empty


if (name.isEmpty() || bank.isEmpty() || account.isEmpty() ||
pan.isEmpty()) {
messageLabel.setText("Please fill in all the details!");
} else {
messageLabel.setText("Details submitted successfully.");
messageLabel.setForeground(Color.GREEN);
}
}
});
}
}

—----------------+++++++++++++++======-----------

Q5. Simple Calculator

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

class SimpleCalculator{
public static void main(String[] args) {
// Create the frame
JFrame frame = new JFrame("Calculator with Search Bar");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 500); // Increased size to accommodate the search bar

// Main panel with BorderLayout


JPanel mainPanel = new JPanel(new BorderLayout());

// Create the search bar


JTextField searchBar = new JTextField();
searchBar.setHorizontalAlignment(JTextField.CENTER);
searchBar.setText("Search..."); // Placeholder text
mainPanel.add(searchBar, BorderLayout.NORTH); // Search bar at the top

// Panel for the calculator display and buttons


JPanel calculatorPanel = new JPanel(new BorderLayout());

// Create the display field for calculator


JTextField displayField = new JTextField();
displayField.setEditable(false);
displayField.setHorizontalAlignment(JTextField.RIGHT);
calculatorPanel.add(displayField, BorderLayout.NORTH); // Display at the
top

// Create a panel for buttons (4x3 grid layout)


JPanel buttonPanel = new JPanel(new GridLayout(4, 3, 10, 10)); // 4 rows,
3 columns, 10px gaps

// Array of button labels


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

// Add buttons to the panel


for (String text : buttons) {
JButton button = new JButton(text);
buttonPanel.add(button);

// Add action listener to each button


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (text.equals("Clear")) {
displayField.setText(""); // Clear the display if "Clear"
is clicked
} else {
displayField.setText(displayField.getText() + text); //
Append the button text to the display
}
}
});
}

// Add the button panel to the calculator panel


calculatorPanel.add(buttonPanel, BorderLayout.CENTER);

// Add calculator panel to the main panel


mainPanel.add(calculatorPanel, BorderLayout.CENTER);

// Set the layout and add the main panel to the frame
frame.add(mainPanel);

// Make the frame visible


frame.setVisible(true);
}
}

You might also like