Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Java lab

dsa

Uploaded by

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

Java lab

dsa

Uploaded by

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

Salary

import java.util.Scanner;

public class SalaryCalculator {

public static void main(String[] args) {

int empNo;
String empName;
double basic, da, hra, cca = 240, pf, pt = 100, grossSalary, netSalary;

Scanner scanner = new Scanner(System.in);

System.out.print("Enter Employee Number: ");


empNo = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Employee Name: ");
empName = scanner.nextLine();
System.out.print("Enter Basic Salary: ");
basic = scanner.nextDouble();

da = 0.70 * basic;
hra = 0.30 * basic;
pf = 0.10 * basic;

grossSalary = basic + da + hra + cca;

netSalary = grossSalary - pf - pt;

System.out.println("\nEmployee Number: " + empNo);


System.out.println("Employee Name: " + empName);
System.out.println("Basic Salary: Rs" + basic);
System.out.println("Gross Salary: Rs" + grossSalary);
System.out.println("Net Salary: Rs" + netSalary);
}
}
Quadratic
import java.util.Scanner;

public class QuadraticEquationSolver {

public static void main(String[] args) {

double a, b, c;
double discriminant, root1, root2;

Scanner scanner = new Scanner(System.in);

System.out.print("Enter coefficient a: ");


a = scanner.nextDouble();
System.out.print("Enter coefficient b: ");
b = scanner.nextDouble();
System.out.print("Enter coefficient c: ");
c = scanner.nextDouble();

discriminant = (b * b) - (4 * a * c);

if (discriminant > 0) {

root1 = (-b + Math.sqrt(discriminant)) / (2 * a);


root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The equation has two real and distinct solutions:");
System.out.println("Root 1: " + root1);
System.out.println("Root 2: " + root2);
} else if (discriminant == 0) {

root1 = -b / (2 * a);
System.out.println("The equation has one real solution (double root):");
System.out.println("Root: " + root1);
} else {

System.out.println("The equation has no real solutions.");


}
}
}

Rectangle
import java.util.Scanner;

class Area {

private double length;


private double breadth;

public void setDim(double length, double breadth) {


this.length = length;
this.breadth = breadth;
}

public double getArea() {


return length * breadth;
}
}

public class Main {


public static void main(String[] args) {

Area rectangle = new Area();

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the length of the rectangle: ");


double length = scanner.nextDouble();
System.out.print("Enter the breadth of the rectangle: ");
double breadth = scanner.nextDouble();

rectangle.setDim(length, breadth);

double area = rectangle.getArea();


System.out.println("The area of the rectangle is: " + area);
}
}

Chaining
import java.util.Scanner;
class Parent {

public Parent() {
System.out.println("Parent class constructor called.");
}
}
class Child extends Parent {
private int a, b;
public Child() {
super();
System.out.println("Default constructor of Child class called.");
}
public Child(int a, int b) {
super();
this.a = a;
this.b = b;
System.out.println("Parameterized constructor of Child class called with a = " + a
+ " and b = " + b);
}
public void display() {
System.out.println("a: " + a + ", b: " + b);
}
}
public class ConstructorChainingDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter value for a: ");
int a = scanner.nextInt();
System.out.print("Enter value for b: ");
int b = scanner.nextInt();
Child childObject = new Child(a, b);
childObject.display();
}
}

Student
import java.util.Scanner;
class Student {

private String name;


private int age;
private String address;

public Student() {
this.name = "unknown";
this.age = 0;
this.address = "not available";
}

public void setInfo(String name, int age) {


this.name = name;
this.age = age;
}

public void setInfo(String name, int age, String address) {


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

public void printInfo() {


System.out.println("Name: " + name + ", Age: " + age + ", Address: " + address);
}
}

public class StudentInfoDemo {


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

Student[] students = new Student[10];

for (int i = 0; i < students.length; i++) {


students[i] = new Student();

System.out.println("Enter details for Student " + (i + 1) + ":");


System.out.print("Enter name: ");
String name = scanner.nextLine();
System.out.print("Enter age: ");
int age = scanner.nextInt();
scanner.nextLine();

System.out.print("Do you want to enter an address? (yes/no): ");


String choice = scanner.nextLine();

if (choice.equalsIgnoreCase("yes")) {
System.out.print("Enter address: ");
String address = scanner.nextLine();

students[i].setInfo(name, age, address);


} else {

students[i].setInfo(name, age);
}
}

System.out.println("\nStudent Information:");
for (int i = 0; i < students.length; i++) {
System.out.println("Student " + (i + 1) + ":");
students[i].printInfo();
System.out.println();
}
}
}

