Advance Java
Advance Java
"Design and implement a Java Swing application for user registration and
shape drawing. Use various layout managers (BorderLayout, GridLayout),
event handling mechanisms, adapter classes, and basic Swing components.
The app should collect user input and allow drawing 2D shapes in different
colors."
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class ShapeDrawingApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new RegistrationFrame());
}
}
class RegistrationFrame extends JFrame {
JTextField nameField, emailField;
JPasswordField passField;
JRadioButton maleBtn, femaleBtn;
JButton registerBtn;
public RegistrationFrame() {
setTitle("User Registration");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel centerPanel = new JPanel(new GridLayout(5, 2, 5, 5));
centerPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
nameField = new JTextField();
emailField = new JTextField();
passField = new JPasswordField();
maleBtn = new JRadioButton("Male");
femaleBtn = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(maleBtn);
genderGroup.add(femaleBtn);
centerPanel.add(new JLabel("Name:"));
centerPanel.add(nameField);
centerPanel.add(new JLabel("Email:"));
centerPanel.add(emailField);
centerPanel.add(new JLabel("Password:"));
centerPanel.add(passField);
centerPanel.add(new JLabel("Gender:"));
JPanel genderPanel = new JPanel(new FlowLayout());
genderPanel.add(maleBtn);
genderPanel.add(femaleBtn);
centerPanel.add(genderPanel);
registerBtn = new JButton("Register");
add(centerPanel, BorderLayout.CENTER);
add(registerBtn, BorderLayout.SOUTH);
registerBtn.addActionListener(e -> {
if (nameField.getText().isEmpty() || emailField.getText().isEmpty() ||
passField.getPassword().length == 0
|| (!maleBtn.isSelected() && !femaleBtn.isSelected())) {
JOptionPane.showMessageDialog(this, "Please fill all fields.");
} else {
dispose();
new DrawingFrame();
}
});
setVisible(true);
}
}
class DrawingFrame extends JFrame {
private JComboBox<String> shapeBox, colorBox;
private DrawingPanel drawingPanel;
public DrawingFrame() {
setTitle("Shape Drawing Panel");
setSize(600, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
shapeBox = new JComboBox<>(new String[]{"Circle", "Rectangle"});
colorBox = new JComboBox<>(new String[]{"Red", "Green", "Blue", "Black"});
topPanel.add(new JLabel("Shape:"));
topPanel.add(shapeBox);
topPanel.add(new JLabel("Color:"));
topPanel.add(colorBox);
add(topPanel, BorderLayout.NORTH);
drawingPanel = new DrawingPanel(shapeBox, colorBox);
add(drawingPanel, BorderLayout.CENTER);
setVisible(true);
}
}
class DrawingPanel extends JPanel {
private final JComboBox<String> shapeBox, colorBox;
private final ArrayList<ShapeRecord> shapes = new ArrayList<>();
public DrawingPanel(JComboBox<String> shapeBox, JComboBox<String> colorBox) {
this.shapeBox = shapeBox;
this.colorBox = colorBox;
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
String shape = (String) shapeBox.getSelectedItem();
String colorName = (String) colorBox.getSelectedItem();
Color color;
switch (colorName) {
case "Red" -> color = Color.RED;
case "Green" -> color = Color.GREEN;
case "Blue" -> color = Color.BLUE;
default -> color = Color.BLACK;
}
shapes.add(new ShapeRecord(shape, e.getX(), e.getY(), color));
repaint();
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (ShapeRecord s : shapes) {
g.setColor(s.color);
switch (s.shape) {
case "Circle" -> g.fillOval(s.x - 25, s.y - 25, 50, 50);
case "Rectangle" -> g.fillRect(s.x - 30, s.y - 20, 60, 40);
}
}
}
static class ShapeRecord {
String shape;
int x, y;
Color color;
ShapeRecord(String shape, int x, int y, Color color) {
this.shape = shape;
this.x = x;
this.y = y;
this.color = color;
}
}
How It Works
● Starts with a Registration Form – User enters name, email, password, and gender.
● After Registration – Opens a Shape Drawing Window.
● User Picks Shape & Color – Circle or Rectangle; Red, Green, Blue, Black.
● Click on Canvas – Draws the selected shape at the clicked location.
Components & Features:
Component Purpose
Layouts Used:
● BorderLayout – Main layout of
windows
● GridLayout – Form fields
● FlowLayout – Gender options
OUTPUT:
2. "Develop a JavaBean for storing employee details (name, ID, salary,
department). Demonstrate the use of properties, getter/setter methods, bound
and constrained properties, and the use of BeanInfo interface. Also, create a
GUI application that uses this bean and allows users to set and retrieve the
properties."
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.Serializable;
public class EmployeeBeanApp {
public static class EmployeeBean implements Serializable {
private String name;
private int id;
private double salary;
private String department;
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private final VetoableChangeSupport vcs = new VetoableChangeSupport(this);
public EmployeeBean() {}
public String getName() {
return name;
}
public void setName(String name) {
String old = this.name;
this.name = name;
pcs.firePropertyChange("name", old, name);
}
public int getId() {
return id;
}
public void setId(int id) throws PropertyVetoException {
int old = this.id;
vcs.fireVetoableChange("id", old, id);
this.id = id;
pcs.firePropertyChange("id", old, id);
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
double old = this.salary;
this.salary = salary;
pcs.firePropertyChange("salary", old, salary);
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
String old = this.department;
this.department = department;
pcs.firePropertyChange("department", old, department);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
public void addVetoableChangeListener(VetoableChangeListener listener) {
vcs.addVetoableChangeListener(listener);
}
public void removeVetoableChangeListener(VetoableChangeListener listener) {
vcs.removeVetoableChangeListener(listener);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(EmployeeBeanApp::createAndShowGUI);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Employee Bean GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(450, 350);
EmployeeBean bean = new EmployeeBean();
bean.addPropertyChangeListener(evt ->
System.out.println("Property '" + evt.getPropertyName() + "' changed from " +
evt.getOldValue() + " to " + evt.getNewValue()));
try {
bean.addVetoableChangeListener(evt -> {
if ("id".equals(evt.getPropertyName()) && (int) evt.getNewValue() < 0) {
throw new PropertyVetoException("Negative ID not allowed", evt);
}
});
} catch (Exception e) {
e.printStackTrace();
}
JPanel panel = new JPanel(new GridLayout(6, 2, 5, 5));
JTextField nameField = new JTextField();
JTextField idField = new JTextField();
JTextField salaryField = new JTextField();
JTextField deptField = new JTextField();
JButton setBtn = new JButton("Set");
JButton getBtn = new JButton("Get");
JTextArea outputArea = new JTextArea(5, 30);
outputArea.setEditable(false);
panel.add(new JLabel("Name:"));
panel.add(nameField);
panel.add(new JLabel("ID:"));
panel.add(idField);
panel.add(new JLabel("Salary:"));
panel.add(salaryField);
panel.add(new JLabel("Department:"));
panel.add(deptField);
panel.add(setBtn);
panel.add(getBtn);
panel.add(new JLabel("Output:"));
panel.add(new JScrollPane(outputArea));
setBtn.addActionListener(e -> {
try {
bean.setName(nameField.getText());
bean.setId(Integer.parseInt(idField.getText()));
bean.setSalary(Double.parseDouble(salaryField.getText()));
bean.setDepartment(deptField.getText());
JOptionPane.showMessageDialog(frame, "Employee details set successfully!");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "Invalid number format", "Error",
JOptionPane.ERROR_MESSAGE);
} catch (PropertyVetoException ex) {
JOptionPane.showMessageDialog(frame, "Vetoed: " + ex.getMessage(), "Veto",
JOptionPane.WARNING_MESSAGE);
}
});
getBtn.addActionListener(e -> {
outputArea.setText("Employee Details:\n");
outputArea.append("Name: " + bean.getName() + "\n");
outputArea.append("ID: " + bean.getId() + "\n");
outputArea.append("Salary: " + bean.getSalary() + "\n");
outputArea.append("Department: " + bean.getDepartment() + "\n");
});
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
How the Code Works:
● EmployeeBean class is a JavaBean with 4 properties: name, id, salary, and department.
● It supports bound properties (notifies listeners when property changes) via
PropertyChangeSupport.
● It supports constrained properties (listeners can veto changes) via
VetoableChangeSupport — here used to prevent negative IDs.
● The GUI allows users to set these properties via text fields and buttons.
● Clicking Set updates the bean properties; invalid input or veto triggers error messages.
● Clicking Get shows current employee details in a non-editable text area.
● Property changes print messages to the console.
Swing Components & Their Properties:
Componen
Purpose Important Properties / Features
t
JPanel Holds form inputs and buttons Uses GridLayout(6, 2, 5, 5) for neat grid
JButton Buttons for setting and getting data Action listeners to handle clicks
i)Arithmetic.java code:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Arithmetic extends Remote {
double add(double a, double b) throws RemoteException;
double subtract(double a, double b) throws RemoteException;
double multiply(double a, double b) throws RemoteException;
double divide(double a, double b) throws RemoteException;
}
ii) ArithmeticImpl.java code:
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class ArithmeticImpl extends UnicastRemoteObject implements Arithmetic {
protected ArithmeticImpl() throws RemoteException {
super();
}
public double add(double a, double b) throws RemoteException {
return a + b;
}
public double subtract(double a, double b) throws RemoteException {
return a - b;
}
public double multiply(double a, double b) throws RemoteException {
return a * b;
}
public double divide(double a, double b) throws RemoteException {
if (b == 0) throw new ArithmeticException("Division by zero");
return a / b;
}
}
iii) ArithmeticServer.java code:
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class ArithmeticServer {
public static void main(String[] args) {
try {
ArithmeticImpl obj = new ArithmeticImpl();
Registry registry = LocateRegistry.createRegistry(1099); // default RMI registry port
registry.rebind("ArithmeticService", obj);
System.out.println("ArithmeticService bound and ready.");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client-side proxy for remote Marshals method calls and parameters; sends
Stub
object requests to server
@WebServlet("/submitFeedbackAlt")
public class FeedbackServletResponse extends HttpServlet {
private static final String DB_URL = "jdbc:mysql://localhost:3306/feedback_db";
private static final String DB_USER = "root";
private static final String DB_PASS = "yourpassword";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
String username = request.getParameter("username");
String comments = request.getParameter("comments");
try (Connection con = DriverManager.getConnection(DB_URL, DB_USER,
DB_PASS);
PreparedStatement ps = con.prepareStatement("INSERT INTO feedbacks(username,
comments) VALUES (?, ?)")) {
ps.setString(1, username);
ps.setString(2, comments);
ps.executeUpdate();
} catch (SQLException e) {
throw new ServletException("DB error", e);
}
@Override
public void init() throws ServletException {
super.init();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ServletException(e);
}
}
}
<servlet>
<servlet-name>FeedbackServlet</servlet-name>
<servlet-class>com.example.feedback.FeedbackServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FeedbackServlet</servlet-name>
<url-pattern>/submitFeedback</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>FeedbackServletResponse</servlet-name>
<servlet-class>com.example.feedback.FeedbackServletResponse</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>FeedbackServletResponse</servlet-name>
<url-pattern>/submitFeedbackAlt</url-pattern>
</servlet-mapping>
</web-app>
How It Works:
● User fills a feedback form (HTML).
● Servlet processes the form, saves feedback to the database, and stores feedback history in
the session.
● Servlet sets a cookie with the username for future visits.
● Servlet forwards the request to a JSP page that shows a thank you message and user’s
feedback history.
● Alternatively, the servlet can generate the entire HTML response itself (for comparison).
Database
Stores feedback permanently feedbacks table, SQL INSERT
(MySQL)
Remembers username
Cookie Stores username, max age set
client-side
5. "Create a Java application using JDBC to perform CRUD (Create, Read, Update,
Delete) operations on a student database. Use different JDBC driver types,
connect to a MySQL/PostgreSQL database, and demonstrate execution of SQL
queries using both Statement.
String insertQuery = "INSERT INTO student VALUES(" + id + ", '" + name + "',
" + age + ", '"
+ grade + "')";
stmt.executeUpdate(insertQuery);
System.out.println("Student added.");
break;
case 2:
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
System.out.println("ID | Name | Age | Grade");
while (rs.next()) {
System.out.println(rs.getInt("id") + " | " +
rs.getString("name") + " | " +
rs.getInt("age") + " | " +
rs.getString("grade"));
}
break;
case 3:
System.out.print("Enter ID to update: ");
int uid = sc.nextInt();
sc.nextLine();
System.out.print("Enter New Name: ");
String newName = sc.nextLine();
System.out.print("Enter New Age: ");
int newAge = sc.nextInt();
sc.nextLine();
System.out.print("Enter New Grade: ");
String newGrade = sc.nextLine();
case 4:
System.out.print("Enter ID to delete: ");
int did = sc.nextInt();
String deleteQuery = "DELETE FROM student WHERE id=" + did;
stmt.executeUpdate(deleteQuery);
System.out.println("Student deleted.");
break;
case 5:
System.out.println("Exiting...");
stmt.close();
conn.close();
return;
default:
System.out.println("Invalid choice.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
How the Code Works:
● Connects to MySQL database school using JDBC.
● Displays a menu to perform CRUD:
● Add, View, Update, Delete a student.
● Uses Statement to run SQL queries.
● Takes user input with Scanner.
● Handles all operations in a loop until the user exits.
Created with
Connection Connects to the database
DriverManager.getConnection()
Scanner Reads user input from console Reads int and String values
ResultSet Holds data returned from query Used to display student list
Class.forName
Loads MySQL JDBC driver Ensures the driver class is registered
()