0% found this document useful (0 votes)
3 views44 pages

Unit 5 Java-Sem

JDBC (Java Database Connectivity) is an API that allows Java applications to connect and interact with databases through a two-layer architecture consisting of the JDBC API Layer and the JDBC Driver Layer. It supports various database operations and provides four types of JDBC drivers for different use cases. Additionally, the document covers string operations in Java, event handling in GUI applications, and multithreading concepts with example programs demonstrating each topic.

Uploaded by

ramanagweb
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views44 pages

Unit 5 Java-Sem

JDBC (Java Database Connectivity) is an API that allows Java applications to connect and interact with databases through a two-layer architecture consisting of the JDBC API Layer and the JDBC Driver Layer. It supports various database operations and provides four types of JDBC drivers for different use cases. Additionally, the document covers string operations in Java, event handling in GUI applications, and multithreading concepts with example programs demonstrating each topic.

Uploaded by

ramanagweb
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 5

[Link] Architecture (Java Database Connectivity)


Definition:

JDBC (Java Database Connectivity) is an API (Application Programming Interface) in Java that
enables Java programs to connect and interact with databases.​
It allows Java applications to execute SQL statements, retrieve results, and perform CRUD
operations (Create, Read, Update, Delete) in a database-independent way.

JDBC Architecture Overview:

JDBC architecture consists of two layers:

1.​ JDBC API Layer​

2.​ JDBC Driver Layer​

These layers work together to connect a Java application with the database.

1. JDBC API Layer:

●​ This layer provides the interfaces and classes that Java developers use to interact with
databases.​

●​ It allows the application to send SQL queries and process the results.​

●​ The main classes and interfaces are found in the [Link] package.​

Main Components:

●​ DriverManager – Manages a list of database drivers and establishes connections.​

●​ Connection – Represents a session/connection with a specific database.​


●​ Statement – Used to execute SQL queries.​

●​ ResultSet – Stores the results of executed SQL queries.​

●​ SQLException – Handles database-related errors.​

2. JDBC Driver Layer:

●​ This layer is responsible for communicating directly with the database.​

●​ It converts the JDBC API calls into database-specific calls.​

Types of JDBC Drivers:

There are four types of JDBC drivers:

1.​ Type 1: JDBC-ODBC Bridge Driver​

○​ Translates JDBC calls into ODBC calls.​

○​ Requires ODBC driver installed.​

○​ Example: [Link]​

○​ Disadvantage: Platform dependent and slow.​

2.​ Type 2: Native API Driver (Partly Java Driver)​

○​ Converts JDBC calls into native database calls using client-side libraries.​

○​ Example: Oracle OCI Driver.​

○​ Disadvantage: Database-specific, not fully portable.​

3.​ Type 3: Network Protocol Driver (Middleware Driver)​

○​ Uses a middleware server to translate JDBC calls into database-specific calls.​


○​ Advantage: No client-side library required.​

4.​ Type 4: Thin Driver (Pure Java Driver)​

○​ Directly converts JDBC calls to database protocol using pure Java.​

○​ Example: [Link] for MySQL.​

○​ Advantage: Platform independent, fastest, widely used.​

JDBC Architecture Diagram:


Java Application
|
| (JDBC API)

JDBC Driver Manager
|
| (Driver)

Database Server

Steps to Connect Java with Database using JDBC:


Load the driver class​

[Link]("[Link]");

1.​

Establish the connection​



Connection con = [Link](
"jdbc:mysql://localhost:3306/studentdb", "root", "password");

2.​
Create a statement​

Statement stmt = [Link]();

3.​

Execute the query​



ResultSet rs = [Link]("SELECT * FROM students");

4.​

Process the results​



while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}

5.​

Close the connection​



[Link]();

6.​

Advantages of JDBC:

●​ Database-independent (portable)​

●​ Simple and easy to use​

●​ Supports multiple databases​

●​ Secure and robust​

●​ Allows both static and dynamic SQL execution​

Conclusion:
JDBC architecture provides a standard interface for connecting Java applications to various
databases.​
By using the JDBC API and driver layers, Java programs can perform all database operations
efficiently and in a platform-independent way.

Q3. Illustrate various String operations with examples.


(10 Marks)

Answer:

1. Introduction:

In Java, a String is a sequence of characters enclosed in double quotes (" ").​


Strings are objects of the String class in the [Link] package and are immutable
(cannot be changed once created).

Example:

String name = "Java Programming";

2. Ways to Create Strings:

Strings can be created in two ways:

Using String Literal​



String s1 = "Hello";

1.​

Using new Keyword​



String s2 = new String("Hello");

2.​

3. Common String Operations (Methods):


(1) length()

Returns the number of characters in a string.

String s = "Hello";
[Link]([Link]()); // Output: 5

(2) charAt(index)

Returns the character at the given index (index starts from 0).