Employee
import java.util.Scanner;

class Employee {
private int empNo;
private String name;
private double salary;

public Employee(int empNo, String name, double salary) {


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

public int getEmpNo() {


return empNo;
}

public String getName() {


return name;
}

public double getSalary() {


return salary;
}

public void enhanceSalary(double percentage) {


this.salary += this.salary * (percentage / 100);
}

public void printEmployeeDetails() {


System.out.println("Employee Number: " + empNo);
System.out.println("Employee Name: " + name);
System.out.println("Salary: Rs." + salary);
}
}

class Department {

private String deptName;


private Employee headOfDepartment;

public Department(String deptName, Employee headOfDepartment) {


this.deptName = deptName;
this.headOfDepartment = headOfDepartment;
}
public void changeHead(Employee newHead) {
this.headOfDepartment = newHead;
}

public void printDepartmentDetails() {


System.out.println("Department Name: " + deptName);
System.out.println("Head of Department: " + headOfDepartment.getName());
}
}

public class OrganizationDemo {


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

Employee[] employees = new Employee[3];


for (int i = 0; i < 3; i++) {
System.out.println("Enter details for Employee " + (i + 1) + ":");
System.out.print("Employee Number: ");
int empNo = scanner.nextInt();
scanner.nextLine();
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Salary: ");
double salary = scanner.nextDouble();
scanner.nextLine();

employees[i] = new Employee(empNo, name, salary);


System.out.println();
}

System.out.print("Enter Department Name: ");


String deptName = scanner.nextLine();
Department dept = new Department(deptName, employees[0]);

System.out.println("\nInitial Details:");
dept.printDepartmentDetails();
System.out.println();
employees[0].printEmployeeDetails();
System.out.println();

System.out.println("Enter the new head of department (Employee Number): ");


int newHeadEmpNo = scanner.nextInt();
scanner.nextLine();

for (Employee emp : employees) {


if (emp.getEmpNo() == newHeadEmpNo) {
dept.changeHead(emp);
break;
}
}

System.out.println("\nAfter one year:");


dept.printDepartmentDetails();
System.out.println();

for (int i = 0; i < employees.length; i++) {


System.out.print("Enter the percentage increase for Employee " +
employees[i].getName() + ": ");
double percentage = scanner.nextDouble();
employees[i].enhanceSalary(percentage);
}

System.out.println("\nUpdated Employee Details:");


for (Employee emp : employees) {
emp.printEmployeeDetails();
System.out.println();
}

scanner.close();
}
}

Professor
import java.util.Scanner;

class Teacher {

private String name;


private int age;
private String department;
public Teacher(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}

public void displayInfo() {


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Department: " + department);
}
}

class Professor extends Teacher {

public Professor(String name, int age, String department) {


super(name, age, department);
}

public void displayInfo() {


super.displayInfo();
System.out.println("Designation: Professor");
}
}

class Associate_Professor extends Teacher {


public Associate_Professor(String name, int age, String department) {
super(name, age, department);
}

public void displayInfo() {


super.displayInfo();
System.out.println("Designation: Associate Professor");
}
}

class Assistant_Professor extends Teacher {


public Assistant_Professor(String name, int age, String department) {
super(name, age, department);
}
public void displayInfo() {
super.displayInfo();
System.out.println("Designation: Assistant Professor");
}
}

