Advance Java Lab
Advance Java Lab
frame.add(label);
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
OUTPUT:
CONCLUSION:
This program successfully creates a simple GUI window using Java Swing and displays
the text "Hello World" in the center. It introduces the fundamental structure of GUI
applications in Java using JFrame and JLabel.
Experiment No: 2
frame.add(label1);
frame.add(field1);
frame.add(label2);
frame.add(field2);
frame.add(addButton);
frame.add(resultLabel);
frame.setSize(400, 250);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int num1 = Integer.parseInt(field1.getText());
int num2 = Integer.parseInt(field2.getText());
int sum = num1 + num2;
resultLabel.setText("Result: " + sum);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid numbers.");
}
}
});
}
}
OUTPUT:
CONCLUSION:
This program demonstrates how to use Swing components and event handling in Java. It
takes two numerical inputs, processes them on a button click, and displays the sum. This
builds foundational understanding of interactive desktop GUI applications.
Experiment No. 3
// BorderLayout Example
JFrame borderFrame = new JFrame("BorderLayout");
borderFrame.setLayout(new BorderLayout());
borderFrame.add(new JButton("North"), BorderLayout.NORTH);
borderFrame.add(new JButton("South"), BorderLayout.SOUTH);
borderFrame.add(new JButton("East"), BorderLayout.EAST);
borderFrame.add(new JButton("West"), BorderLayout.WEST);
borderFrame.add(new JButton("Center"), BorderLayout.CENTER);
borderFrame.setSize(300, 200);
borderFrame.setVisible(true);
// GridLayout Example
JFrame gridFrame = new JFrame("GridLayout");
gridFrame.setLayout(new GridLayout(2, 3)); // 2 rows, 3 columns
for (int i = 1; i <= 5; i++) {
gridFrame.add(new JButton("Button " + i));
}
gridFrame.setSize(300, 150);
gridFrame.setVisible(true);
}
}
OUTPUT:
CONCLUSION:
This program illustrates the usage of three core layout managers in Java Swing.
Understanding these layouts is crucial for designing structured and user-friendly GUI
interfaces. Each layout serves a specific use case and offers different control over
component arrangement.
Experiment No. 4
frame.add(nameLabel); frame.add(nameField);
frame.add(emailLabel); frame.add(emailField);
frame.add(phoneLabel); frame.add(phoneField);
frame.add(addressLabel); frame.add(addressField);
frame.add(genderLabel); frame.add(genderPanel);
frame.add(provinceLabel); frame.add(provinceBox);
frame.add(aboutLabel); frame.add(aboutScroll);
frame.add(new JLabel()); frame.add(submitButton);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
OUTPUT:
CONCLUSION:
This program creates a structured and interactive student record form using GridLayout.
It introduces multiple Swing components and demonstrates how to effectively align them
in a uniform grid-based layout. This form will be used in the next step for database
operations.
Experiment No. 5
PROGRAM
import java.awt.*;
import java.sql.*;
import javax.swing.*;
String[] provinces = {
"Province 1", "Province 2", "Bagmati", "Gandaki",
"Lumbini", "Karnali", "Sudurpashchim"
};
JComboBox<String> provinceBox = new JComboBox<>(provinces);
frame.setSize(450, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
submitButton.addActionListener(e -> {
String name = nameField.getText();
String email = emailField.getText();
String phone = phoneField.getText();
String address = addressField.getText();
String gender = male.isSelected() ? "Male" : (female.isSelected() ?
"Female" : "");
String province = (String) provinceBox.getSelectedItem();
String about = aboutArea.getText();
if (name.isEmpty() || email.isEmpty()) {
JOptionPane.showMessageDialog(frame, "Name and Email are required
fields.");
return;
}
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/pncbca", "root", "bimal123"
);
String sql = "INSERT INTO student (name, email, phone, address, gender,
province, about) VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, name);
pst.setString(2, email);
pst.setString(3, phone);
pst.setString(4, address);
pst.setString(5, gender);
pst.setString(6, province);
pst.setString(7, about);
pst.executeUpdate();
OUTPUT:
CONCLUSION:
This program successfully connects a Java Swing form to a MySQL database using
JDBC. It stores student information into the student table of the PNCBCA database,
demonstrating real-world data entry and persistence techniques.
Experiment No. 6
PROGRAM
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
Connection conn;
public StudentCRUDApp() {
setTitle("Student Management (CRUD)");
setLayout(new BorderLayout(10, 10));
setSize(900, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(formPanel, BorderLayout.WEST);
buttonPanel.add(addBtn);
buttonPanel.add(updateBtn);
buttonPanel.add(deleteBtn);
buttonPanel.add(refreshBtn);
add(buttonPanel, BorderLayout.SOUTH);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int row = table.getSelectedRow();
if (row >= 0) {
nameField.setText(model.getValueAt(row, 1).toString());
emailField.setText(model.getValueAt(row, 2).toString());
phoneField.setText(model.getValueAt(row, 3).toString());
addressField.setText(model.getValueAt(row, 4).toString());
String gender = model.getValueAt(row, 5).toString();
maleBtn.setSelected(gender.equals("Male"));
femaleBtn.setSelected(gender.equals("Female"));
provinceBox.setSelectedItem(model.getValueAt(row, 6).toString());
aboutArea.setText(model.getValueAt(row, 7).toString());
}
}
});
connectDB();
loadTable();
}
void connectDB() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/pncbca",
"root", "bimal123");
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "DB Error: " + ex.getMessage());
}
}
void loadTable() {
try {
model.setRowCount(0);
PreparedStatement ps = conn.prepareStatement("SELECT * FROM
student");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
model.addRow(new Object[] {
rs.getInt("id"), rs.getString("name"), rs.getString("email"),
rs.getString("phone"), rs.getString("address"), rs.getString("gender"),
rs.getString("province"), rs.getString("about")
});
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Load Error: " + e.getMessage());
}
}
void insertRecord() {
try {
String gender = maleBtn.isSelected() ? "Male" : "Female";
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO student(name, email, phone, address, gender, province,
about) VALUES (?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, nameField.getText());
ps.setString(2, emailField.getText());
ps.setString(3, phoneField.getText());
ps.setString(4, addressField.getText());
ps.setString(5, gender);
ps.setString(6, (String) provinceBox.getSelectedItem());
ps.setString(7, aboutArea.getText());
ps.executeUpdate();
loadTable();
clearForm();
JOptionPane.showMessageDialog(this, "Record added.");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Insert Error: " + e.getMessage());
}
}
void updateRecord() {
int row = table.getSelectedRow();
if (row < 0) {
JOptionPane.showMessageDialog(this, "Select a row to update.");
return;
}
try {
String gender = maleBtn.isSelected() ? "Male" : "Female";
int id = (int) model.getValueAt(row, 0);
PreparedStatement ps = conn.prepareStatement(
"UPDATE student SET name=?, email=?, phone=?, address=?,
gender=?, province=?, about=? WHERE id=?");
ps.setString(1, nameField.getText());
ps.setString(2, emailField.getText());
ps.setString(3, phoneField.getText());
ps.setString(4, addressField.getText());
ps.setString(5, gender);
ps.setString(6, (String) provinceBox.getSelectedItem());
ps.setString(7, aboutArea.getText());
ps.setInt(8, id);
ps.executeUpdate();
loadTable();
clearForm();
JOptionPane.showMessageDialog(this, "Record updated.");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Update Error: " + e.getMessage());
}
}
void deleteRecord() {
int row = table.getSelectedRow();
if (row < 0) {
JOptionPane.showMessageDialog(this, "Select a row to delete.");
return;
}
try {
int id = (int) model.getValueAt(row, 0);
PreparedStatement ps = conn.prepareStatement("DELETE FROM student
WHERE id=?");
ps.setInt(1, id);
ps.executeUpdate();
loadTable();
clearForm();
JOptionPane.showMessageDialog(this, "Record deleted.");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Delete Error: " + e.getMessage());
}
}
void clearForm() {
nameField.setText("");
emailField.setText("");
phoneField.setText("");
addressField.setText("");
maleBtn.setSelected(true);
provinceBox.setSelectedIndex(0);
aboutArea.setText("");
}
Update
Delete
Read
CONCLUSION:
In this program, we successfully developed a complete window-based CRUD (Create,
Read, Update, Delete) application using Java Swing and MySQL. The application enables
users to manage student records efficiently through a graphical user interface.
Experiment No. 7
PROGRAM
StudentBean.java
import java.io.Serializable;
public StudentBean() {
// No-argument constructor
}
BeanTest.java
public class BeanTest {
public static void main(String[] args) {
StudentBean student = new StudentBean();
student.setName("Bimal Bhandari");
student.setEmail("[email protected]");
student.setAge(22);
System.out.println("Student Details:");
System.out.println("Name : " + student.getName());
System.out.println("Email : " + student.getEmail());
System.out.println("Age : " + student.getAge());
}
}
OUTPUT:
CONCLUSION:
This program demonstrated the creation and use of a JavaBean class. The StudentBean
class follows all JavaBean conventions, such as providing private fields, public
getter/setter methods, and a no-argument constructor. The BeanTest class shows how to
use the bean by setting and retrieving its properties. This example reinforces the concept
of encapsulation and reusability in Java programming, essential for scalable and modular
application design.
Experiment No. 8
Web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT
Conclusion
In this program, I created a basic servlet called HelloServlet that displays "Hello World"
on the browser. I used the HttpServlet class and wrote the output inside the doGet()
method. I also made the required folder structure inside the webapps directory of Tomcat
and placed my compiled class file inside WEB-INF/classes. After setting up the servlet
and writing the web.xml file for mapping, I ran Tomcat and accessed the servlet using
localhost:8080. It worked successfully and displayed the output. Through this program, I
understood how servlets work, how to configure them using web.xml, and how to deploy
them on Apache Tomcat.
Experiment No. 9
PROGRAM
AddServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try {
int a = Integer.parseInt(req.getParameter("num1"));
int b = Integer.parseInt(req.getParameter("num2"));
int sum = a + b;
Web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<servlet>
<servlet-name>Add</servlet-name>
<servlet-class>AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Add</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
CONCLUSION:
In this program, I created a servlet called AddServlet to perform the addition of two
numbers entered through an HTML form. I took the input using getParameter(), parsed
them to integers, and displayed the result using PrintWriter. I also made a web.xml file
for mapping the servlet and used Tomcat to deploy and test it. The output showed the sum
correctly on the browser. This helped me understand how to take user input from an
HTML form and process it using a servlet.
Experiment No. 10
PROGRAM
Index.jsp
<!DOCTYPE html>
<html>
<head>
<title>Add Two Numbers in JSP</title>
</head><body>
<h2>Enter Two Numbers</h2>
<form action="result.jsp" method="get">
Number 1: <input type="text" name="num1"><br><br>
Number 2: <input type="text" name="num2"><br><br>
<input type="submit" value="Add">
</form></body></html>
Result.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Result</title>
</head>
<body>
<% try {
int a = Integer.parseInt(request.getParameter("num1"));
int b = Integer.parseInt(request.getParameter("num2"));
int sum = a + b;
%>
<h2>Sum = <%= sum %></h2>
<%
} catch (Exception e) {
%>
<h2>Error: Please enter valid numbers.</h2>
<% }%>
</body>
</html>
OUTPUT:
CONCLUSION:
In this program, I created a simple JSP application to perform the addition of two
numbers. I used one JSP page for input and another for processing and displaying the
result. I used request.getParameter() to get the values and calculated the sum using
embedded Java. This program helped me understand how JSP works and how it separates
Java logic from HTML layout, making it easier to build dynamic web pages.
Experiment No. 11
Validate.jsp
<%@ page session="true" %>
<%
String uname = request.getParameter("username");
String pwd = request.getParameter("password");
Welcome.jsp
<%@ page session="true" %>
<%
String user = (String) session.getAttribute("user");
if(user == null) {
response.sendRedirect("login.jsp");
}
%>
Welcome Page and Logout button which redirects to login page again after ending the
session
Conclusion
In this program, I created a login system using JSP with session handling. The user inputs
username and password in login.jsp, which is validated in validate.jsp. If correct, a
session is created and the user is redirected to welcome.jsp, where their session is
checked. A logout option was also added that invalidates the session. This helped me
understand JSP sessions and basic authentication flow using server-side logic.
Experiment No. 12
Db.jsp
<%@ page import="java.sql.*" %>
<%
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/pncbca",
"root", "bimal123");
} catch(Exception e) {
out.println("DB Connection Error: " + e.getMessage());
}
%>
Delete.jsp
<%@ include file="db.jsp" %>
<%
String id = request.getParameter("id");
PreparedStatement ps = conn.prepareStatement("DELETE FROM student WHERE
id=?");
ps.setInt(1, Integer.parseInt(id));
ps.executeUpdate();
conn.close();
response.sendRedirect("index.jsp");
%>
Edit.jsp
<%@ include file="db.jsp" %>
<%
String id = request.getParameter("id");
PreparedStatement ps = conn.prepareStatement("SELECT * FROM student WHERE
id=?");
ps.setInt(1, Integer.parseInt(id));
ResultSet rs = ps.executeQuery();
rs.next();
%>
<h2>Edit Student</h2>
<form action="update.jsp" method="post">
<input type="hidden" name="id" value="<%= id %>">
Name: <input type="text" name="name" value="<%= rs.getString("name")
%>"><br>
Email: <input type="text" name="email" value="<%= rs.getString("email")
%>"><br>
Phone: <input type="text" name="phone" value="<%= rs.getString("phone")
%>"><br>
Address: <input type="text" name="address" value="<%= rs.getString("address")
%>"><br>
Gender: <input type="text" name="gender" value="<%= rs.getString("gender")
%>"><br>
Province: <input type="text" name="province" value="<%=
rs.getString("province") %>"><br>
About: <textarea name="about"><%= rs.getString("about") %></textarea><br>
<input type="submit" value="Update">
</form>
<%
conn.close();
%>
Index.jsp
<%@ include file="db.jsp" %>
<%
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
%>
<h2>Student List</h2>
<a href="add.jsp">Add New Student</a>
<table border="1" cellpadding="5">
<tr>
<th>ID</th><th>Name</th><th>Email</th><th>Phone</th><th>Actions</th>
</tr>
<%
while(rs.next()) {
%>
<tr>
<td><%= rs.getInt("id") %></td>
<td><%= rs.getString("name") %></td>
<td><%= rs.getString("email") %></td>
<td><%= rs.getString("phone") %></td>
<td>
<a href="edit.jsp?id=<%=rs.getInt("id")%>">Edit</a> |
<a href="delete.jsp?id=<%=rs.getInt("id")%>">Delete</a>
</td>
</tr>
<% } %>
</table>
<%
conn.close();
%>
Insert.jsp
<%@ include file="db.jsp" %>
<%
PreparedStatement ps = conn.prepareStatement("INSERT INTO
student(name,email,phone,address,gender,province,about) VALUES (?,?,?,?,?,?,?)");
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("email"));
ps.setString(3, request.getParameter("phone"));
ps.setString(4, request.getParameter("address"));
ps.setString(5, request.getParameter("gender"));
ps.setString(6, request.getParameter("province"));
ps.setString(7, request.getParameter("about"));
ps.executeUpdate();
conn.close();
response.sendRedirect("index.jsp");
%>
Update.jsp
<%@ include file="db.jsp" %>
<%
PreparedStatement ps = conn.prepareStatement("UPDATE student SET
name=?,email=?,phone=?,address=?,gender=?,province=?,about=? WHERE
id=?");
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("email"));
ps.setString(3, request.getParameter("phone"));
ps.setString(4, request.getParameter("address"));
ps.setString(5, request.getParameter("gender"));
ps.setString(6, request.getParameter("province"));
ps.setString(7, request.getParameter("about"));
ps.setInt(8, Integer.parseInt(request.getParameter("id")));
ps.executeUpdate();
conn.close();
response.sendRedirect("index.jsp");
%>
OUTPUT
Index.jsp
Add.jsp
Edit.jsp
Final index.jsp after deleting second row of student named TreVor
CONCLUSION
In this program, I created a full student management system using JSP and MySQL. I
made pages to add, view, update, and delete student records. I used JSP forms and
connected them with MySQL using JDBC. All operations worked using queries and
redirections. Through this project, I understood how to build a full CRUD app and how
JSP interacts with databases in a real web application.
Experiment No. 13
ChatInterface.java
import java.rmi.*;
CONCLUSION
In this program, I implemented a simple RMI-based communication system where the
client sends a message to the server. I created a remote interface, then implemented it on
the server and invoked the method from the client. This helped me understand how
distributed systems work using RMI, and how a client can access server-side methods
remotely.