String s = "Java";
[Link]([Link](2)); // Output: v

(3) concat()

Joins (concatenates) two strings together.

String s1 = "Hello ";


String s2 = "World";
[Link]([Link](s2)); // Output: Hello World

(4) equals()

Compares two strings for equality (case-sensitive).

String s1 = "Java";
String s2 = "java";
[Link]([Link](s2)); // Output: false

(5) equalsIgnoreCase()

Compares two strings ignoring case differences.

[Link]([Link](s2)); // Output: true


(6) compareTo()

Compares strings lexicographically (alphabetical order).

String s1 = "Apple";
String s2 = "Banana";
[Link]([Link](s2)); // Output: Negative value

(7) toUpperCase() / toLowerCase()

Converts the string to uppercase or lowercase.

String s = "Java";
[Link]([Link]()); // Output: JAVA
[Link]([Link]()); // Output: java

(8) substring()

Extracts a portion (part) of a string.

String s = "Programming";
[Link]([Link](0, 4)); // Output: Prog

(9) indexOf() / lastIndexOf()

Finds the index position of a character or substring.

String s = "Java Programming";


[Link]([Link]("a")); // Output: 1
[Link]([Link]("a")); // Output: 3

(10) replace()

Replaces characters or substrings in a string.

String s = "Java";
[Link]([Link]('a', 'o')); // Output: Jovo
(11) trim()

Removes leading and trailing spaces from a string.

String s = " Hello ";


[Link]([Link]()); // Output: Hello

(12) split()

Splits a string into parts using a delimiter (like comma, space, etc.).

String s = "A,B,C,D";
String[] parts = [Link](",");
for(String p : parts){
[Link](p);
}

Output:

A
B
C
D

(13) contains()

Checks if the string contains a particular sequence of characters.

String s = "Java Programming";


[Link]([Link]("Program")); // Output: true

(14) startsWith() / endsWith()

Checks if the string starts or ends with a given substring.


String s = "HelloWorld";
[Link]([Link]("Hello")); // true
[Link]([Link]("World")); // true

4. Example Program Demonstrating String Operations:


public class StringExample {
public static void main(String[] args) {
String str = "Java Programming";

// 1. Find length
[Link]("1. Length: " + [Link]());

// 2. Convert to uppercase
[Link]("2. Uppercase: " + [Link]());

// 3. Extract substring
[Link]("3. Substring: " + [Link](5));

// 4. Replace word
[Link]("4. Replace: " + [Link]("Java",
"Python"));

// 5. Check if contains
[Link]("5. Contains 'Pro': " +
[Link]("Pro"));
}
}

Output:

1. Length: 16
2. Uppercase: JAVA PROGRAMMING
3. Substring: Programming
4. Replace: Python Programming
5. Contains 'Pro': true
5. Conclusion:

String operations in Java allow programmers to easily manipulate and process text data.​
They are used in input validation, file handling, message formatting, and many other
real-world applications.

Q4. Discuss about Event Handling in Java. (10 Marks)

1. Introduction:

Event Handling is one of the key features in Java GUI programming (AWT, Swing, and
JavaFX).​
It allows a program to respond to user interactions, such as button clicks, key presses,
mouse movements, etc.

🖱️
In simple terms —​
When a user performs an action (event), Java executes a specific block of code
(event handler).

2. What is an Event?

An event is any action generated by the user or by the system.​


Examples:

●​ Clicking a button​

●​ Moving or dragging the mouse​

●​ Pressing a key on the keyboard​

●​ Closing a window​

3. Event Handling Mechanism (Delegation Event Model):

Java uses the Delegation Event Model to handle events.​


It consists of three main components:
1.​ Event Source → The object that generates the event (e.g., Button).​

2.​ Event Object → Contains information about the event (e.g., which key was
pressed).​

3.​ Event Listener → The object that receives the event and processes it.​

4. Steps in Event Handling:

1.​ Create the Event Source (like Button, TextField, etc.)​

2.​ Implement the Listener Interface that corresponds to the event.​

3.​ Register the Listener with the Event Source using addXXXListener() method.​

4.​ Write the Event Handling Code (inside the listener method).​

5. Commonly Used Event Classes (from [Link] package):


Event Description
Class

ActionEve Generated when a button is clicked


nt

MouseEven Generated on mouse actions


t

KeyEvent Generated on keyboard actions

ItemEvent Generated when item is


selected/deselected

WindowEve Generated when window state changes


nt

6. Commonly Used Listener Interfaces:


Listener Interface Used For

ActionListener Handling button clicks

MouseListener Handling mouse events

KeyListener Handling keyboard inputs

ItemListener Handling checkbox/list selections

WindowListener Handling window close/minimize


events

7. Example 1: Handling Button Click using ActionListener


import [Link].*;
import [Link].*;

public class ButtonEventExample extends Frame implements