public class UniversityDemo {


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

System.out.println("Enter details for the Professor:");


System.out.print("Name: ");
String professorName = scanner.nextLine();
System.out.print("Age: ");
int professorAge = scanner.nextInt();
scanner.nextLine();
System.out.print("Department: ");
String professorDept = scanner.nextLine();

System.out.println("\nEnter details for the Associate Professor:");


System.out.print("Name: ");
String associateProfessorName = scanner.nextLine();
System.out.print("Age: ");
int associateProfessorAge = scanner.nextInt();
scanner.nextLine();
System.out.print("Department: ");
String associateProfessorDept = scanner.nextLine();

System.out.println("\nEnter details for the Assistant Professor:");


System.out.print("Name: ");
String assistantProfessorName = scanner.nextLine();
System.out.print("Age: ");
int assistantProfessorAge = scanner.nextInt();
scanner.nextLine();
System.out.print("Department: ");
String assistantProfessorDept = scanner.nextLine();

Professor prof = new Professor(professorName, professorAge, professorDept);


Associate_Professor assocProf = new
Associate_Professor(associateProfessorName, associateProfessorAge,
associateProfessorDept);
Assistant_Professor asstProf = new
Assistant_Professor(assistantProfessorName, assistantProfessorAge,
assistantProfessorDept);

System.out.println("\nProfessor Details:");
prof.displayInfo();
System.out.println();

System.out.println("Associate Professor Details:");


assocProf.displayInfo();
System.out.println();

System.out.println("Assistant Professor Details:");


asstProf.displayInfo();

scanner.close();
}
}

Vehicle

interface Vehicle {

void start();

void stop();
void speedUp(int increment);
}

