Java Lab File
Java Lab File
SOURCE CODE
class Stack {
private int maxSize;
private int top;
private int[] stackArray;
OUTPUT
Practical -4
➢ Aim: WAP to implement the concept of String and String Buffer.
SOURCE CODE
public class StringVsStringBuffer {
public static void main(String[] args) {
buffer.append(" World!");
System.out.println("StringBuffer after append: " + buffer);
buffer.insert(5, ",");
System.out.println("StringBuffer after insert: " + buffer);
buffer.reverse();
System.out.println("StringBuffer after reverse: " + buffer);
buffer.reverse();
System.out.println("StringBuffer after re-reverse: " + buffer);
buffer.replace(0, 5, "Hi");
System.out.println("StringBuffer after replace: " + buffer);
System.out.println("Length of StringBuffer: " + buffer.length());
System.out.println("Capacity of StringBuffer: " + buffer.capacity());
}
}
OUTPUT
Practical -5
➢ Aim: WAP in java to implement the concept of Exception Handling with five
Keywords: -TRY, CATCH, FINALLY, THROW and THROWS.
SOURCE CODE
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
class InvalidDepositException extends Exception {
public InvalidDepositException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
OUTPUT
Practical -6
➢ Aim: Write a java program to show the concept of multithreading.
SOURCE CODE
class SAITM {
private int availableSeats;
@Override
public void run() {
// Apply for admission
saitm.applyForAdmission(studentName);
}
}
public class CollegeAdmissionSystem {
public static void main(String[] args) {
student1.start();
student2.start();
student3.start();
student4.start();
}
}
OUTPUT
Practical -3
➢ Aim: Write a java package to show dynamic polymorphism
and interfaces.
SOURCE CODE
package polymorphism; // package polymorphism declared for all classes
OUTPUT
Practical -8
➢ Aim: WAP in Java to create a Calculator using AWT.
SOURCE CODE
public class myCalculator extends javax.swing.JFrame {
double num1=0,num2=0;
String operator=null;
/**
* Creates new form myCalculator
*/
public myCalculator() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton3.setText("jButton1");
jButton4.setText("jButton1");
jButton15.setText("jButton1");
jButton16.setText("jButton1");
jButton17.setText("jButton1");
jButton18.setText("jButton1");
jButton20.setText("-");
jButton21.setText("2");
jButton23.setText("3");
jButton24.setText("1");
jButton19.setText("jButton1");
jButton22.setText("jButton1");
jButton28.setText("1");
jButton30.setText("0");
jButton31.setText("+");
jButton32.setText(".");
jButton33.setText("=");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
b7.setText("7");
b7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b7ActionPerformed(evt);
}
});
bdiv.setText("/");
bdiv.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bdivActionPerformed(evt);
}
});
b8.setText("8");
b8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b8ActionPerformed(evt);
}
});
b9.setText("9");
b9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b9ActionPerformed(evt);
}
});
bmul.setText("x");
bmul.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bmulActionPerformed(evt);
}
});
b5.setText("5");
b5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b5ActionPerformed(evt);
}
});
b6.setText("6");
b6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b6ActionPerformed(evt);
}
});
b4.setText("4");
b4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b4ActionPerformed(evt);
}
});
bsub.setText("-");
bsub.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bsubActionPerformed(evt);
}
});
b2.setText("2");
b2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b2ActionPerformed(evt);
}
});
b3.setText("3");
b3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b3ActionPerformed(evt);
}
});
b1.setText("1");
b1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b1ActionPerformed(evt);
}
});
badd.setText("+");
badd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
baddActionPerformed(evt);
}
});
bdot.setText(".");
bdot.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bdotActionPerformed(evt);
}
});
bequal.setText("=");
bequal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bequalActionPerformed(evt);
}
});
b0.setText("0");
b0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b0ActionPerformed(evt);
}
});
bclear.setText("Clear");
bclear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bclearActionPerformed(evt);
}
});
bback.setText("Back");
bback.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bbackActionPerformed(evt);
}
});
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(t1)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(bclear, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING,
layout.createSequentialGroup()
.addComponent(b0, javax.swing.GroupLayout.PREFERRED_SIZE, 67,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(bdot, javax.swing.GroupLayout.PREFERRED_SIZE, 66,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(bequal, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(badd, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(bback, javax.swing.GroupLayout.PREFERRED_SIZE, 148,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(b4, javax.swing.GroupLayout.PREFERRED_SIZE, 67,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b5, javax.swing.GroupLayout.PREFERRED_SIZE, 66,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b6, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(bmul, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(b7, javax.swing.GroupLayout.PREFERRED_SIZE, 67,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b8, javax.swing.GroupLayout.PREFERRED_SIZE, 66,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b9, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(bdiv, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(b1, javax.swing.GroupLayout.PREFERRED_SIZE, 67,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b2, javax.swing.GroupLayout.PREFERRED_SIZE, 66,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b3, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(bsub, javax.swing.GroupLayout.PREFERRED_SIZE, 65,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(12, 12, 12))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 39,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, 35,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b7, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b8, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b9, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bdiv, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b4, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b5, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b6, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bmul, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b1, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b2, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b3, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bsub, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bdot, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bequal, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(badd, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(b0, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bback, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bclear, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
operator="*";
}
t1.setText(t1.getText()+"7");
}
operator="/";
}
operator="-";
}
operator="+";
}
num2 = Double.parseDouble(t1.getText());
double ans=0;
if(operator =="+")
{
ans= num1 + num2;
}
if(operator =="*")
{
ans= num1 * num2;
}
if(operator =="-")
{
ans= num1 - num2;
}
if(operator =="/")
{
ans= num1 / num2;
}
t1.setText(""+ans);
operator=null;
}
t1.setText("");
}
t1.setText(str.substring(0,str.length()-1));
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(myCalculator.class.getName()).log(java.util.logging.Level.SEVE
RE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(myCalculator.class.getName()).log(java.util.logging.Level.SEVE
RE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(myCalculator.class.getName()).log(java.util.logging.Level.SEVE
RE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(myCalculator.class.getName()).log(java.util.logging.Level.SEVE
RE, null, ex);
}
//</editor-fold>
OUTPUT
Practical -9
➢ Aim: Create an editor like MS-word using swings.
SOURCE CODE
package ms.word.application;
import java.awt.Font;
import javax.swing.*;
import java.awt.event.*;
import java.awt.print.PrinterException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.filechooser.FileNameExtensionFilter;
MSWordApplication() {
setTitle("MS Word Application");
setBounds(100, 100, 800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setJMenuBar(menubar);
menubar.add(file);
menubar.add(edit);
menubar.add(view); // Add View menu to menu bar
menubar.add(help);
file.add(newFile);
file.add(openFile);
file.add(saveFile);
file.add(print);
file.add(exit);
edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(selectall);
newFile.addActionListener(this);
openFile.addActionListener(this);
saveFile.addActionListener(this);
print.addActionListener(this);
exit.addActionListener(this);
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectall.addActionListener(this);
zoomIn.addActionListener(this); // Add action listener for Zoom In
zoomOut.addActionListener(this); // Add action listener for Zoom Out
about.addActionListener(this);
newFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
KeyEvent.CTRL_DOWN_MASK));
openFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
KeyEvent.CTRL_DOWN_MASK));
saveFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
KeyEvent.CTRL_DOWN_MASK));
print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
KeyEvent.CTRL_DOWN_MASK));
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
KeyEvent.CTRL_DOWN_MASK));
cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
KeyEvent.CTRL_DOWN_MASK));
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
KeyEvent.CTRL_DOWN_MASK));
paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
KeyEvent.CTRL_DOWN_MASK));
selectall.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
KeyEvent.CTRL_DOWN_MASK));
zoomIn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS,
KeyEvent.CTRL_DOWN_MASK));
zoomOut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS,
KeyEvent.CTRL_DOWN_MASK));
about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_J,
KeyEvent.CTRL_DOWN_MASK));
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("New")) {
textArea.setText(null);
} else if (e.getActionCommand().equalsIgnoreCase("Open")) {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter textFilter = new FileNameExtensionFilter("Only Text Files(.txt)",
"txt");
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.addChoosableFileFilter(textFilter);
if (action != JFileChooser.APPROVE_OPTION) {
return;
} else {
try {
BufferedReader reader = new BufferedReader(new
FileReader(fileChooser.getSelectedFile()));
textArea.read(reader, null);
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} else if (e.getActionCommand().equalsIgnoreCase("Save")) {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter textFilter = new FileNameExtensionFilter("Only Text Files(.txt)",
"txt");
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.addChoosableFileFilter(textFilter);
OUTPUT
Practical -1
➢ Aim: Write a program in java to print your details (Name, Rollno, Class, Sem,
College Name) and create the JAR file of this program with both outputs i.e.
.java and .jar.
SOURCE CODE
package studentdetails;
import java.util.Scanner;
public class StudentDetails {
}
OUTPUT
SOURCE CODE
import java.util.*;
System.out.println("\nSet Operations:");
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
System.out.println("Initial Set: " + set);
set.remove("Banana");
System.out.println("After Removing 'Banana': " + set);
System.out.println("Contains 'Apple'? " + set.contains("Apple"));
set.add("Date");
set.add("Elderberry");
System.out.println("Set after adding new elements: " + set);
System.out.println("Size of Set: " + set.size());
System.out.println("Is Set empty? " + set.isEmpty()); // Check if set is empty
set.clear(); // Clear the set
System.out.println("Set after clear: " + set);
System.out.println("\nMap Operations:");
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
System.out.println("Initial Map: " + map);
System.out.println("Get value for key 2: " + map.get(2));
map.remove(1);
System.out.println("Map after removing key 1: " + map);
System.out.println("Contains key 3? " + map.containsKey(3));
map.put(4, "Four");
map.put(5, "Five");
System.out.println("Final Map: " + map);
System.out.println("Size of Map: " + map.size());
System.out.println("Contains value 'Four'? " + map.containsValue("Four")); // Check if value
exists
map.replace(2, "Second"); // Replace value for a key
System.out.println("Map after replace operation on key 2: " + map);
}
OUTPUT
Practical -7
➢ Aim: WAP in java to create package in java.
SOURCE CODE
package shapes; //package shapes declared for all classes
// Constructor
public Circle(double radius) {
this.radius = radius;
}
// Constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Constructor
public Square(double side) {
this.side = side;
}
package geometryapp;
import shapes.Circle;
import shapes.Rectangle;
import shapes.Square;
System.out.println("\nRectangle:");
System.out.println("Area: " + rectangle.getArea());
System.out.println("Perimeter: " + rectangle.getPerimeter());
System.out.println("\nSquare:");
System.out.println("Area: " + square.getArea());
System.out.println("Perimeter: " + square.getPerimeter());
}
}
OUTPUT
Practical -2
➢ Aim: Create a registration page with JDBC connectivity.
SOURCE CODE
package dbconnect;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public StudentAppRedesigned() {
// Set up JFrame
setTitle("Student Management System");
setSize(700, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
gbc.gridx = 0;
gbc.gridy = 0;
JLabel regnLabel = new JLabel("Registration No:");
regnLabel.setFont(labelFont);
inputPanel.add(regnLabel, gbc);
gbc.gridx = 1;
regnField = new JTextField(20);
regnField.setFont(new Font("Serif", Font.PLAIN, 16));
inputPanel.add(regnField, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
JLabel nameLabel = new JLabel("Name:");
nameLabel.setFont(labelFont);
inputPanel.add(nameLabel, gbc);
gbc.gridx = 1;
nameField = new JTextField(20);
nameField.setFont(new Font("Serif", Font.PLAIN, 16));
inputPanel.add(nameField, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
JLabel rollnoLabel = new JLabel("Roll No:");
rollnoLabel.setFont(labelFont);
inputPanel.add(rollnoLabel, gbc);
gbc.gridx = 1;
rollnoField = new JTextField(20);
rollnoField.setFont(new Font("Serif", Font.PLAIN, 16));
inputPanel.add(rollnoField, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
JLabel branchLabel = new JLabel("Branch:");
branchLabel.setFont(labelFont);
inputPanel.add(branchLabel, gbc);
gbc.gridx = 1;
branchField = new JTextField(20);
branchField.setFont(new Font("Serif", Font.PLAIN, 16));
inputPanel.add(branchField, gbc);
gbc.gridx = 0;
gbc.gridy = 4;
JLabel semesterLabel = new JLabel("Semester:");
semesterLabel.setFont(labelFont);
inputPanel.add(semesterLabel, gbc);
gbc.gridx = 1;
semesterField = new JTextField(20);
semesterField.setFont(new Font("Serif", Font.PLAIN, 16));
inputPanel.add(semesterField, gbc);
add(inputPanel, BorderLayout.WEST);
// Button Panel
JPanel buttonPanel = new JPanel(new GridLayout(4, 1, 10, 10)); // 4 rows, 1 column, 10px
horizontal and vertical gap
addButton = new JButton("Add");
deleteButton = new JButton("Delete");
updateButton = new JButton("Update");
displayButton = new JButton("Display");
addButton.setFont(buttonFont);
deleteButton.setFont(buttonFont);
updateButton.setFont(buttonFont);
displayButton.setFont(buttonFont);
// Display Area
displayArea = new JTextArea(10, 50);
displayArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
displayArea.setEditable(false);
add(new JScrollPane(displayArea), BorderLayout.SOUTH);
// Add Action Listeners
addButton.addActionListener(this);
deleteButton.addActionListener(this);
updateButton.addActionListener(this);
displayButton.addActionListener(this);
@Override
public void actionPerformed(ActionEvent e) {
try {
if (e.getSource() == addButton) {
String query = "INSERT INTO Student (registration_no, name, rollno, branch, semester)
VALUES (?, ?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, Integer.parseInt(regnField.getText()));
ps.setString(2, nameField.getText());
ps.setString(3, rollnoField.getText());
ps.setString(4, branchField.getText());
ps.setInt(5, Integer.parseInt(semesterField.getText()));
ps.executeUpdate();
JOptionPane.showMessageDialog(this, "Student Added Successfully!");
} else if (e.getSource() == deleteButton) {
String query = "DELETE FROM Student WHERE registration_no = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, Integer.parseInt(regnField.getText()));
ps.executeUpdate();
JOptionPane.showMessageDialog(this, "Student Deleted Successfully!");
} else if (e.getSource() == updateButton) {
String query = "UPDATE Student SET name = ?, rollno = ?, branch = ?, semester = ?
WHERE registration_no = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, nameField.getText());
ps.setString(2, rollnoField.getText());
ps.setString(3, branchField.getText());
ps.setInt(4, Integer.parseInt(semesterField.getText()));
ps.setInt(5, Integer.parseInt(regnField.getText()));
ps.executeUpdate();
JOptionPane.showMessageDialog(this, "Student Updated Successfully!");
} else if (e.getSource() == displayButton) {
String query = "SELECT * FROM Student";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
displayArea.setText("---------------------------------------------------\n");
displayArea.append("Registration No : Name : Roll No : Branch : Semester\n");
displayArea.append("---------------------------------------------------\n");
while (rs.next()) {
displayArea.append(
"Regn No: " + rs.getInt("registration_no") + "\n" +
"Name: " + rs.getString("name") + "\n" +
"Roll No: " + rs.getString("rollno") + "\n" +
"Branch: " + rs.getString("branch") + "\n" +
"Semester: " + rs.getInt("semester") + "\n" +
"---------------------------------------------------\n"
);
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}
OUTPUT