ActionListener {

TextField tf;
Button b;

ButtonEventExample() {
tf = new TextField();
[Link](60, 50, 170, 20);

b = new Button("Click Me");


[Link](100, 120, 80, 30);

// Register listener
[Link](this);

add(b);
add(tf);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
// Event handler
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked!");
}

public static void main(String[] args) {


new ButtonEventExample();
}
}

Explanation:

1.​ ActionListener interface is implemented.​

2.​ addActionListener(this) registers the listener.​

3.​ actionPerformed() method is executed when the button is clicked.​

Output:​
When the user clicks the “Click Me” button → the text field displays “Button Clicked!”

8. Example 2: Mouse Event Handling


import [Link].*;
import [Link].*;

public class MouseEventExample extends Frame implements MouseListener


{

Label l;

MouseEventExample() {
addMouseListener(this);
l = new Label("Move or click mouse");
[Link](50, 100, 200, 30);
add(l);
setSize(300, 300);
setLayout(null);
setVisible(true);
}

public void mouseClicked(MouseEvent e) { [Link]("Mouse


Clicked"); }
public void mouseEntered(MouseEvent e) { [Link]("Mouse
Entered"); }
public void mouseExited(MouseEvent e) { [Link]("Mouse
Exited"); }
public void mousePressed(MouseEvent e) { [Link]("Mouse
Pressed"); }
public void mouseReleased(MouseEvent e){ [Link]("Mouse
Released"); }

public static void main(String[] args) {


new MouseEventExample();
}
}

Explanation:

●​ The class implements MouseListener.​

●​ Each method handles a specific mouse action.​

9. Steps Summary (Numbered):

1.​ Import [Link] and [Link] packages.​

2.​ Create GUI components (like Button, Label, TextField).​

3.​ Implement appropriate Listener Interface (e.g., ActionListener).​

4.​ Override the listener method (e.g., actionPerformed()).​


5.​ Register the listener with the component (addActionListener()).​

6.​ Execute the event-handling logic when the event occurs.​

10. Advantages of Event Handling:

✅ Increases interactivity of GUI applications.​


✅ Separates logic from the user interface.​
✅ Makes programs more organized and responsive.​
✅ Provides reusability and flexibility in design.

11. Conclusion:

Event Handling in Java enables GUI applications to react to user actions like button
clicks, key presses, and mouse movements.​
By using the Delegation Event Model, Java provides a powerful and flexible way to
manage and control user interactions.

Q5. Develop a Java program using Multithreaded


concept. (10 Marks)

1. Introduction:

Multithreading in Java is a process of executing two or more threads (subtasks)


simultaneously to achieve multitasking.​
A thread is a lightweight sub-process — the smallest unit of CPU execution.

It helps in performing multiple tasks at the same time such as:

●​ Downloading files while playing music​

●​ Printing documents while typing in a text editor​

2. Key Terms:
●​ Process: An independent program in execution.​

●​ Thread: A smaller unit of a process.​

●​ Multithreading: Running multiple threads concurrently.​

3. Life Cycle of a Thread:

A thread passes through several stages:

1.​ New: Thread object is created.​

2.​ Runnable: Thread is ready to run but waiting for CPU.​

3.​ Running: Thread starts execution.​

4.​ Blocked/Waiting: Thread is paused temporarily.​

5.​ Terminated: Thread completes its execution.​

4. Thread Creation Methods:

There are two ways to create a thread in Java:

(a) By extending Thread class

(b) By implementing Runnable interface

5. Example 1: Creating Thread by Extending Thread Class


// Step 1: Extend Thread class
class MyThread extends Thread {

// Step 2: Override run() method


public void run() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + " -
Count: " + i);
try {
[Link](500); // Step 3: Pause for 0.5 seconds
} catch (InterruptedException e) {
[Link](e);
}
}
}
}

public class ThreadExample1 {


public static void main(String[] args) {

// Step 4: Create thread objects


MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

// Step 5: Start threads


[Link]();
[Link]();
}
}

Output:

Thread-0 - Count: 1
Thread-1 - Count: 1
Thread-0 - Count: 2
Thread-1 - Count: 2
...

Explanation:

1.​ MyThread class extends Thread class.​

2.​ run() method defines the task to perform.​


3.​ start() method begins execution — JVM runs run() on a new thread.​

4.​ Multiple threads (t1, t2) execute simultaneously.​

6. Example 2: Creating Thread by Implementing Runnable Interface


// Step 1: Implement Runnable interface
class Task implements Runnable {
public void run() {
for (int i = 1; i <= 3; i++) {
[Link]([Link]().getName() + " is
running iteration " + i);
}
}
}

public class ThreadExample2 {


public static void main(String[] args) {

// Step 2: Create Runnable object


Task t = new Task();

// Step 3: Create Thread objects passing Runnable reference


Thread t1 = new Thread(t, "Thread-A");
Thread t2 = new Thread(t, "Thread-B");

// Step 4: Start threads


[Link]();
[Link]();
}
}

Output:

Thread-A is running iteration 1


Thread-B is running iteration 1
Thread-A is running iteration 2
Thread-B is running iteration 2

7. Important Thread Methods:


Method Description

start() Starts the execution of a thread

run() Contains the code executed by the


thread

sleep(ms) Pauses thread for given milliseconds

join() Waits for a thread to complete

isAlive() Checks if thread is still running

setName() / Sets or gets thread name


getName()

setPriority() Sets thread priority (1–10)

8. Advantages of Multithreading:

1.​ Efficient CPU utilization​

2.​ Faster execution​

3.​ Saves time through parallelism​

4.​ Enables responsive GUI applications​

5.​ Independent and concurrent task execution​

9. Step-by-Step Summary:

1.​ Define a class that extends Thread or implements Runnable.​


2.​ Override the run() method to define task logic.​

3.​ Create objects of the thread class.​

4.​ Call the start() method to begin thread execution.​

5.​ Use thread methods (sleep, join, etc.) to control execution.​

10. Conclusion:

Multithreading in Java allows multiple operations to run concurrently within a program,


improving efficiency and performance.​
It is widely used in real-time applications such as games, multimedia processing, and
servers.

Q6. Explain about Mouse Events with example. (10 Marks)

1. Introduction:

A Mouse Event in Java occurs when the user interacts with a mouse, such as clicking,
pressing, releasing, entering, or exiting a component (like a button or window).

Java provides the MouseEvent class and the MouseListener or MouseAdapter interfaces
to handle mouse-related actions.

2. What is a Mouse Event?

Mouse events are part of the event-handling mechanism in Java’s Abstract Window Toolkit
(AWT) and Swing.​
They occur when:

●​ The user clicks or double-clicks a mouse button​

●​ The mouse pointer enters or exits a component area​

●​ The mouse is pressed, released, or moved​


3. Mouse Event Classes and Interfaces:
Class / Interface Purpose

MouseEvent Represents events generated by the mouse.

MouseListener Used for handling basic mouse events (click, press, release, enter,
exit).

MouseMotionList Used for handling mouse movement (move, drag).


ener

MouseAdapter A class that provides empty implementations of mouse methods (to


avoid implementing all methods manually).

4. Important Methods of MouseListener:


Method Description

mouseClicked(MouseEven Invoked when mouse is clicked (pressed +


t e) released).

mousePressed(MouseEven Invoked when mouse button is pressed.


t e)

mouseReleased(MouseEve Invoked when mouse button is released.


nt e)

mouseEntered(MouseEven Invoked when mouse enters the component area.


t e)

mouseExited(MouseEvent Invoked when mouse leaves the component area.


e)

5. Steps for Handling Mouse Events:

1.​ Import the packages:​


Import [Link].* and [Link].*.​
2.​ Create a class:​
The class should implement the MouseListener interface.​

3.​ Override all methods of MouseListener.​

4.​ Register the listener using addMouseListener() method.​

5.​ Write logic for each mouse event (e.g., change label text when mouse is clicked).​

6. Example Program: Handling Mouse Events


import [Link].*;
import [Link].*;

public class MouseEventExample extends Frame implements MouseListener


{

Label label;

MouseEventExample() {
// Step 1: Create label
label = new Label("Perform any mouse action");
[Link](50, 100, 200, 30);
add(label);

// Step 2: Register MouseListener


addMouseListener(this);

// Step 3: Frame settings


setSize(300, 300);
setLayout(null);
setVisible(true);
}

// Step 4: Override all methods of MouseListener


public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked at (" + [Link]() + "," + [Link]()
+ ")");
}

public void mousePressed(MouseEvent e) {


[Link]("Mouse Pressed");
}

public void mouseReleased(MouseEvent e) {


[Link]("Mouse Released");
}

public void mouseEntered(MouseEvent e) {


[Link]("Mouse Entered the Frame");
}

public void mouseExited(MouseEvent e) {


[Link]("Mouse Exited the Frame");
}

public static void main(String[] args) {


new MouseEventExample();
}
}

7. Explanation of the Program:

1.​ The class extends Frame and implements MouseListener.​

2.​ A Label is used to show the mouse event messages.​

3.​ The addMouseListener(this) statement registers the current class as a listener.​

4.​ Each method (e.g., mouseClicked, mousePressed) performs a specific action.​

5.​ The program updates the label text according to the mouse event.​

8. Output (Runtime Behavior):


●​ When the mouse enters the window → “Mouse Entered the Frame”​

●​ When the mouse exits → “Mouse Exited the Frame”​

●​ When you click → “Mouse Clicked at (x,y)”​

●​ When you press or release → Message updates accordingly.​

9. Advantages of Mouse Events:

✅ Enhances user interaction in GUI applications​


✅ Detects mouse actions precisely​
✅ Helps in building interactive applications (games, drawing apps, editors, etc.)

10. Conclusion:

Mouse Events in Java allow programs to respond to user interactions effectively.​


By using the MouseListener and MouseEvent classes, developers can build interactive GUI
applications that react to mouse actions such as clicks, movements, and drags.

Q7. Write a Java program to JDBC concept. (10 Marks)

1. Introduction:

JDBC (Java Database Connectivity) is a Java API that enables Java applications to connect
and interact with databases such as MySQL, Oracle, or PostgreSQL.​
It allows executing SQL queries like SELECT, INSERT, UPDATE, and DELETE directly from
Java code.

2. JDBC Architecture:

The JDBC architecture consists of two main layers:

1.​ JDBC API Layer → Provides interfaces and classes in [Link] package.​
2.​ JDBC Driver Layer → Translates Java calls into database-specific calls.​

3. JDBC Steps (Numbered Explanation):

To connect and interact with a database using JDBC, follow these 6 steps:

Step 1: Import required packages

Import the [Link] package which includes all JDBC classes and interfaces.

Step 2: Load the JDBC Driver

Register the driver class that communicates with the database.​


Example:

[Link]("[Link]");

Step 3: Establish the Connection

Use [Link]() to connect Java to the database.​


Example:

Connection con =
[Link]("jdbc:mysql://localhost:3306/studentdb",
"root", "password");

Step 4: Create a Statement Object

A statement object is used to execute SQL queries.

Statement stmt = [Link]();

Step 5: Execute SQL Query

Run SQL commands using executeQuery() (for SELECT) or executeUpdate() (for


INSERT/UPDATE/DELETE).

ResultSet rs = [Link]("SELECT * FROM students");


Step 6: Close the Connection

Always close the connection to free resources.

[Link]();

4. Example Java Program Using JDBC (MySQL Database):


// Step 1: Import package
import [Link].*;

public class JDBCExample {


public static void main(String args[]) {
try {
// Step 2: Load the MySQL JDBC driver
[Link]("[Link]");

// Step 3: Establish connection to the database


Connection con = [Link](
"jdbc:mysql://localhost:3306/studentdb", "root",
"password");

// Step 4: Create Statement object


Statement stmt = [Link]();

// Step 5: Execute SQL query


ResultSet rs = [Link]("SELECT * FROM
students");

// Step 6: Process the result set


while ([Link]()) {
[Link]([Link](1) + " " +
[Link](2) + " " + [Link](3));
}

// Step 7: Close connection


[Link]();
} catch (Exception e) {
[Link](e);
}
}
}

5. Explanation of the Program:

1.​ The program connects to a MySQL database named studentdb.​

2.​ It retrieves all rows from the table students.​

3.​ ResultSet is used to read data row by row.​

4.​ Each student’s ID, Name, and Course are printed on the console.​

5.​ try-catch block handles exceptions like missing drivers or connection errors.​

6. Sample Output (If Database Table ‘students’ has data):


ID Name Cours
e

1 Ram Java

2 Sai Python

Output:

1 Ram Java
2 Sai Python

7. Common JDBC Classes:


Class / Purpose
Interface
DriverManage Establishes connection between Java and
r database

Connection Maintains session with database

Statement Executes SQL queries

ResultSet Holds data returned from the database

SQLException Handles SQL-related exceptions

8. Advantages of JDBC:

✅ Platform Independent​
✅ Supports multiple databases​
✅ Easy to execute SQL commands​
✅ Secure and efficient​
✅ Part of standard Java library

9. Important Points to Remember:

●​ Include MySQL Connector JAR file in your Java classpath.​

●​ Ensure MySQL is installed and the database (studentdb) and table (students) exist.​

●​ Always close connection and statement objects to prevent memory leaks.​

10. Conclusion:

JDBC provides a simple and powerful way to connect Java programs to databases.​
It plays a key role in enterprise-level applications that require database access, such as web
applications and management systems.

Q8. Discuss about JavaFX GUI Scene Builder concept.


(10 Marks)
1. Introduction:

JavaFX is a powerful GUI (Graphical User Interface) framework in Java used to create rich
desktop, internet, and mobile applications.​
Scene Builder is a visual layout tool that allows developers to design JavaFX user interfaces
without writing any code manually — using a drag-and-drop interface.

It generates an FXML file (XML-based UI description), which can be connected to Java code
through controllers.

2. What is Scene Builder?

Scene Builder is a Graphical UI Design Tool provided by Gluon for building JavaFX layouts
visually.

●​ It allows you to drag and drop UI controls (like buttons, text fields, labels) into a layout.​

●​ Automatically generates the FXML code.​

●​ You can later link this FXML file to Java logic using a controller class.​

3. Advantages of Scene Builder:

✅ No need to manually code the UI​


✅ Faster UI design using drag and drop​
✅ Auto-generates FXML code​
✅ Easy to integrate with IDEs (Eclipse, IntelliJ, NetBeans)​
✅ Helps maintain separation of UI (FXML) and Logic (Java Controller)

4. JavaFX Architecture Overview:


+----------------------------+
| JavaFX Application Class |
+----------------------------+

+----------------------------+
| Stage (Main Window) |
+----------------------------+

+----------------------------+
| Scene (Container for UI) |
+----------------------------+

+----------------------------+
| UI Controls (Buttons, etc)|
+----------------------------+

Scene Builder mainly focuses on designing the Scene — arranging the layout and UI
components.

5. Key Components in JavaFX Scene Builder:


Component Description

Stage The main window of the application.

Scene Holds all UI elements in a hierarchical structure.

Layout Pane Controls the arrangement of elements (e.g., VBox, HBox,


GridPane).

Controls GUI elements like Button, Label, TextField.

FXML File XML file that defines the UI layout.

Controller Java class that handles user actions (events).

6. Steps to Create JavaFX GUI Using Scene Builder:

Step 1: Install Scene Builder

👉
Download and install from:​
[Link]

Step 2: Create a JavaFX Project

In your IDE (like IntelliJ, Eclipse, or NetBeans), create a new JavaFX Project.

Step 3: Open FXML File in Scene Builder


●​ Right-click the [Link] file → Choose Open with Scene Builder.​

●​ The Scene Builder window opens.​

Step 4: Design UI Visually

●​ Drag UI components (Label, Button, TextField, etc.) from the Library Panel to the
Design Area.​

●​ Adjust their layout using the Inspector Panel.​

Step 5: Save the Design

●​ Scene Builder automatically generates or updates the FXML file.​

Step 6: Link the FXML with Controller

●​ Add fx:id for UI components in Scene Builder.​

●​ Create a controller Java class (e.g., [Link]) and connect actions (like
button clicks).​

Step 7: Run the Application

●​ The main JavaFX application loads the FXML file and displays the designed UI.​

7. Example Program: JavaFX Application using Scene Builder

(a) FXML File — [Link]

<?xml version="1.0" encoding="UTF-8"?>


<?import [Link].*?>
<?import [Link].*?>

<VBox xmlns:fx="[Link] fx:controller="Controller"


spacing="10" alignment="CENTER">
<Label text="Enter Your Name:"/>
<TextField fx:id="txtName" />
<Button text="Say Hello" onAction="#sayHello"/>
<Label fx:id="lblOutput"/>
</VBox>

(b) Controller Class — [Link]

import [Link];
import [Link];
import [Link];

public class Controller {


@FXML
private TextField txtName;
@FXML
private Label lblOutput;

// Method called when button is clicked


public void sayHello() {
String name = [Link]();
[Link]("Hello, " + name + "!");
}
}

(c) Main Application — [Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class Main extends Application {


public void start(Stage primaryStage) throws Exception {
Parent root =
[Link](getClass().getResource("[Link]"));
[Link]("JavaFX Scene Builder Example");
[Link](new Scene(root, 300, 200));
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

8. Output:

When the program runs:

●​ A window appears with a text field and a “Say Hello” button.​

●​ After typing your name and clicking the button → the label displays:​
“Hello, Ram!”​

9. Advantages of Using Scene Builder in JavaFX:

1.​ Simplifies GUI creation through visual design.​

2.​ No need to manually write FXML layout code.​

3.​ Clean separation between UI and logic (FXML + Controller).​

4.​ Reduces development time for large-scale JavaFX projects.​

5.​ Provides real-time preview of UI.​

10. Conclusion:
JavaFX Scene Builder is a fast and efficient tool for building user interfaces visually.​
It allows developers to design, preview, and link UI components to Java logic easily — making
GUI application development in Java simple and modular.

Q9. Explain about Laying Out Nodes in Scene Graph. (10


Marks)

1. Introduction:

In JavaFX, every graphical element such as a Button, Label, TextField, or Pane is called a
Node.​
All nodes are arranged in a Scene Graph, which represents the hierarchical structure of the
graphical user interface (GUI).

To display the nodes properly on the screen, JavaFX uses Layout Panes that manage the
positioning, alignment, and sizing of nodes — this process is called Layout Management or
Laying Out Nodes.

2. What is a Scene Graph?

A Scene Graph is a tree-like data structure that contains all the graphical elements of a
JavaFX application.

●​ The root node is the topmost container (like Group, Pane, VBox, etc.).​

●​ Every other UI element (Button, Label, ImageView, etc.) is a child node of that root.​

Hierarchy Example:

Stage
└── Scene
└── Root Node (Layout Pane)
├── Label
├── Button
└── TextField
3. Layout Panes (Used to Arrange Nodes):

JavaFX provides several built-in layout panes to position and align nodes automatically.

Layout Pane Description

Pane Basic container; manually position nodes using coordinates.

HBox Arranges nodes horizontally in a single row.

VBox Arranges nodes vertically in a single column.

BorderPane Divides the area into top, bottom, left, right, and center regions.

GridPane Arranges nodes in a table-like grid of rows and columns.

StackPane Places all nodes on top of each other in a stack.

FlowPane Arranges nodes in rows or columns, automatically wrapping them.

AnchorPane Positions nodes relative to the edges of the pane.

4. Layout Panes with Examples:

(1) VBox Layout (Vertical Arrangement)


VBox vbox = new VBox(10); // 10px spacing
[Link]().addAll(new Label("Name:"), new TextField(), new
Button("Submit"));

👉 Arranges components vertically (one below another).


(2) HBox Layout (Horizontal Arrangement)
HBox hbox = new HBox(20); // 20px spacing
[Link]().addAll(new Label("Username:"), new TextField());

👉 Arranges components horizontally (side by side).


(3) BorderPane Layout
BorderPane borderPane = new BorderPane();
[Link](new Label("Top Region"));
[Link](new Button("Center Button"));
[Link](new Label("Bottom Region"));

👉 Divides screen into Top, Bottom, Left, Right, Center areas.


(4) GridPane Layout
GridPane grid = new GridPane();
[Link](10);
[Link](10);
[Link](new Label("Username:"), 0, 0);
[Link](new TextField(), 1, 0);
[Link](new Label("Password:"), 0, 1);
[Link](new PasswordField(), 1, 1);

👉 Arranges UI elements in rows and columns (like a table).


(5) StackPane Layout
StackPane stack = new StackPane();
Button btn = new Button("Click Me");
[Link]().add(btn);

👉 Places all components on top of each other, center-aligned by default.


(6) FlowPane Layout
FlowPane flow = new FlowPane();
[Link]().addAll(new Button("A"), new Button("B"), new
Button("C"));

👉 Arranges nodes in a flow — automatically moves to the next line when space is insufficient.
5. Complete Example: Scene Graph with Layouts
import [Link];
import [Link];
import [Link].*;
import [Link].*;
import [Link];

public class LayoutExample extends Application {


public void start(Stage primaryStage) {
// Step 1: Create nodes
Label label1 = new Label("Enter Name:");
TextField textField = new TextField();
Button button = new Button("Submit");

// Step 2: Create layout pane (VBox)


VBox layout = new VBox(10); // 10px spacing
[Link]().addAll(label1, textField, button);

// Step 3: Create scene and add layout


Scene scene = new Scene(layout, 300, 200);

// Step 4: Set stage


[Link]("JavaFX Layout Example");
[Link](scene);
[Link]();
}

public static void main(String[] args) {


launch(args);
}
}

6. Explanation of Example:

1.​ The Stage acts as the main window.​


2.​ A VBox layout pane is created as the root node.​

3.​ Child nodes (Label, TextField, Button) are added to the VBox.​

4.​ The Scene is set with the VBox as its root node.​

5.​ The Stage displays the Scene, showing all nodes vertically aligned.​

7. Output (GUI Window):


Enter Name:
[Text Field Here]
[Submit Button]

👉 The nodes are neatly arranged vertically using the VBox layout.

8. Benefits of Using Layout Panes:

✅ Automatically adjust size and position of components.​


✅ Make the GUI responsive to window resizing.​
✅ Reduce manual positioning errors.​
✅ Simplify GUI design using combinations of layouts.

9. Common Scene Graph Hierarchy Example:


Stage
└── Scene
└── BorderPane (root)
├── Top → MenuBar
├── Left → VBox (Buttons)
├── Center → GridPane (Form)
└── Bottom → Label (Status)

This hierarchy defines how each part of the interface is structured and displayed.
10. Conclusion:

Laying out nodes in a Scene Graph is an essential part of building a JavaFX GUI.​
By using layout panes like VBox, HBox, GridPane, and BorderPane, developers can design
responsive, structured, and visually appealing interfaces easily.

Q10. Discuss about Various Mouse Event Mechanisms


with Example. (10 Marks)

1. Introduction:

Mouse events in Java are used to handle user interactions made using a mouse device —
such as clicking, pressing, releasing, entering, or exiting components.​
These actions generate Mouse Events, which can be captured and processed using Event
Listener interfaces in AWT or JavaFX.

In Java, the Mouse Event Mechanism follows the Delegation Event Model, where an event
source (like a button or frame) delegates the event to a registered listener.

2. What is a Mouse Event Mechanism?

The Mouse Event Mechanism is the process that allows a Java GUI component to:

1.​ Detect mouse actions.​

2.​ Generate appropriate event objects.​

3.​ Notify listener methods that respond to those events.​

This mechanism provides interaction and control to the user interface.

3. Classes and Interfaces Used in Mouse Event Handling:


Component Purpose

MouseEvent Represents all mouse actions like click, press, release, enter, and
exit.
MouseListener Interface for basic mouse actions.

MouseMotionList Interface for mouse movement (drag, move).


ener

MouseWheelListe Interface for handling mouse wheel actions.


ner

MouseAdapter Abstract class providing empty implementations (for convenience).

4. Types of Mouse Events:


Mouse Action Event Method Description

Mouse Clicked mouseClicked(MouseEvent e) When mouse is clicked (pressed +


released)

Mouse Pressed mousePressed(MouseEvent e) When mouse button is pressed

Mouse Released mouseReleased(MouseEvent When mouse button is released


e)

Mouse Entered mouseEntered(MouseEvent e) When mouse enters a component

Mouse Exited mouseExited(MouseEvent e) When mouse exits a component

Mouse Moved mouseMoved(MouseEvent e) When mouse moves over a


component

Mouse Dragged mouseDragged(MouseEvent e) When mouse is dragged while


holding a button

Mouse Wheel mouseWheelMoved(MouseWheel When mouse wheel is rotated


Moved Event e)

5. Steps in Handling Mouse Events:

1.​ Import Packages:​


[Link].* and [Link].*​

2.​ Create a Class:​


That implements required mouse listener interfaces (e.g., MouseListener,
MouseMotionListener).​

3.​ Override Event Methods:​


Provide logic for each mouse event you want to handle.​

4.​ Register the Listener:​


Use addMouseListener(), addMouseMotionListener(), or
addMouseWheelListener() methods.​

5.​ Compile and Run:​


The program responds to mouse actions on the GUI component.​

6. Example Program: Mouse Event Mechanisms


import [Link].*;
import [Link].*;

public class MouseMechanismExample extends Frame


implements MouseListener, MouseMotionListener,
MouseWheelListener {

Label label;

MouseMechanismExample() {
// Step 1: Create a label to display messages
label = new Label("Interact using Mouse");
[Link](60, 100, 200, 30);
add(label);

// Step 2: Register mouse listeners


addMouseListener(this);
addMouseMotionListener(this);
addMouseWheelListener(this);

// Step 3: Frame settings


setSize(350, 300);
setLayout(null);
setVisible(true);
}

// Step 4: Override MouseListener methods


public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked at (" + [Link]() + "," + [Link]()
+ ")");
}

public void mousePressed(MouseEvent e) {


[Link]("Mouse Pressed");
}

public void mouseReleased(MouseEvent e) {


[Link]("Mouse Released");
}

public void mouseEntered(MouseEvent e) {


[Link]("Mouse Entered the Frame");
}

public void mouseExited(MouseEvent e) {


[Link]("Mouse Exited the Frame");
}

// Step 5: Override MouseMotionListener methods


public void mouseDragged(MouseEvent e) {
[Link]("Mouse Dragged at (" + [Link]() + "," + [Link]()
+ ")");
}

public void mouseMoved(MouseEvent e) {


[Link]("Mouse Moved at (" + [Link]() + "," + [Link]() +
")");
}

// Step 6: Override MouseWheelListener method


public void mouseWheelMoved(MouseWheelEvent e) {
[Link]("Mouse Wheel Rotated: " + [Link]());
}

public static void main(String[] args) {


new MouseMechanismExample();
}
}

7. Explanation of the Program:

1.​ The program creates a Frame window with a Label.​

2.​ It implements all three interfaces:​

○​ MouseListener for clicks and presses​

○​ MouseMotionListener for movement and drag events​

○​ MouseWheelListener for wheel actions​

3.​ Each overridden method changes the label text depending on the mouse action.​

4.​ The program demonstrates all mouse event mechanisms in one example.​

8. Output (Runtime Behavior):

●​ When mouse enters the frame → “Mouse Entered the Frame”​

●​ When mouse exits → “Mouse Exited the Frame”​

●​ When clicked → “Mouse Clicked at (x, y)”​

●​ When dragged → “Mouse Dragged at (x, y)”​

●​ When mouse wheel scrolled → “Mouse Wheel Rotated: 1” or “-1”​


9. Advantages of Mouse Event Mechanisms:

✅ Enables user interaction with GUI elements​


✅ Helps in games, graphics editors, and design software​
✅ Provides full control over all mouse activities​
✅ Supports advanced motion and wheel detection

10. Conclusion:

The Mouse Event Mechanism in Java provides a structured way to handle all mouse actions
— including clicks, movements, drags, and wheel rotations.​
By using MouseListener, MouseMotionListener, and MouseWheelListener, developers can
create interactive and user-friendly GUI applications.

You might also like