class Bicycle implements Vehicle {


private int speed;

public Bicycle() {
this.speed = 0;
}

public void start() {


System.out.println("Bicycle started.");
}

public void stop() {


System.out.println("Bicycle stopped.");
speed = 0;
}

public void speedUp(int increment) {


speed += increment;
System.out.println("Bicycle speed increased by " + increment + ". Current speed:
" + speed);
}
}

class Car implements Vehicle {


private int speed;

public Car() {
this.speed = 0;
}

public void start() {


System.out.println("Car engine started.");
}

public void stop() {


System.out.println("Car stopped.");
speed = 0; // Reset speed to 0
}

public void speedUp(int increment) {


speed += increment;
System.out.println("Car speed increased by " + increment + ". Current speed: " +
speed);
}
}

class Bike implements Vehicle {


private int speed;

public Bike() {
this.speed = 0;
}

public void start() {


System.out.println("Bike started.");
}

public void stop() {


System.out.println("Bike stopped.");
speed = 0; // Reset speed to 0
}

public void speedUp(int increment) {


speed += increment;
System.out.println("Bike speed increased by " + increment + ". Current speed: "
+ speed);
}
}

public class VehicleDemo {


public static void main(String[] args) {

Vehicle bicycle = new Bicycle();


Vehicle car = new Car();
Vehicle bike = new Bike();
System.out.println("Bicycle:");
bicycle.start();
bicycle.speedUp(5);
bicycle.stop();
System.out.println();

System.out.println("Car:");
car.start();
car.speedUp(20);
car.stop();
System.out.println();

System.out.println("Bike:");
bike.start();
bike.speedUp(10);
bike.stop();
}
}

Words
import java.util.Scanner;

public class AmountInWords {

private static final String[] units = {


"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen"
};

private static final String[] tens = {


"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};

private String convertThreeDigitNumber(int number) {


String result = "";

if (number >= 100) {


result += units[number / 100] + " hundred ";
number %= 100;
}

if (number >= 20) {


result += tens[number / 10] + " ";
number %= 10;
}

if (number > 0) {
result += units[number];
}

return result.trim();
}

public String convertAmountToWords(int amount) {


if (amount == 0) {
return "zero";
} else if (amount < 0) {
return "Negative amounts are not supported.";
} else if (amount > 100000) {
return "Amount exceeds limit of 100,000.";
}

String result = "";

if (amount >= 1000) {


result += convertThreeDigitNumber(amount / 1000) + " thousand ";
amount %= 1000;
}

if (amount > 0) {
result += convertThreeDigitNumber(amount);
}

return result.trim();
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
AmountInWords converter = new AmountInWords();

System.out.print("Enter an amount (not more than 100,000): ");


int amount = scanner.nextInt();

String amountInWords = converter.convertAmountToWords(amount);


System.out.println("Amount in words: " + amountInWords);

scanner.close();
}
}

Login
import java.util.Scanner;

class InvalidPasswordException extends Exception {


public InvalidPasswordException(String message) {
super(message);
}
}

public class LoginSystem {

public static void validatePassword(String password) throws


InvalidPasswordException {
if (password.length() != 8) {
throw new InvalidPasswordException("Password must be 8 characters long.");
}

boolean hasDigit = password.matches(".*\\d.*");


boolean hasSpecialChar = password.matches(".*[^a-zA-Z0-9].*");

if (!hasDigit || !hasSpecialChar) {
throw new InvalidPasswordException("Password must contain at least one
digit and one special character.");
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter Login ID: ");


String loginID = scanner.nextLine();

System.out.print("Enter Password: ");


String password = scanner.nextLine();

try {
validatePassword(password);
System.out.println("Login Successful for user: " + loginID);
} catch (InvalidPasswordException e) {
System.out.println(e.getMessage());
System.out.println("Please enter a valid password of length 8, containing at
least one digit and one special symbol.");
}
scanner.close();
}
}
Thread
import java.util.Scanner;

class NumberPrinter {
private int number = 1;
private int limit;

public NumberPrinter(int limit) {


this.limit = limit;
}

public synchronized void printOdd() {


while (number <= limit) {
if (number % 2 == 0) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("Odd Thread: " + number);
number++;
notify();
}
}

public synchronized void printEven() {


while (number <= limit) {
if (number % 2 != 0) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("Even Thread: " + number);
number++;
notify();
}
}
}

public class OddEvenThread {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the limit for printing numbers: ");
int limit = scanner.nextInt();

NumberPrinter numberPrinter = new NumberPrinter(limit);

Thread oddThread = new Thread(() -> numberPrinter.printOdd());


Thread evenThread = new Thread(() -> numberPrinter.printEven());

oddThread.start();
evenThread.start();
}
}
Swing
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class BookInfoApp extends JFrame {

private JTextField titleField, authorField, yearField;


private JComboBox<String> genreComboBox;
private JTable bookTable;
private DefaultTableModel tableModel;

public BookInfoApp() {
setTitle("Book Information Form");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
setLayout(new BorderLayout());

createMenuBar();
createToolBar();

JPanel mainPanel = new JPanel();


mainPanel.setLayout(new GridLayout(4, 1));

JPanel titlePanel = new JPanel();


titlePanel.add(new JLabel("Title: "));
titleField = new JTextField(20);
titlePanel.add(titleField);
mainPanel.add(titlePanel);

JPanel authorPanel = new JPanel();


authorPanel.add(new JLabel("Author: "));
authorField = new JTextField(20);
authorPanel.add(authorField);
mainPanel.add(authorPanel);

JPanel genrePanel = new JPanel();


genrePanel.add(new JLabel("Genre: "));
String[] genres = {"Fiction", "Non-Fiction", "Science Fiction", "Fantasy",
"Mystery"};
genreComboBox = new JComboBox<>(genres);
genrePanel.add(genreComboBox);
mainPanel.add(genrePanel);

JPanel yearPanel = new JPanel();


yearPanel.add(new JLabel("Publication Year: "));
yearField = new JTextField(4);
yearPanel.add(yearField);
mainPanel.add(yearPanel);

add(mainPanel, BorderLayout.NORTH);

DefaultListModel<String> listModel = new DefaultListModel<>();


JList<String> bookList = new JList<>(listModel);
JScrollPane listScrollPane = new JScrollPane(bookList);
add(listScrollPane, BorderLayout.WEST);
String[] columnNames = {"Title", "Author", "Genre", "Year"};
tableModel = new DefaultTableModel(columnNames, 0);
bookTable = new JTable(tableModel);
JScrollPane tableScrollPane = new JScrollPane(bookTable);
add(tableScrollPane, BorderLayout.CENTER);

DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Books");


JTree bookTree = new JTree(rootNode);
JScrollPane treeScrollPane = new JScrollPane(bookTree);
add(treeScrollPane, BorderLayout.EAST);

JButton submitButton = new JButton("Submit");


submitButton.addActionListener(new SubmitAction(listModel, rootNode));
add(submitButton, BorderLayout.SOUTH);
}

private void createMenuBar() {


JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(e -> System.exit(0));
fileMenu.add(exitItem);

menuBar.add(fileMenu);
setJMenuBar(menuBar);
}

private void createToolBar() {


JToolBar toolBar = new JToolBar();
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(e -> clearForm());
toolBar.add(clearButton);
add(toolBar, BorderLayout.NORTH);
}

private void clearForm() {


titleField.setText("");
authorField.setText("");
yearField.setText("");
genreComboBox.setSelectedIndex(0);
}

private class SubmitAction implements ActionListener {


private DefaultListModel<String> listModel;
private DefaultMutableTreeNode rootNode;
public SubmitAction(DefaultListModel<String> listModel,
DefaultMutableTreeNode rootNode) {
this.listModel = listModel;
this.rootNode = rootNode;
}

@Override
public void actionPerformed(ActionEvent e) {
String title = titleField.getText().trim();
String author = authorField.getText().trim();
String genre = (String) genreComboBox.getSelectedItem();
String year = yearField.getText().trim();

if (title.isEmpty() || author.isEmpty() || year.isEmpty()) {


JOptionPane.showMessageDialog(BookInfoApp.this, "Please fill in all
fields.", "Input Error", JOptionPane.ERROR_MESSAGE);
return;
}

tableModel.addRow(new Object[]{title, author, genre, year});


listModel.addElement(title + " by " + author);
rootNode.add(new DefaultMutableTreeNode(title + " by " + author));
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
BookInfoApp app = new BookInfoApp();
app.setVisible(true);
});
}
}

Student Profile
import java.awt.*;
import java.awt.event.*;

public class StudentProfileForm extends Frame implements ActionListener {


Label nameLabel, ageLabel, genderLabel, addressLabel, contactLabel,
academicLabel;
TextField nameField, ageField, addressField, contactField;
CheckboxGroup genderGroup;
Checkbox maleCheckbox, femaleCheckbox;
Button submitButton, resetButton;
TextArea displayArea;
public StudentProfileForm() {
setTitle("Student Profile Form");
setSize(1000, 600);
setLocationRelativeTo(null);
setLayout(new GridLayout(8, 5));

nameLabel = new Label("Name:");


nameField = new TextField();

ageLabel = new Label("Age:");


ageField = new TextField();

genderLabel = new Label("Gender:");


genderGroup = new CheckboxGroup();
maleCheckbox = new Checkbox("Male", genderGroup, false);
femaleCheckbox = new Checkbox("Female", genderGroup, false);

addressLabel = new Label("Address:");


addressField = new TextField();

contactLabel = new Label("Contact:");


contactField = new TextField();

academicLabel = new Label("Academic Info:");


displayArea = new TextArea();

submitButton = new Button("Submit");


resetButton = new Button("Reset");

add(nameLabel);
add(nameField);
add(ageLabel);
add(ageField);
add(genderLabel);
add(maleCheckbox);
add(new Label(""));
add(femaleCheckbox);
add(addressLabel);
add(addressField);
add(contactLabel);
add(contactField);
add(submitButton);
add(resetButton);
add(academicLabel);
add(displayArea);

submitButton.addActionListener(this);
resetButton.addActionListener(this);

setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == submitButton) {
handleSubmit();
} else if (e.getSource() == resetButton) {
handleReset();
}
}

private void handleSubmit() {


String name = nameField.getText();
String age = ageField.getText();
String gender = genderGroup.getSelectedCheckbox() != null ?
genderGroup.getSelectedCheckbox().getLabel() : "";
String address = addressField.getText();
String contact = contactField.getText();

if (name.isEmpty() || age.isEmpty() || gender.isEmpty() || address.isEmpty() ||


contact.isEmpty()) {
displayArea.setText("Please fill all fields.");
return;
}

displayArea.setText("Student Profile:\n");
displayArea.append("Name: " + name + "\n");
displayArea.append("Age: " + age + "\n");
displayArea.append("Gender: " + gender + "\n");
displayArea.append("Address: " + address + "\n");
displayArea.append("Contact: " + contact + "\n");
}

private void handleReset() {


nameField.setText("");
ageField.setText("");
genderGroup.setSelectedCheckbox(null);
addressField.setText("");
contactField.setText("");
displayArea.setText("");
}

public static void main(String[] args) {


new StudentProfileForm();
}
}

Login using Javafx


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

public class LibraryLoginForm extends JFrame {


private JTextField usernameField;
private JPasswordField passwordField;

public LibraryLoginForm() {
setTitle("Library Login Form");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridBagLayout());

GridBagConstraints gbc = new GridBagConstraints();


gbc.fill = GridBagConstraints.HORIZONTAL;

gbc.gridx = 0;
gbc.gridy = 0;
add(new JLabel("Username:"), gbc);

usernameField = new JTextField(15);


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

gbc.gridx = 0;
gbc.gridy = 1;
add(new JLabel("Password:"), gbc);

passwordField = new JPasswordField(15);


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

JButton loginButton = new JButton("Login");


loginButton.addActionListener(new LoginAction());
gbc.gridx = 1;
gbc.gridy = 2;
add(loginButton, gbc);

JButton exitButton = new JButton("Exit");


exitButton.addActionListener(e -> System.exit(0));
gbc.gridx = 1;
gbc.gridy = 3;
add(exitButton, gbc);
}

private class LoginAction implements ActionListener {


@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText().trim();
String password = new String(passwordField.getPassword());

if (isValid(username, password)) {
showMessage("Login Successful", "Welcome to the Library, " + username +
"!");
usernameField.setText("");
passwordField.setText("");
} else {
showMessage("Login Failed", "Invalid username or password.");
}
}
}

private boolean isValid(String username, String password) {


return username.equals("rutuja39") && password.equals("rutuja12");
}

private void showMessage(String title, String message) {


JOptionPane.showMessageDialog(this, message, title,
JOptionPane.INFORMATION_MESSAGE);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
LibraryLoginForm form = new LibraryLoginForm();
form.setVisible(true);
});
}
}

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

