JAVAlab
JAVAlab
1. Write a GUI application to find sum and difference of two integer numbers. Use two text fields for input
and third text field for output. Your program should display sum if the user presses the mouse and
difference if the user releases the mouse........................................................................................................ 3
2.Design and develop the below registration form and when the user press on the submit button then
fetch the value of elements from the left side and display the results in the right side of JTextArea. ............ 5
3.Write Java Code to display a window with a label and three buttons as shown in the figure. When the
user clicks a button, it should change the background color of the panel that contains the components and
the foreground color of the label. .................................................................................................................... 7
4. Write a Java code and display the window with a JLabel, JButton and JTexField as shown in figure below.
When a user clicks on a button, it should convert the value of Celsius to Fahrenheit and display the result
in text Field....................................................................................................................................................... 9
6.Write a Java code and display the window with textField and register the text field with a KeyListner.
Handle the following key events. a.When user type b in the text field changes the background color of the
window. b.When a user presses any key, display the name of the key in the window. ................................. 10
7.Write a program to prepare one small form containing fields employee id, name, and salary with buttons
view, insert, and delete. And perform the operations as indicated by button names. ................................. 12
8.Write a JDBC program to insert multiple records into a Books table using PreparedStatement. The table
should include the columns: BookID, Title, Author, Price, and Genre. .......................................................... 14
9.Write a JDBC program to update the Salary of employees in the Employees table by 10% if their current
salary is below 30000. .................................................................................................................................... 15
10.Develop a small form using Java Swing connected to JDBC where the user can: i. View a student's full
profile using the RollNo. ii. Update the student’s Major and Division. iii. Add a new student to the Students
table. .............................................................................................................................................................. 16
11. Write a JavaBean program that finds square and cube value in terms of properties. ............................. 20
12.Write a JavaBean program and modify the district name using JavaBean Bound property. .................... 21
13.Write a JavaBean program for students of Texas International college, if the student has scored more
than 40 in Advanced JavaProgramming then set the student as passed otherwise fail. Use JavaBean
Constrained. ................................................................................................................................................... 22
14. Write a JavaBean program and check if odd or even number and save then retrieve the state of the
bean using JavaBean persistence. .................................................................................................................. 23
15.Create a servlet that computes and displays factorial of an input number entered from a page when the
button from that page is pressed by the user. ............................................................................................... 25
16.Create a JSP page that contains three textboxes to input three numbers and a button. It should display
the greatest and smallest number among three numbers when the button is clicked. ................................ 26
17.Create JSP web from to take inputs: name, password, gender, email and phone number and submit it to
servlet file which may simply print the values of from submission. .............................................................. 28
18.Write a client/server application using RMI to find sum and difference of two numbers. ....................... 31
19.Write a client-server application in RMI to find the selling price of an item with cost price Rs. 5000 after
a discount of Rs.50. ........................................................................................................................................ 33
20.Create a RMI application such that a client sends an integer number to the server and the server return
the factorial value of that integer................................................................................................................... 34
21.Create a RMI application such that a client sends an String to the server and the server return the
reverse of that String. .................................................................................................................................... 36
22.Write a client/server application using RMI to find division between two numbers and also the
remainder. ...................................................................................................................................................... 38
1. Write a GUI application to find sum and difference of two integer
numbers. Use two text fields for input and third text field for output.
Your program should display sum if the user presses the mouse and
difference if the user releases the mouse.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public SumDifferenceCalculator()
setTitle("Sum and Difference Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLayout(new GridLayout(4, 2, 10, 10));
add(label1);
add(inputField1);
add(label2);
add(inputField2);
add(outputLabel);
add(outputField);
outputField.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
calculateSum();
}
@Override
public void mouseReleased(MouseEvent e) {
calculateDifference();
}
});
public RegistrationForm() {
setTitle("Registration Form");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 500);
setLayout(new GridLayout(1, 2, 10, 10));
JPanel inputPanel = new JPanel(new GridLayout(8, 1, 10, 10));
inputPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
inputPanel.add(new JLabel("Name:"));
nameField = new JTextField();
inputPanel.add(nameField);
inputPanel.add(new JLabel("Mobile:"));
mobileField = new JTextField();
inputPanel.add(mobileField)
inputPanel.add(new JLabel("Gender:"));
JPanel genderPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
maleRadio = new JRadioButton("Male", true);
femaleRadio = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(maleRadio);
genderGroup.add(femaleRadio);
genderPanel.add(maleRadio);
genderPanel.add(femaleRadio);
inputPanel.add(genderPanel);
inputPanel.add(new JLabel("Date of Birth:"));
dobSpinner = new JSpinner(new SpinnerDateModel());
JSpinner.DateEditor dobEditor = new JSpinner.DateEditor(dobSpinner, "dd/MM/yyyy");
dobSpinner.setEditor(dobEditor);
inputPanel.add(dobSpinner)
inputPanel.add(new JLabel("Address:"));
addressArea = new JTextArea(3, 20);
addressArea.setLineWrap(true);
JScrollPane addressScroll = new JScrollPane(addressArea);
inputPanel.add(addressScroll);
termsCheck = new JCheckBox("Accept Terms And Conditions");
inputPanel.add(termsCheck);
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
JButton submitButton = new JButton("Submit");
JButton resetButton = new JButton("Reset");
buttonPanel.add(submitButton);
buttonPanel.add(resetButton);
inputPanel.add(buttonPanel);
JPanel resultPanel = new JPanel(new BorderLayout());
resultPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
resultPanel.add(new JLabel("Registration Details:"), BorderLayout.NORTH);
resultArea = new JTextArea();
resultArea.setEditable(false);
JScrollPane resultScroll = new JScrollPane(resultArea);
resultPanel.add(resultScroll, BorderLayout.CENTER);
add(inputPanel);
add(resultPanel);
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!termsCheck.isSelected()) {
JOptionPane.showMessageDialog(RegistrationForm.this,
"Please accept the terms and conditions",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
String name = nameField.getText();
String mobile = mobileField.getText();
String gender = maleRadio.isSelected() ? "Male" : "Female";
Date dob = (Date) dobSpinner.getValue();
String address = addressArea.getText();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String dobStr = dateFormat.format(dob);
String result = "Name: " + name + "\n" +
"Mobile: " + mobile + "\n" +
"Gender: " + gender + "\n" +
"Date of Birth: " + dobStr + "\n" +
"Address: " + address + "\n\n" +
"Terms Accepted: Yes";
resultArea.setText(result);
}
});
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
nameField.setText("");
mobileField.setText("");
maleRadio.setSelected(true);
dobSpinner.setValue(new Date());
addressArea.setText("");
termsCheck.setSelected(false);
resultArea.setText("");
}
});
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
RegistrationForm form = new RegistrationForm();
form.setVisible(true);
});
}
}
3.Write Java Code to display a window with a label and three buttons as
shown in the figure. When the user clicks a button, it should change the
background color of the panel that contains the components and the
foreground color of the label.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
mainPanel.add(buttonPanel, BorderLayout.CENTER);
setLocationRelativeTo(null);
}
private JButton createColorButton(String text, Color bgColor, Color fgColor) {
JButton button = new JButton(text);
button.addActionListener(e -> {
mainPanel.setBackground(bgColor);
label.setForeground(fgColor);
});
return button;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
ColorChanger frame = new ColorChanger();
frame.setVisible(true);
});
}
}
4. Write a Java code and display the window with a JLabel, JButton and
JTexField as shown in figure below. When a user clicks on a button, it
should convert the value of Celsius to Fahrenheit and display the result in
text Field.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public TemperatureConverter() {
setTitle("Celsius to Fahrenheit Converter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
setLayout(new GridLayout(3, 2, 10, 10));
add(new JLabel("Celsius:"));
celsiusField = new JTextField("0");
add(celsiusField);
add(new JLabel("Fahrenheit:"));
fahrenheitField = new JTextField("32.0 F");
fahrenheitField.setEditable(false);
add(fahrenheitField);
JButton convertButton = new JButton("Convert");
add(convertButton);
add(new JLabel()); // Empty cell for layout
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
double celsius = Double.parseDouble(celsiusField.getText());
double fahrenheit = (celsius * 9/5) + 32;
fahrenheitField.setText(String.format("%.1f F", fahrenheit));
} catch (NumberFormatException ex) {
fahrenheitField.setText("Invalid input");
}
}
});
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TemperatureConverter frame = new TemperatureConverter();
frame.setVisible(true);
});
}
}
5. Write a Java code and display the window with registering mouse listeners. Handle the following mouse
event: a.When the user pressed the mouse, change the background color of the window to Red Color.
b.When the mouse enters the window, change the background color of the window to Green Color. c.When
the mouse exited from the window, change the background color of the window to Yellow Color. d.When the
user releases the mouse, change the background color of the window to Gray color.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseEventDemo extends JFrame implements MouseListener {
public MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(Color.WHITE);
addMouseListener(this);
setVisible(true);
}
public void mousePressed(MouseEvent e) {
getContentPane().setBackground(Color.RED);
}
public void mouseReleased(MouseEvent e) {
getContentPane().setBackground(Color.GRAY);
}
public void mouseEntered(MouseEvent e) {
getContentPane().setBackground(Color.GREEN);
}
public void mouseExited(MouseEvent e) {
getContentPane().setBackground(Color.YELLOW);
}
public void mouseClicked(MouseEvent e) {}
public static void main(String[] args) {
new MouseEventDemo();
}
}
6.Write a Java code and display the window with textField and register
the text field with a KeyListner. Handle the following key events. a.When
user type b in the text field changes the background color of the window.
b.When a user presses any key, display the name of the key in the
window.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
package com.Lab;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class EmployeeForm extends JFrame implements ActionListener {
JTextField txtId, txtName, txtSalary;
JButton btnInsert, btnView, btnDelete;
Connection con;
PreparedStatement pst;
ResultSet rs;
public EmployeeForm() {
setTitle("Employee Form");
setSize(400, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2));
add(new JLabel("Employee ID:"));
txtId = new JTextField();
add(txtId);
add(new JLabel("Name:"));
txtName = new JTextField();
add(txtName)
add(new JLabel("Salary:"));
txtSalary = new JTextField();
add(txtSalary);
btnInsert = new JButton("Insert");
btnInsert.addActionListener(this);
add(btnInsert);
btnView = new JButton("View");
btnView.addActionListener(this);
add(btnView);
btnDelete = new JButton("Delete");
btnDelete.addActionListener(this);
add(btnDelete);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Company", "root", "shiva");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "DB Connection Failed: " + e);
}
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
int id = Integer.parseInt(txtId.getText());
if (e.getSource() == btnInsert) {
String name = txtName.getText();
double salary = Double.parseDouble(txtSalary.getText());
pst = con.prepareStatement("INSERT INTO Employee VALUES(?, ?, ?)");
pst.setInt(1, id);
pst.setString(2, name);
pst.setDouble(3, salary);
pst.executeUpdate();
JOptionPane.showMessageDialog(this, "Inserted Successfully");
} else if (e.getSource() == btnView) {
pst = con.prepareStatement("SELECT * FROM Employee WHERE EmpID = ?");
pst.setInt(1, id);
rs = pst.executeQuery();
if (rs.next()) {
txtName.setText(rs.getString("Name"));
txtSalary.setText(String.valueOf(rs.getDouble("Salary")));
} else {
JOptionPane.showMessageDialog(this, "No record found");
}
} else if (e.getSource() == btnDelete) {
pst = con.prepareStatement("DELETE FROM Employee WHERE EmpID = ?");
pst.setInt(1, id);
int i = pst.executeUpdate();
if (i > 0) {
JOptionPane.showMessageDialog(this, "Deleted Successfully");
txtName.setText("");
txtSalary.setText("");
} else {
JOptionPane.showMessageDialog(this, "No record to delete");
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex);
}
}
public static void main(String[] args) {
new EmployeeForm();
}
}
8.Write a JDBC program to insert multiple records into a Books table
using PreparedStatement. The table should include the columns: BookID,
Title, Author, Price, and Genre.
package com.Shiva;
import java.sql.*;
String query = "INSERT INTO Books (BookID, Title, Author, Price, Genre) VALUES (?, ?, ?, ?, ?)";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement pst = con.prepareStatement(query);
pst.setInt(1, 104);
pst.setString(2, "Atomic Habits");
pst.setString(3, "James Clear");
pst.setDouble(4, 499.99);
pst.setString(5, "Self-Help");
pst.executeUpdate();
pst.setInt(1, 105);
pst.setString(2, "The Alchemist");
pst.setString(3, "Paulo Coelho");
pst.setDouble(4, 299.00);
pst.setString(5, "Fiction");
pst.executeUpdate();
pst.setInt(1, 106);
pst.setString(2, "Clean Code");
pst.setString(3, "Robert C. Martin");
pst.setDouble(4, 650.00);
pst.setString(5, "Programming");
pst.executeUpdate();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
pstmt = conn.prepareStatement(updateQuery);
int rowsUpdated = pstmt.executeUpdate();
System.out.println("Number of employees updated: " + rowsUpdated);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
10.Develop a small form using Java Swing connected to JDBC where the
user can: i. View a student's full profile using the RollNo. ii. Update the
student’s Major and Division. iii. Add a new student to the Students
table.
package com.Shiva;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.io.Serializable;
public class SquareCubeBean implements Serializable {
private int number;
private int square;
private int cube;
public SquareCubeBean() {
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
calculateSquareAndCube();
}
public int getSquare() {
return square;
}
public int getCube() {
return cube;
}
private void calculateSquareAndCube() {
this.square = number * number;
this.cube = number * number * number;
}
}
12.Write a JavaBean program and modify the district name using
JavaBean Bound property.
DistrictBean.java
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
public class DistrictBean implements Serializable {
private String districtName;
private PropertyChangeSupport support;
public DistrictBean() {
support = new PropertyChangeSupport(this);
}
public String getDistrictName() {
return districtName;
}
public void setDistrictName(String districtName) {
String oldName = this.districtName;
this.districtName = districtName;
support.firePropertyChange("districtName", oldName, districtName);
}
public void addPropertyChangeListener(PropertyChangeListener pcl) {
support.addPropertyChangeListener(pcl);
}
public void removePropertyChangeListener(PropertyChangeListener pcl) {
support.removePropertyChangeListener(pcl);
}
}
TestDistrictBean.java
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class TestDistrictBean {
public static void main(String[] args) {
DistrictBean bean = new DistrictBean();
bean.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("District name changed from " + evt.getOldValue() + " to " + evt.getNewValue());
}
});
bean.setDistrictName("Kathmandu");
bean.setDistrictName("Lalitpur");
}
}
13.Write a JavaBean program for students of Texas International college,
if the student has scored more than 40 in Advanced JavaProgramming
then set the student as passed otherwise fail. Use JavaBean Constrained.
import java.beans.*;
import java.io.Serializable;
import java.beans.PropertyVetoException;
public class TestStudentBean {
public static void main(String[] args) {
StudentBean student = new StudentBean();
student.addVetoableChangeListener(evt -> {
// Accept all changes, but you could throw PropertyVetoException to reject
System.out.println("Result changing from " + evt.getOldValue() + " to " + evt.getNewValue());
});
try {
student.setAdvancedJavaScore(45);
System.out.println("Score: " + student.getAdvancedJavaScore() + ", Result: " + student.getResult());
student.setAdvancedJavaScore(35);
System.out.println("Score: " + student.getAdvancedJavaScore() + ", Result: " + student.getResult());
} catch (PropertyVetoException e) {
System.out.println("Change rejected: " + e.getMessage());
}
}
}
14. Write a JavaBean program and check if odd or even number and save
then retrieve the state of the bean using JavaBean persistence.
NumberBean.java
import java.io.*;
} catch (Exception e) {
e.printStackTrace();
}
}
}
15.Create a servlet that computes and displays factorial of an input
number entered from a page when the button from that page is pressed
by the user.
FactorialApplication.java
package com.example;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet("/factorial")
public class FactorialServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int number = Integer.parseInt(request.getParameter("number"));
long fact = 1;
for (int i = 1; i <= number; i++) {
fact *= i;
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Factorial of " + number + " is: " + fact + "</h2>");
out.println("</body></html>");
}
}
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Factorial Calculator</title>
</head>
<body>
<h2>Enter a number:</h2>
<form action="factorial" method="post">
<input type="number" name="number" required>
<input type="submit" value="Calculate">
</form>
</body>
</html>
<%
String n1 = request.getParameter("num1");
String n2 = request.getParameter("num2");
String n3 = request.getParameter("num3");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Form Submission Details:</h2>");
out.println("<p><strong>Name:</strong> " + name + "</p>");
out.println("<p><strong>Password:</strong> " + password + "</p>");
out.println("<p><strong>Gender:</strong> " + gender + "</p>");
out.println("<p><strong>Email:</strong> " + email + "</p>");
out.println("<p><strong>Phone:</strong> " + phone + "</p>");
out.println("</body></html>");
}
}
web.xml
<web-app>
<servlet>
<servlet-name>SubmitForm</servlet-name>
<servlet-class>SubmitForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SubmitForm</servlet-name>
<url-pattern>/SubmitForm</url-pattern>
</servlet-mapping>
</web-app>
18.Write a client/server application using RMI to find sum and difference
of two numbers.
Calc.java (Interface)
import java.rmi.*;
public interface Calc extends Remote {
int sum(int a, int b) throws RemoteException;
int diff(int a, int b) throws RemoteException;
}
CalcImpl.java
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class CalcImpl extends UnicastRemoteObject implements Calc {
public CalcImpl() throws RemoteException {
super();
}
public int sum(int a, int b) throws RemoteException {
return a + b;
}
public int diff(int a, int b) throws RemoteException {
return a - b;
}
}
Server.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
PriceCalc.java
import java.rmi.*;
Division.java
import java.rmi.Remote;
import java.rmi.RemoteException;