0% found this document useful (0 votes)
21 views

Practical Exam

Uploaded by

Isha Narvekar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Practical Exam

Uploaded by

Isha Narvekar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

1.

Program using Border Layout (Chapter 1)


import javax.swing.*;
import java.awt.*;

public class BorderLayoutDemo


{
public static void main(String[] args) {
JFrame frame = new JFrame("Border Layout Example");
frame.setLayout(new BorderLayout());

frame.add(new JButton("North"), BorderLayout.NORTH);


frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.add(new JButton("East"), BorderLayout.EAST);
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JButton("Center"), BorderLayout.CENTER);

frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
2. JComboBox for Selecting States (Chapter 2)
import javax.swing.*;

public class StatesComboBox {


public static void main(String[] args) {
JFrame frame = new JFrame("Select State");
String[] states = {"Maharashtra", "Gujarat", "Rajasthan", "Punjab", "Kerala"};
JComboBox<String> comboBox = new JComboBox<>(states);

frame.add(comboBox);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
3. Program to demonstrate the use of Tree component in Swing (Chapter 2)
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

public class TreeComponentDemo


{
public static void main(String[] args) {
JFrame frame = new JFrame("JTree Example");

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");


DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Node 1");
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Node 2");

root.add(node1);
root.add(node2);
node1.add(new DefaultMutableTreeNode("Leaf 1"));
node2.add(new DefaultMutableTreeNode("Leaf 2"));

JTree tree = new JTree(root);


frame.add(new JScrollPane(tree));
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
4. Program to demonstrate the use of mouseDragged and mouseMoved (Chapter 3)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseMotionExample extends JFrame implements MouseMotionListener {


JLabel label;

public MouseMotionExample() {
label = new JLabel();
label.setBounds(20, 50, 200, 20);
add(label);
addMouseMotionListener(this);
setSize(400, 300);
setLayout(null);
setVisible(true);
}

public void mouseDragged(MouseEvent e) {


label.setText("Mouse Dragged at X:" + e.getX() + " Y:" + e.getY());
}

public void mouseMoved(MouseEvent e) {


label.setText("Mouse Moved at X:" + e.getX() + " Y:" + e.getY());
}

public static void main(String[] args) {


new MouseMotionExample();
}
}
5. Program using URL class to retrieve details (Chapter 4)
import java.net.*;

public class URLDetails {


public static void main(String[] args) {
try {
URL url = new URL("http://www.msbte.org.in");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
System.out.println("File: " + url.getFile());
} catch (Exception e) {
e.printStackTrace();
}
}
}
8. Application using List components to add names of 10 cities (Chapter 1)
import javax.swing.*;

public class CityListFrame {


public static void main(String[] args) {
JFrame frame = new JFrame("City List");
String[] cities = {"Mumbai", "Delhi", "Chennai", "Bangalore", "Pune", "Kolkata",
"Ahmedabad", "Jaipur", "Hyderabad", "Lucknow"};
JList<String> cityList = new JList<>(cities);

frame.add(new JScrollPane(cityList));
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
7. Write the output of following code considering below HTML is front end and servlet as back
end (Chapter 6)
<html>
<body>
<center>
<form name="Form1" method="post"
action="http://localhost:8080/examples/servlet/PostParametersServlet">
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>

import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements())
{
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}
6. Create a Student Table in database and insert a record (Chapter 5)
import java.sql.*;
public class SimpleStudentInsert {
public static void main(String[] args) {
// Database connection details
String url = "jdbc:mysql://localhost:3306/collegeDB";
String username = "root"; // Default username for XAMPP MySQL
String password = ""; // Default password is empty for XAMPP

try (Connection connection = DriverManager.getConnection(url, username, password)) {

// Step 1: Insert a new student record into the existing table


String insertQuery = "INSERT INTO student (name, roll_number, course, email) VALUES
('Apurva ', '36', 'Mathematics', '[email protected]')";
Statement statementInsert = connection.createStatement();
int rowsInserted = statementInsert.executeUpdate(insertQuery);
if (rowsInserted > 0) {
System.out.println("A student record has been inserted successfully.");
}

// Step 2: Retrieve all student records


String selectQuery = "SELECT * FROM student";
Statement statementSelect = connection.createStatement();
ResultSet resultSet = statementSelect.executeQuery(selectQuery);

System.out.println("\nStudent Records:");
while (resultSet.next()) {
int id = resultSet.getInt("student_id");
String name = resultSet.getString("name");
String rollNumber = resultSet.getString("roll_number");
String course = resultSet.getString("course");
String email = resultSet.getString("email");

System.out.println(id + ", " + name + ", " + rollNumber + ", " + course + ", " + email);
}

} catch (SQLException e) {
e.printStackTrace();
}
}
}
Code with form Design

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class StudentForm extends JFrame {


// Declare form components
private JTextField txtName, txtRollNumber, txtCourse, txtEmail;
private JButton btnSubmit, btnClear;

// Constructor to set up the form


public StudentForm() {
setTitle("Student Registration Form");
setSize(400, 300);
setLayout(new GridLayout(5, 2, 10, 10));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create form labels and text fields


JLabel lblName = new JLabel("Name:");
JLabel lblRollNumber = new JLabel("Roll Number:");
JLabel lblCourse = new JLabel("Course:");
JLabel lblEmail = new JLabel("Email:");

txtName = new JTextField();


txtRollNumber = new JTextField();
txtCourse = new JTextField();
txtEmail = new JTextField();

// Create buttons
btnSubmit = new JButton("Submit");
btnClear = new JButton("Clear");

// Add components to the form


add(lblName); add(txtName);
add(lblRollNumber); add(txtRollNumber);
add(lblCourse); add(txtCourse);
add(lblEmail); add(txtEmail);
add(btnSubmit); add(btnClear);

// Add action listener to the Submit button


btnSubmit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
insertStudentData();
}
});

// Add action listener to the Clear button


btnClear.addActionListener(e -> clearForm());

setVisible(true);
}

// Method to insert student data into the database


private void insertStudentData() {
String url = "jdbc:mysql://localhost:3306/collegeDB?
useSSL=false&allowPublicKeyRetrieval=true";
String username = "root"; // Replace with your MySQL username
String password = ""; // Replace with your MySQL password
try (Connection conn = DriverManager.getConnection(url, username, password)) {
String query = "INSERT INTO student (name, roll_number, course, email) VALUES
(?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);

// Get data from text fields


pstmt.setString(1, txtName.getText());
pstmt.setString(2, txtRollNumber.getText());
pstmt.setString(3, txtCourse.getText());
pstmt.setString(4, txtEmail.getText());

int rowsInserted = pstmt.executeUpdate();


if (rowsInserted > 0) {
JOptionPane.showMessageDialog(this, "Record Inserted Successfully!");
clearForm();
}
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}

// Method to clear the form fields


private void clearForm() {
txtName.setText("");
txtRollNumber.setText("");
txtCourse.setText("");
txtEmail.setText("");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new StudentForm());
}
}

You might also like