public class ShapeDrawerSwing extends JPanel {

private enum ShapeType {


CIRCLE, RECTANGLE, POLYGON
}

private ShapeType currentShape = ShapeType.CIRCLE;


@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);

switch (currentShape) {
case CIRCLE:
g2d.drawOval(200, 100, 200, 200);
break;
case RECTANGLE:
g2d.drawRect(150, 100, 300, 150);
break;
case POLYGON:
int[] xPoints = {300, 450, 300, 150};
int[] yPoints = {50, 150, 250, 150};
int nPoints = 4;
g2d.drawPolygon(xPoints, yPoints, nPoints);
break;
}
}

public void setCurrentShape(ShapeType shape) {


this.currentShape = shape;
repaint();
}

public static void main(String[] args) {


JFrame frame = new JFrame("Shape Drawer");
ShapeDrawerSwing panel = new ShapeDrawerSwing();
String[] shapes = {"Circle", "Rectangle", "Polygon"};
JComboBox<String> shapeSelector = new JComboBox<>(shapes);

shapeSelector.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String selectedShape = (String) shapeSelector.getSelectedItem();
switch (selectedShape) {
case "Circle":
panel.setCurrentShape(ShapeType.CIRCLE);
break;
case "Rectangle":
panel.setCurrentShape(ShapeType.RECTANGLE);
break;
case "Polygon":
panel.setCurrentShape(ShapeType.POLYGON);
break;
}
}
});

frame.setLayout(new BorderLayout());
frame.add(shapeSelector, BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

You might also like