0% found this document useful (0 votes)
123 views64 pages

Unit V - Javafx and JDBC

The document covers JavaFX and JDBC, focusing on event handling and UI controls in JavaFX. It explains various types of events, how to handle them, and details common controls like CheckBox, ToggleButton, and RadioButton, along with layout management. Additionally, it provides code examples demonstrating the implementation of these concepts in JavaFX applications.

Uploaded by

ilogesh1221
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)
123 views64 pages

Unit V - Javafx and JDBC

The document covers JavaFX and JDBC, focusing on event handling and UI controls in JavaFX. It explains various types of events, how to handle them, and details common controls like CheckBox, ToggleButton, and RadioButton, along with layout management. Additionally, it provides code examples demonstrating the implementation of these concepts in JavaFX applications.

Uploaded by

ilogesh1221
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
You are on page 1/ 64

Unit – V: JavaFX & JDBC

JAVAFX Events and Controls: Event Basics , Handling Key and Mouse Events ; Controls:
Checkbox, ToggleButton , RadioButtons , ListView , ComboBox , ChoiceBox , Text Controls ,
ScrollPane , Layouts: FlowPane , HBox and VBox , BorderPane , StackPane , GridPane;
Menus: Basics , Menu bars , MenuItem , JDBC , drivers, Steps to create a JDBC application ,
DB Connection Pool
JAVAFX Events and Controls: Event Basics
In JavaFX, events and controls are fundamental components that allows to create
interactive and dynamic user interfaces.
Events in JavaFX
JavaFX provides a rich event-handling mechanism that allows interaction between the
user and the application. Events can be triggered by user actions (like mouse clicks or key
presses) or programmatic changes.
Types of Events
1. Input Events:
o MouseEvent (e.g., mouse clicks, drags)
o KeyEvent (e.g., key presses)
o TouchEvent (e.g., touch gestures)
2. Action Events:
o Triggered by controls like buttons (ActionEvent).
3. Window Events:
o Events related to the application window (WindowEvent).
4. Focus Events:
o Occurs when a control gains or loses focus.
Handling Events
JavaFX uses the Event Handling API, which involves:
 Event Source: The object that generates the event.
 Event Target: The object where the event is sent.
 Event Handler: The logic that responds to the event.
Steps for Event Handling:
1. Register an Event Handler: Use the setOn<EventType> method, e.g., setOnAction.

1
Button button = new Button("Click Me");
button.setOnAction(event -> {
System.out.println("Button clicked!");
});
2. Implement an Event Handler: We can create a separate class implementing
EventHandler:
class MyEventHandler implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent event) {
System.out.println("Handled in a separate class!");
}
}
button.setOnAction(new MyEventHandler());
3. Event Filtering: Use the addEventFilter method to intercept events during the capturing
phase.
4. Event Bubbling: Events propagate through the scene graph from the source to the root
node, allowing parent nodes to handle events.
Controls in JavaFX
JavaFX controls are UI components that enable user interaction.
Common Controls
1. Buttons:
o Button: A clickable button.
o ToggleButton: A button that toggles between selected and unselected states.
2. Text Input:
o TextField: A single-line text input.
o PasswordField: A secure input for passwords.
o TextArea: A multi-line text input.
3. Selections:
o CheckBox: A selectable checkbox.
o RadioButton: A radio button used in a group.
o ComboBox: A dropdown selection box.

2
o ChoiceBox: Similar to ComboBox, but simpler.
4. Lists and Tables:
o ListView: Displays a list of items.
o TableView: Displays data in tabular form.
5. Menu Components:
o MenuBar, Menu, MenuItem: For creating menus.
6. Sliders and Progress:
o Slider: A sliding control for selecting a value.
o ProgressBar, ProgressIndicator: Display progress.
Layout for Controls
Controls are placed in layout containers like:
 HBox (Horizontal layout)
 VBox (Vertical layout)
 GridPane (Grid-based layout)
 StackPane (Stacked layers)
Example with Controls:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class JavaFXExample extends Application {
@Override
public void start(Stage stage) {
Button button = new Button("Click Me");
button.setOnAction(event -> System.out.println("Hello, JavaFX!"));
VBox root = new VBox(button);
Scene scene = new Scene(root, 300, 200);
stage.setTitle("JavaFX Controls and Events");
stage.setScene(scene);

3
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Output:

Hello, JavaFX!
Handling Key and Mouse Events
In JavaFX, handling key events and mouse events allows to make interactive
applications that respond to user input.
Key Events
Key events are generated when the user interacts with the keyboard. They include key
presses, key releases, and typed keys.
Key Event Types
1. KEY_PRESSED: Triggered when a key is pressed down.
2. KEY_RELEASED: Triggered when a key is released.
3. KEY_TYPED: Triggered when a key is typed (press and release). It corresponds to the
character representation of the key.
Handling Key Events
We can handle key events using setOnKeyPressed, setOnKeyReleased, or
setOnKeyTyped methods.

4
Example: Handling Key Events
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class KeyEventExample extends Application {
@Override
public void start(Stage stage) {
Text text = new Text(100, 100, "Press a key");
Pane pane = new Pane(text);
Scene scene = new Scene(pane, 400, 200);

// Handle key pressed event


scene.setOnKeyPressed(event -> {
text.setText("Key Pressed: " + event.getCode());
});
// Handle key released event
scene.setOnKeyReleased(event -> {
text.setText("Key Released: " + event.getCode());
});
stage.setTitle("Key Event Example");
stage.setScene(scene);
stage.show();
// Request focus to receive key events
scene.getRoot().requestFocus();
}
public static void main(String[] args) {
launch();

5
}
}
Output:

Mouse Events
Mouse events are triggered by mouse actions such as clicks, movements, or drags.
Mouse Event Types
1. MOUSE_CLICKED: Triggered when the mouse is clicked.
2. MOUSE_PRESSED: Triggered when a mouse button is pressed.
3. MOUSE_RELEASED: Triggered when a mouse button is released.
4. MOUSE_MOVED: Triggered when the mouse is moved over a node.
5. MOUSE_DRAGGED: Triggered when the mouse is dragged.
6. MOUSE_ENTERED and MOUSE_EXITED: Triggered when the mouse enters or
exits a node.
Handling Mouse Events
Mouse events can be handled using methods like setOnMouseClicked,
setOnMousePressed, and setOnMouseMoved.
Example: Handling Mouse Events
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;

6
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class MouseEventExample extends Application {
@Override
public void start(Stage stage) {
Circle circle = new Circle(200, 150, 50);
circle.setFill(Color.LIGHTBLUE);
Pane pane = new Pane(circle);
Scene scene = new Scene(pane, 400, 300);
// Handle mouse clicked event
circle.setOnMouseClicked(event -> {
System.out.println("Circle clicked at: (" + event.getX() + ", " + event.getY() + ")");
circle.setFill(Color.LIGHTGREEN);
});
// Handle mouse entered event
circle.setOnMouseEntered(event -> {
circle.setFill(Color.YELLOW);
});
// Handle mouse exited event
circle.setOnMouseExited(event -> {
circle.setFill(Color.LIGHTBLUE);
});
stage.setTitle("Mouse Event Example");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}

7
Output:

Circle clicked at: (214.0, 149.0)


Circle clicked at: (206.0, 157.0)
Circle clicked at: (206.0, 157.0)
Key and Mouse Events Together
We can combine key and mouse events in the same application to handle more complex
interactions.
Example: Moving a Circle with Keys and Mouse
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class KeyAndMouseExample extends Application {
@Override
public void start(Stage stage) {

8
Circle circle = new Circle(200, 150, 20);
circle.setFill(Color.CORAL);
Pane pane = new Pane(circle);
Scene scene = new Scene(pane, 400, 300);
// Move circle with arrow keys
scene.setOnKeyPressed(event -> {
switch (event.getCode()) {
case UP -> circle.setCenterY(circle.getCenterY() - 10);
case DOWN -> circle.setCenterY(circle.getCenterY() + 10);
case LEFT -> circle.setCenterX(circle.getCenterX() - 10);
case RIGHT -> circle.setCenterX(circle.getCenterX() + 10);
}
});
// Change circle color on mouse click
circle.setOnMouseClicked(event -> {
circle.setFill(Color.DARKBLUE);
});
stage.setTitle("Key and Mouse Example");
stage.setScene(scene);
stage.show();
// Request focus to capture key events
scene.getRoot().requestFocus();
}
public static void main(String[] args) {
launch();
}
}

9
Output:

Controls: CheckBox
In JavaFX, a CheckBox is a control that allows the user to make a binary choice, such as
selecting or deselecting an option. It is a part of the javafx.scene.control package.
Basic Usage
The CheckBox control has two states:
1. Selected (true)
2. Not selected (false)
It can also have a third state (indeterminate) if explicitly enabled.
Creating a CheckBox
We can create a CheckBox by instantiating it and optionally providing a label.
CheckBox checkBox = new CheckBox("Enable Feature");
Key Properties and Methods
1. Properties:
o selectedProperty(): Tracks whether the CheckBox is selected.
o indeterminateProperty(): Tracks whether the CheckBox is in an indeterminate
state.

10
2. Methods:
o isSelected(): Returns true if the CheckBox is selected.
o setSelected(boolean value): Sets the selection state.
o isIndeterminate(): Returns true if the CheckBox is indeterminate.
o setIndeterminate(boolean value): Sets the indeterminate state.
Example: Basic CheckBox
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class CheckBoxExample extends Application {
@Override
public void start(Stage stage) {
// Create CheckBoxes
CheckBox checkBox1 = new CheckBox("Enable Notifications");
CheckBox checkBox2 = new CheckBox("Subscribe to Newsletter");
// Set default state
checkBox1.setSelected(true);
// Handle user interaction
checkBox1.setOnAction(event -> {
if (checkBox1.isSelected()) {
System.out.println("Notifications Enabled");
} else {
System.out.println("Notifications Disabled");
}
});
VBox root = new VBox(10, checkBox1, checkBox2);
Scene scene = new Scene(root, 300, 200);

11
stage.setTitle("CheckBox Example");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Output:

Example: Handling Multiple CheckBoxes


package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class MultipleCheckBoxesExample extends Application {
@Override
public void start(Stage stage) {
// Create CheckBoxes
CheckBox pizzaBox = new CheckBox("Pizza");

12
CheckBox burgerBox = new CheckBox("Burger");
CheckBox sushiBox = new CheckBox("Sushi");
// Button to show selected options
Button submitButton = new Button("Submit");
submitButton.setOnAction(event -> {
System.out.println("Selected items:");
if (pizzaBox.isSelected()) System.out.println("- Pizza");
if (burgerBox.isSelected()) System.out.println("- Burger");
if (sushiBox.isSelected()) System.out.println("- Sushi");
});

VBox root = new VBox(10, pizzaBox, burgerBox, sushiBox, submitButton);


Scene scene = new Scene(root, 300, 200);
stage.setTitle("Multiple CheckBoxes Example");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Output:

13
ToggleButton
In JavaFX, a ToggleButton is a control that functions like a regular button but with a
"toggle" behavior. When clicked, it remains pressed (selected) until clicked again, toggling
between two states: selected and unselected.
Creating a ToggleButton
We can create a ToggleButton using its constructor and optionally provide a label.
ToggleButton toggleButton = new ToggleButton("Toggle Me");
Key Features of ToggleButton
1. Two States:
o Selected: When the button is pressed and remains active.
o Unselected: When the button is not pressed.
2. Properties:
o selectedProperty(): Tracks whether the ToggleButton is selected.
o isSelected(): Returns true if the button is in the selected state.
o setSelected(boolean value): Manually sets the state.
3. Methods:
o setOnAction(EventHandler<ActionEvent> handler): Sets a handler for action
events triggered on toggle.
Basic Example: ToggleButton
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class ToggleButtonExample extends Application {
@Override
public void start(Stage stage) {
// Create a ToggleButton
ToggleButton toggleButton = new ToggleButton("Toggle Me");
// Add an event handler

14
toggleButton.setOnAction(event -> {
if (toggleButton.isSelected()) {
System.out.println("Button is ON");
} else {
System.out.println("Button is OFF");
}
});
StackPane root = new StackPane(toggleButton);
Scene scene = new Scene(root, 300, 200);
stage.setTitle("ToggleButton Example");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Output:

RadioButton
In JavaFX, a RadioButton is a control that allows users to select one option from a group
of mutually exclusive options. Radio buttons are typically grouped using a ToggleGroup to
enforce single selection within the group.
Key Features of RadioButton
15
1. Single Selection: Only one RadioButton in a ToggleGroup can be selected at a time.
2. Properties:
o selectedProperty(): Tracks whether the RadioButton is selected.
o toggleGroupProperty(): Links the RadioButton to a ToggleGroup.
3. Methods:
o isSelected(): Returns true if the button is selected.
o setSelected(boolean value): Manually selects or deselects the button.
Creating a RadioButton
We can create a RadioButton by instantiating it and optionally providing a label.
RadioButton radioButton = new RadioButton("Option 1");
Basic Example: RadioButtons
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class RadioButtonExample extends Application {
@Override
public void start(Stage stage) {
// Create RadioButtons
RadioButton option1 = new RadioButton("Option 1");
RadioButton option2 = new RadioButton("Option 2");
RadioButton option3 = new RadioButton("Option 3");
// Group the RadioButtons
ToggleGroup group = new ToggleGroup();
option1.setToggleGroup(group);
option2.setToggleGroup(group);
option3.setToggleGroup(group);
// Set default selection

16
option1.setSelected(true);
// Add event handlers
group.selectedToggleProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
RadioButton selected = (RadioButton) newValue;
System.out.println("Selected: " + selected.getText());
}
});
VBox root = new VBox(10, option1, option2, option3);
Scene scene = new Scene(root, 300, 200);
stage.setTitle("RadioButton Example");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Output:

17
Selected: Option 2
ListView
A list view is a scrollable list of items from which we can select desired items. We can
create a list view component by instantiating the javafx.scene.control.ListView class. We can
create either a vertical or a horizontal ListView.
Example Program:
package application;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class ListViewExample extends Application {
public void start(Stage stage) {
//Label for education
Label label = new Label("Educational qualification:");

18
Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
label.setFont(font);
//list View for educational qualification
ObservableList<String> names = FXCollections.observableArrayList("Engineering",
"MCA", "MBA", "Graduation", "MTECH", "Mphil", "Phd");
ListView<String> listView = new ListView<String>(names);
listView.setMaxSize(200, 160);
//Creating the layout
VBox layout = new VBox(10);
layout.setPadding(new Insets(5, 5, 5, 50));
layout.getChildren().addAll(label, listView);
layout.setStyle("-fx-background-color: BEIGE");
//Setting the stage
Scene scene = new Scene(layout, 595, 200);
stage.setTitle("List View Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
ComboBox
ComboBox is a part of the JavaFX library. JavaFX ComboBox is an implementation of simple
ComboBox which shows a list of items out of which user can select at most one item, it inherits
the class ComboBoxBase.
Constructors of ComboBox:
 ComboBox(): creates a default empty combo box
 ComboBox(ObservableList i): creates a combo box with the given items

19
Example:
This following program creates a ComboBox named combo_box and add a list of string
to it using ChoiceBox(FXCollections.observableArrayList(week_days)). We can add the combo
box and a label(description) to the tilepane(getChildren().add() function). We can create a stage
(container) and add the tilepane to the scene and add the scene to the stage. We can display the
stage using show() function.
Program:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.collections.*;
import javafx.stage.Stage;
import javafx.scene.text.Text.*;
import javafx.scene.paint.*;
import javafx.scene.text.*;
public class combo_box_1 extends Application {
// Launch the application
public void start(Stage stage)
{
// Set title for the stage
stage.setTitle("creating combo box ");
// Create a tile pane
TilePane r = new TilePane();
// Create a label
Label description_label =
new Label("This is a combo box example ");
// Weekdays

20
String week_days[] = { "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday" };
// Create a combo box
ComboBox combo_box =
new ComboBox(FXCollections
.observableArrayList(week_days));
// Create a tile pane
TilePane tile_pane = new TilePane(combo_box);
// Create a scene
Scene scene = new Scene(tile_pane, 200, 200);
// Set the scene
stage.setScene(scene);
stage.show();
}
public static void main(String args[])
{
// Launch the application
launch(args);
}
}
Output:

21
ChoiceBox
ChoiceBox is a part of the JavaFX package. ChoiceBox shows a set of items and allows the user
to select a single choice and it will show the currently selected item on the top. ChoiceBox by
default has no selected item unless otherwise selected. One may either specify the items and then
the selected item, or you may specify the selected item and then the items. Constructor of the
ChoiceBox class are:
 ChoiceBox(): Creates a new empty ChoiceBox.
 ChoiceBox(ObservableList items): Creates a new ChoiceBox with the given set of items.
Program to create a ChoiceBox and add items to it:
The following program creates a ChoiceBox named c and add a list of string to it
using(ChoiceBox(FXCollections.observableArrayList(string_array))). We can add the choice
and a label to the tilepane(getChildren().add() function). We can create a stage (container) and
add the tilepane to the scene and add the scene to the stage. Then display the stage using show()
function.
Program:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.collections.*;
import javafx.stage.Stage;
public class Choice_1 extends Application {
// launch the application
public void start(Stage s)
{
// set title for the stage
s.setTitle("Creating ChoiceBox");
// create a button

22
Button b = new Button("show");
// create a tile pane
TilePane r = new TilePane();
// create a label
Label l = new Label("This is a choice box");
// string array
String st[] = { "Arnab", "Andrew", "Ankit", "None" };
// create a choiceBox
ChoiceBox c = new ChoiceBox(FXCollections.observableArrayList(st));
// add ChoiceBox
r.getChildren().add(l);
r.getChildren().add(c);
// create a scene
Scene sc = new Scene(r, 200, 200);
// set the scene
s.setScene(sc);
s.show();
}
public static void main(String args[])
{
// launch the application
launch(args);
}
}

23
Output:

Text Controls
JavaFX TextField
Text Field is basically used to get the input from the user in the form of text.
javafx.scene.control.TextField represents TextField. It provides various methods to deal with
textfields in JavaFX. TextField can be created by instantiating TextField class.
Example:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class TextFieldExample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {

24
Label user_id=new Label("User ID");
Label password = new Label("Password");
TextField tf1=new TextField();
TextField tf2=new TextField();
Button b = new Button("Submit");
b.setOnAction(e->System.out.println("You entered: User_ID: "+tf1.getText()+" "+"Password:
"+tf2.getText()));
GridPane root = new GridPane();
root.addRow(0, user_id, tf1);
root.addRow(1, password, tf2);
root.addRow(2, b);
Scene scene=new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.setTitle("Text Field Example");
primaryStage.show();
}
}
Output:

You entered: User_ID: EEE Password: EEE

25
ScrollPane
ScrollPane is a control that provides a scrollable viewport of its contents. It allows the user to
scroll the content vertically or horizontally by using scroll bars. It is used to display a component
that is large or one whose size can change dynamically when the screen viewport is limited. The
size of the scroll bars depends on the size of the component.
ScrollPane in JavaFX
In JavaFX, the scrollpane control is represented by a class named ScrollPane. This class belongs
to the package javafx.scene.control. By instantiating this class, we can create a ScrollPane
control in JavaFX. This class has the following constructors.
 ScrollPane() − It constructs a ScrollPane without any node.
 ScrollPane(Node content) − It constructs a new ScrollPane with the specified node.
Steps to create a ScrollPane in JavaFX
To create a ScrollPane in JavaFX, follow the steps given below.
Step 1: Create a node to display within the ScrollPane
In JavaFX, the scrollpane can display nodes that can contain an image, a text or a chart. Hence,
instantiate the respected class to create the desired node. Here, we are using an image as a
content for the ScrollPane.
// create an image view
ImageView imageTp = new ImageView(new Image("tutorials_point.jpg"));
Step 2: Instantiate the ScrollPane class
Instantiate the class named ScrollPane inside the start() method. This action will create a
ScrollPane for the ImageView.
// create a scroll pane
ScrollPane newscroll = new ScrollPane();
Step 3: Set the Content of the ScrollPane
To set the content of the ScrollPane, we use the method named setContent(). Pass the
ImageView object to this method as a parameter value.
// set the content of the scroll pane
newscroll.setContent(imageTp);
Step 4: Launch the Application

26
Once the ScrollPane is created and its content is set, follow the given steps below to launch the
application properly.
 Firstly, instantiate the class named Scene by passing the ScrollPane object as a parameter
value to its constructor along with the dimensions of the application screen.
 Then, set the title of the stage using the setTitle() method of the Stage class.
 Now, a Scene object is added to the stage using the setScene() method of the class
named Stage.
 Display the contents of the scene using the method named show().
 Lastly, the application is launched with the help of the launch() method.
Example Program:
The following JavaFX program demonstrates how to create a ScrollPane within JavaFX
application. Save this code in a file with the name JavafxScrollpane.java.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
public class JavafxScrollpane extends Application {
@Override
public void start(Stage stage) {
// creating an image view
ImageView imageTp = new ImageView(new Image("tutorials_point.jpg"));
// creating a scroll pane
ScrollPane newscroll = new ScrollPane();
// setting the content of the scroll pane
newscroll.setContent(imageTp);
// creating a scene and stage
Scene scene = new Scene(newscroll, 500, 300);
stage.setTitle("ScrollPane in JavaFX");
stage.setScene(scene);

27
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
To compile and execute the saved Java file from the command prompt, use the following
commands.
javac --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxScrollpane.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxScrollpane
Output:
When we execute the above code, it will generate the following output.

Layouts: FlowPane, HBox and VBox, BorderPane, StackPane, GridPane


Layouts are the top level container classes that define the UI styles for scene graph
objects. Layout can be seen as the parent node to all the other nodes. JavaFX provides various
layout panes that support different styles of layouts. In JavaFX, Layout defines the way in which

28
the components are to be seen on the stage. It basically organizes the scene-graph nodes. We
have several built-in layout panes in JavaFX that are HBox, VBox, StackPane, FlowBox,
AnchorPane, etc. Each Built-in layout is represented by a separate class which needs to be
instantiated in order to implement that particular layout pane. All these classes belong to
javafx.scene.layout package. javafx.scene.layout.Pane class is the base class for all the built-in
layout classes in JavaFX.
Layout Classes
javafx.scene.layout package provides various classes that represents the layouts. The classes are
described in the table below.

Class Description

BorderPane Organizes nodes in top, left, right, centre and the bottom of the screen.

Organizes the nodes in the horizontal rows according to the available horizontal spaces.
FlowPane Wraps the nodes to the next line if the horizontal space is less than the total width of the
nodes

GridPane Organizes the nodes in the form of rows and columns.

HBox Organizes the nodes in a single row.

Pane It is the base class for all the layout classes.

StackPane Organizes nodes in the form of a stack i.e. one onto another

VBox Organizes nodes in a vertical column.

Steps to create layout:


In order to create the layouts, we need to follow the following steps.
Instantiate the respective layout class, for example, HBox root = new HBox();
Setting the properties for the layout, for example, root.setSpacing(20);
Adding nodes to the layout object, for example, root.getChildren().addAll(<NodeObjects>);

29
JavaFX BorderPane
BorderPane arranges the nodes at the left, right, centre, top and bottom of the screen. It is
represented by javafx.scene.layout.BorderPane class. This class provides various methods like
setRight(), setLeft(), setCenter(), setBottom() and setTop() which are used to set the position for
the specified nodes. We need to instantiate BorderPane class to create the BorderPane layout.
Properties
The properties of BorderPane class along with their setter methods are given in the table below.

Type Property Setter Methods Description

Node Bottom setBottom() Add the node to the bottom of the screen

Node Centre setCentre() Add the node to the centre of the screen

Node Left setLeft() Add the node to the left of the screen

Node Right setRight() Add the node to the right of the screen

Node Top setTop() Add the node to the top of the screen

Constructors
BorderPane() : create the empty layout
BorderPane(Node Center) : create the layout with the center node
BorderPane(Node Center, Node top, Node right, Node bottom, Node left) : create the layout with
all the nodes
Example Program:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;

30
import javafx.stage.Stage;
public class Label_Test extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane BPane = new BorderPane();
BPane.setTop(new Label("This will be at the top"));
BPane.setLeft(new Label("This will be at the left"));
BPane.setRight(new Label("This will be at the Right"));
BPane.setCenter(new Label("This will be at the Centre"));
BPane.setBottom(new Label("This will be at the bottom"));
Scene scene = new Scene(BPane,600,400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Output:

31
JavaFX HBox
HBox layout pane arranges the nodes in a single row. It is represented by
javafx.scene.layout.HBox class. We just need to instantiate HBox class in order to create HBox
layout.
Properties
The Properties of the class along with their setter methods are given in the table below.

Property Description Setter Methods

alignment This represents the alignment of the nodes. setAlignment(Double)

This is a boolean property. If we set this property to


fillHeight true the height of the nodes will become equal to the setFillHeight(Double)
height of the HBox.

spacing This represents the space between the nodes in the setSpacing(Double)

32
HBox. It is of double type.

Constructors
The HBox class contains two constructors that are given below.
new HBox() : create HBox layout with 0 spacing
new Hbox(Double spacing) : create HBox layout with a spacing value
Example:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class hbox_test extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
HBox root = new HBox();
Scene scene = new Scene(root,200,200);
root.getChildren().addAll(btn1,btn2);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:

33
JavaFX VBox
Instead of arranging the nodes in horizontal row, Vbox Layout Pane arranges the nodes in a
single vertical column. It is represented by javafx.scene.layout.VBox class which provides all the
methods to deal with the styling and the distance among the nodes. This class needs to be
instantiated in order to implement VBox layout in our application.
Properties
This Method Provides various properties which are described in the table below.

Property Description Setter Methods

Alignment This property is for the alignment of the nodes. setAlignement(Double)

This property is of the boolean type. The Widtht of


FillWidth resizeable nodes can be made equal to the Width of the setFillWidth(boolean)
VBox by setting this property to true.

This property is to set some spacing among the nodes of


Spacing setSpacing(Double)
VBox.

Constructors

34
1. VBox() : creates layout with 0 spacing
2. Vbox(Double spacing) : creates layout with a spacing value of double type
3. Vbox(Double spacing, Node? children) : creates a layout with the specified spacing
among the specified child nodes
4. Vbox(Node? children) : creates a layout with the specified nodes having 0 spacing among
them
Example Program:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class vbox_test extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
VBox root = new VBox();
Scene scene = new Scene(root,200,200);
root.getChildren().addAll(btn1,btn2);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Output:

35
JavaFX StackPane
The StackPane layout pane places all the nodes into a single stack where every new node gets
placed on the top of the previous node. It is represented by javafx.scene.layout.StackPane class.
We just need to instantiate this class to implement StackPane layout into our application.
Properties
The class contains only one property that is given below along with its setter method.

Property Description Setter Method

It represents the default alignment of children within setAlignment(Node child, Pos value)
alignment
the StackPane's width and height setAlignment(Pos value)

Constructors
The class contains two constructors that are given below.
StackPane()
StackPane(Node? Children)
Example Program:
package application;
import javafx.application.Application;
import javafx.scene.Scene;

36
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class stackpane_test extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Button btn1 = new Button("Button 1 on bottom ");
Button btn2 = new Button("Button 2 on top");
StackPane root = new StackPane();
Scene scene = new Scene(root,200,200);
root.getChildren().addAll(btn1,btn2);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:

JavaFX GridPane

37
GridPane Layout pane allows us to add the multiple nodes in multiple rows and columns. It is
seen as a flexible grid of rows and columns where nodes can be placed in any cell of the grid. It
is represented by javafx.scence.layout.GridPane class. We just need to instantiate this class to
implement GridPane.
Properties
The properties of the class along with their setter methods are given in the table below.

Property Description Setter Methods

Represents the alignment of the grid within the


alignment setAlignment(Pos value)
GridPane.

This property is intended for debugging. Lines can be


gridLinesVisible displayed to show the gidpane's rows and columns by setGridLinesVisible(Boolean value)
setting this property to true.

hgap Horizontal gaps among the columns setHgap(Double value)

vgap Vertical gaps among the rows setVgap(Double value)

Example Program:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Label_Test extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Label first_name=new Label("First Name");

38
Label last_name=new Label("Last Name");
TextField tf1=new TextField();
TextField tf2=new TextField();
Button Submit=new Button ("Submit");
GridPane root=new GridPane();
Scene scene = new Scene(root,400,200);
root.addRow(0, first_name,tf1);
root.addRow(1, last_name,tf2);
root.addRow(2, Submit);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:

JavaFX FlowPane
FlowPane layout pane organizes the nodes in a flow that are wrapped at the flowpane's
boundary. The horizontal flowpane arranges the nodes in a row and wrap them according to the
flowpane's width. The vertical flowpane arranges the nodes in a column and wrap them
according to the flowpane's height. FlowPane layout is represented by

39
javafx.scene.layout.FlowPane class. We just need to instantiate this class to create the flowpane
layout.
Properties
There are various properties of the class which are described in the table below.

Property Description Setter Methods

alignment The overall alignment of the flowpane's content. setAlignment(Pos value)

The horizontal alignment of nodes within the


columnHalignment setColumnHalignment(HPos Value)
columns.

hgap Horizontal gap between the columns. setHgap(Double value)

orientation Orientation of the flowpane setOrientation(Orientation value)

The preferred height or width where content should


prefWrapLength setPrefWrapLength(double value)
wrap in the horizontal or vertical flowpane.

The vertical alignment of the nodes within the


rowValignment setRowValignment(VPos value)
rows.

vgap The vertical gap among the rows setVgap(Double value)

Constructors
There are 8 constructors in the class that are given below.
FlowPane()
FlowPane(Double Hgap, Double Vgap)
FlowPane(Double Hgap, Double Vgap, Node? children)
FlowPane(Node... Children)
FlowPane(Orientation orientation)
FlowPane(Orientation orientation, double Hgap, Double Vgap)
FlowPane(Orientation orientation, double Hgap, Double Vgap, Node? children )
FlowPane(Orientation orientation, Node... Children)
Example Program

40
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class flowpanetest extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("FlowPane Example");
FlowPane root = new FlowPane();
root.setVgap(6);
root.setHgap(5);
root.setPrefWrapLength(250);
root.getChildren().add(new Button("Start"));
root.getChildren().add(new Button("Stop"));
root.getChildren().add(new Button("Reset"));
Scene scene = new Scene(root,300,200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Output:

41
Menus: Basics
JavaFX provides a Menu class to implement menus. Menu is the main component of a any
application. In JavaFX, javafx.scene.control.Menu class provides all the methods to deal with
menus. This class needs to be instantiated to create a Menu.
The following sample of code shows the implementation of JavaFX menu.
MenuBar menubar = new MenuBar(); //creating MenuBar
Menu MenuName = new Menu("Menu Name"); //creating Menu
MenuItem MenuItem1 = new MenuItem("Menu Item 1 Name"); //creating Menu Item
MenuName.getItems().add(MenuItem1); //adding Menu Item to the Menu
menubar.getMenus().add(MenuName); //adding Menu to the MenuBar
Example Program:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MenuExample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override

42
public void start(Stage primaryStage) throws Exception {
BorderPane root = new BorderPane();
Scene scene = new Scene(root,200,300);
MenuBar menubar = new MenuBar();
Menu FileMenu = new Menu("File");
MenuItem filemenu1=new MenuItem("new");
MenuItem filemenu2=new MenuItem("Save");
MenuItem filemenu3=new MenuItem("Exit");
Menu EditMenu=new Menu("Edit");
MenuItem EditMenu1=new MenuItem("Cut");
MenuItem EditMenu2=new MenuItem("Copy");
MenuItem EditMenu3=new MenuItem("Paste");
EditMenu.getItems().addAll(EditMenu1,EditMenu2,EditMenu3);
root.setTop(menubar);
FileMenu.getItems().addAll(filemenu1,filemenu2,filemenu3);
menubar.getMenus().addAll(FileMenu,EditMenu);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Output:

Menu Bars and Menu Item


43
Java program to create a menu bar and add menu to it and also add menu items to the
menu:
The following program creates a menubar indicated by the name mb. A menu will be
created by name m and 3 menuitems m1, m2, m3 will be added to the menu m and the menu m
will be added to menubar mb. The menubar will be created inside a scene, which in turn will be
hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a VBox is
created, on which addChildren() method is called to attach the menubar inside the scene. Finally,
the show() method is called to display the final results.
Constructor of the MenuBar class:
MenuBar(): creates a new empty menubar.
Example Program:
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.stage.Stage;
import javafx.scene.control.Alert.AlertType;
import java.time.LocalDate;
public class MenuBar_1 extends Application {
// launch the application
public void start(Stage s)
{
// set title for the stage
s.setTitle("creating MenuBar");
// create a menu
Menu m = new Menu("Menu");
// create menuitems

44
MenuItem m1 = new MenuItem("menu item 1");
MenuItem m2 = new MenuItem("menu item 2");
MenuItem m3 = new MenuItem("menu item 3");
// add menu items to menu
m.getItems().add(m1);
m.getItems().add(m2);
m.getItems().add(m3);
// create a menubar
MenuBar mb = new MenuBar();
// add menu to menubar
mb.getMenus().add(m);
// create a VBox
VBox vb = new VBox(mb);
// create a scene
Scene sc = new Scene(vb, 500, 300);
// set the scene
s.setScene(sc);
s.show();
}
public static void main(String args[])
{
// launch the application
launch(args);
}
}

45
Output:

JDBC
JDBC API is a Java API that can access any kind of tabular data, especially data stored in
a Relational Database. JDBC works with Java on a variety of platforms, such as Windows, Mac
OS, and the various versions of UNIX. JDBC stands for Java Database Connectivity, which is a
standard Java API for database-independent connectivity between the Java programming
language and a wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.
Applications of JDBC
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of
executables, such as:
 Java Applications
 Java Applets
 Java Servlets

46
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data. JDBC provides the same capabilities as ODBC, allowing Java
programs to contain database-independent code.
The JDBC 4.0 Packages
The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC
version at the time of writing this tutorial. It offers the main classes for interacting with your data
sources.
The new features in these packages include changes in the following areas:
 Automatic database driver loading.
 Exception handling improvements.
 Enhanced BLOB/CLOB functionality.
 Connection and statement interface enhancements.
 National character set support.
 SQL ROWID access.
 SQL 2003 XML data type support.
 Annotations.
Interfaces and Classes of JDBC API
Following is the list of mostly used interfaces and classes in JDBC API.
 DriverManager class − used to load a SQL driver to connect to database.
 Connection interface − used to make a connection to the database using database
connection string and credentials.
 Statement interface − used to make a query to the database.
 PreparedStatement interface − used for a query with placeholder values.
 CallableStatement interface − used to called stored procedure or functions in database.
 ResultSet interface − represents the query results obtained from the database.
 ResultSetMetaData interface − represents the metadata of the result set.
 BLOB (Binary Large Objects) class − represents binary data stored in BLOB format in
database table.

47
 CLOB (Character Large Objects) class − represents text data like XML stored in
database table
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in
general, JDBC Architecture consists of two layers −
 JDBC API − This provides the application-to-JDBC Manager connection.
 JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct
driver is used to access each data source. The driver manager is capable of supporting multiple
concurrent drivers connected to multiple heterogeneous databases. Following is the architectural
diagram, which shows the location of the driver manager with respect to the JDBC drivers and
the Java application.

Common JDBC Components


The JDBC API provides the following interfaces and classes:
 DriverManager − This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using communication

48
sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be
used to establish a database Connection.
 Driver − This interface handles the communications with the database server. We can
interact directly with Driver objects very rarely. Instead, we use DriverManager objects,
which manages objects of this type. It also abstracts the details associated with working
with Driver objects.
 Connection − This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is
through connection object only.
 Statement − We use objects created from this interface to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing stored
procedures.
 ResultSet − These objects hold data retrieved from a database after we execute an SQL
query using Statement objects. It acts as an iterator to allow us to move through its data.
 SQLException − This class handles any errors that occur in a database application.
JDBC Drivers
Java Database Connectivity (JDBC) is an Application Programming Interface (API) for
the programming language Java, which defines how a client may access any kind of tabular data,
especially a relational database. JDBC Drivers uses JDBC APIs which was developed by Sun
Microsystem, but now this is a part of Oracle. There are 4 types of JDBC drivers. It is part of the
Java Standard Edition platform, from Oracle Corporation. It acts as a middle-layer interface
between Java applications and databases. The JDBC classes are contained in the Java Package
java.sql and javax.sql. JDBC helps is to write Java applications that manage these three
programming activities:
1. Connect to a data source, like a database.
2. Send queries and update statements to the database.
3. Retrieve and process the results received from the database in answer to our query.

49
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that
convert requests from Java programs to a protocol that the DBMS can understand. JDBC drivers
are the software components which implements interfaces in JDBC APIs to enable java
application to interact with the database. Now we will learn how many JDBC driver types does
Sun defines? There are four types of JDBC drivers defined by Sun Microsystem that are
mentioned below:
Type-1 driver or JDBC-ODBC bridge driver
Type-2 driver or Native-API driver
Type-3 driver or Network Protocol driver
Type-4 driver or Thin driver
1. JDBC-ODBC bridge driver – Type 1 driver
Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls. Type-1 driver is also called Universal driver because it can be used to connect to any of the
databases.

50
Advantages
 This driver software is built-in with JDK so no need to install separately.
 It is a database independent driver.
Disadvantages
 As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.
 The ODBC bridge driver is needed to be installed in individual client machines.
 Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
2. Native-API driver – Type 2 driver ( Partially Java driver)
The Native API driver uses the client-side libraries of the database. This driver converts
JDBC method calls into native calls of the database API. In order to interact with different
database, this driver needs their local API, that’s why data transfer is much more secure as
compared to type-1 driver. This driver is not fully written in Java that is why it is also called
Partially Java driver.

51
Advantage
 Native-API driver gives better performance than JDBC-ODBC bridge driver.
Disadvantages
 Driver needs to be installed separately in individual client machines.
 The Vendor client library needs to be installed on client machine.
 Type-2 driver isn’t written in java, that’s why it isn’t a portable driver.
 It is a database dependent driver.
3. Network Protocol driver – Type 3 driver (fully Java driver)
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. Here all the database
connectivity drivers are present in a single server, hence no need of individual client-side
installation.

Advantages
 Type-3 drivers are fully written in Java, hence they are portable drivers.

52
 No client side library is required because of application server that can perform many tasks
like auditing, load balancing, logging etc.
 Switch facility to switch over from one database to another database.
Disadvantages
 Network support is required on client machine.
 Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4. Thin driver – Type 4 driver (fully Java driver)
Type-4 driver is also called native protocol driver. This driver interacts directly with database.
It does not require any native database library, that is why it is also known as Thin Driver.

Advantages
 Does not require any native library and Middleware server, so no client-side or server-side
installation.
 It is fully written in Java language, hence they are portable drivers.
Disadvantage
 If the database varies, then the driver will carry because it is database dependent.
Steps to create a JDBC application
JDBC or Java Database Connectivity is a Java API to connect and execute the query with the
database. It is a specification from Sun microsystems that provides a standard abstraction (API or
Protocol) for java applications to communicate with various databases. It provides the language
with java database connectivity standards. It is used to write programs required to access
databases. JDBC, along with the database driver, can access databases and spreadsheets. The

53
enterprise data stored in a relational database (RDB) can be accessed with the help of JDBC
APIs.
Standard Steps followed for developing JDBC (JDBC4.X) Application
1. Load and register the Driver
2. Establish the Connection b/w java application and database
3. Create a Statement Object
4. Send and execute the Query
5. Process the result from ResultSet
6. Close the Connection
Step1: Load and register the Driver
A third-party DB vendor class that implements java.sql.Driver(I) is called a “Driver”.
This class Object we need to create and register it with JRE to set up the JDBC environment to
run JDBC applications.

In MySQL Jar, the Driver class is implementing java.sql.Driver, so Driver class Object should be
created and it should be registered to set up the JDBC environment inside JRE.
Step 2: Establish the Connection b/w java application and database
 public static Connection getConnection(String url, String username,String password)
throws SQLException;
 public static Connection getConnection(String url, Properties) throws SQLException;
 public static Connection getConnection(String url) throws SQLException;
The below creates the Object of Connection interface.

getConnection(url,username,password) created an object of a class which implements


Connection(I) that class object is collected by Connection(I).
54
Step 3: Create a Statement Object
 public abstract Statement createStatement() throws SQLException;
 public abstract Statement createStatement(int,int) throws SQLException;
 public abstract Statement createStatement(int,int,int) throws SQLException;

Step 4: Send and execute the Query


From the DB administrator’s perspective queries are classified into 5 types
 DDL (Create table, alter table, drop table,..)
 DML(Insert, update, delete)
 DQL(select)
 DCL(alter password,grant access)
 TCL(commit,rollback,savepoint)
According to the java developer perspective, we categorize queries into 2 types:
Select Query
NonSelect Query
Methods for executing the Query are
 executeQuery() => for the select query we use this method.
 executeUpdate() => for insert, update and delete queries we use this method.
 execute() => for both select and non-select queries we use this method

Step 5: Process the result from ResultSet


public abstract boolean next() throws java.sql.SQLException; => To check whether the next
Record is available or not returns true if available otherwise returns false.

55
Step 6: Close the Connection

Example Program:
/*Java code to communicate with database and execute select
* query*/
import com.mysql.cj.jdbc.Driver;
import java.io.*;
import java.sql.*;
class TestApp {
public static void main(String[] args)
throws SQLException
{
// Step1. Load and register the Driver
Driver driver = new Driver(); // Creating driver
// object for MySQLDB
DriverManager.registerDriver(driver);
System.out.println("Driver registered successfully");

// Step2: Establish the connection b/w java and

56
// Database
// JDBC URL SYNTAX::
// <mainprotocol>:<subprotocol>:<subname>
String url
= "jdbc:mysql://localhost:3306/enterprisejavabatch";
String username = "root";
String password = "root123";
Connection connection = DriverManager.getConnection(
url, username, password);
System.out.println("Connection object is created:: "
+ connection);
// Create a Statement Object
Statement statement = connection.createStatement();
System.out.println("Statement object is created:: "
+ statement);
// Sending and execute the Query
String sqlSelectQuery
= "select sid,sname,sage,saddr from Student";
ResultSet resultSet
= statement.executeQuery(sqlSelectQuery);
System.out.println("ResultSet object is created:: "
+ resultSet);
// Process the result from ResultSet
System.out.println("SID\tSNAME\tSAGE\tSADDR");
while (resultSet.next()) {
Integer id = resultSet.getInt(1);
String name = resultSet.getString(2);
Integer age = resultSet.getInt(3);
String team = resultSet.getString(4);
System.out.println(id + "\t" + name + "\t" + age
+ "\t" + team);

57
}
// Close the Connection
connection.close();
System.out.println("Closing the connection...");
}
}
Output:

DB Connection Pool
In Java applications, interacting with the databases using JDBC (Java Database
Connectivity), and managing the database connections efficiently is crucial for optimal
performance and resource utilization. Connection pooling is the technique employed to achieve
the goal by reusing the established database connections instead of creating new ones for each
request.
JDBC usage is establishing the new database connection involving the costly network
communication process, authentication, and resource allocation. This can significantly impact
application performance, especially in the interactions of frequent databases. When an
application needs to perform database operations, it will be requested to the connection from the
pool, utilized it and it will be returned to the pool once it is done. This approach can minimize
the overhead of the connection establishment and teardown, leading to be improved performance
and scalability.
Prerequisites:
The following are the prerequisites to handle connection pooling in JDBC in Java
1. Database Setup
1. JDBC Driver (Java Database Connectivity Driver)

58
1. Connection Pooling Library
1. Java Development Environment
1. Project Configuration
Steps to Handle Connection Pooling in JDBC
Step 1: Create a Table in the Database
Create a table in database (Example: Employee).
Here is the basic example of an employee table:

Step 2: Set Up Project in Eclipse IDE


1. Open Eclipse IDE. Create one Java project and name it as JDBCWithHikariCP.
1. Add HikariCP Dependency to the Java project.
1. Create two Class files in a Java project and name it
as ConnectionManager and Main respectively.
Here is the path for Class files in Java project:

59
Step 3: Implement the Code
Open ConnnectionManager.java file and replace with the below code.
import java.sql.Connection;
import java.sql.SQLException;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

public class ConnectionManager {


private static final HikariDataSource dataSource;

static {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3307/work");
config.setUsername("root");
config.setPassword("tiger");

// Set maximum pool size


config.setMaximumPoolSize(10);

60
// Other configuration options

dataSource = new HikariDataSource(config);


}

public static Connection getConnection() throws SQLException {


return dataSource.getConnection();
}

public static void close() {


if (dataSource != null) {
dataSource.close();
}
}
}
Explanation of the above Program:
1. Import the classes/interfaces for the JDBC and HikariCP configuration.
1. Manage the database connection using the HikariCP connection pooling.
1. Once the class is loaded into the memory, it will be execute.
1. Configures HikariCP DataSource with the connection parameters such
as JDBC URL, username, passwords and maximum pool size.
1. Retrieves a database connection from connection pool with the help of getConnection()
Method.
1. If a connection can't be obtained, it will throws the SQLException.
1. Closes the connection with close() method.
1. To avoid the NullPointerException, checks if the dataSource is not null before closing.
Step 4: Use ConnectionManager in Main Class
Open Main.java file and replace with the below code:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

61
import java.sql.SQLException;

public class Main {


public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;

try {
// Get connection from ConnectionManager
connection = ConnectionManager.getConnection();

if (connection != null) {
// Prepare statement
String sql = "SELECT * FROM employees";
preparedStatement = connection.prepareStatement(sql);

// Execute query
resultSet = preparedStatement.executeQuery();

// Process and print results


while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
} else {
System.out.println("Failed to get connection.");
}
} catch (SQLException e) {
e.printStackTrace();

62
} finally {
// Close resources
try {
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close(); // Return connection to pool
} catch (SQLException e) {
e.printStackTrace();
}
}

// Close the connection pool when application exits


ConnectionManager.close();
}
}
Explanation of the above Program:
1. In main class, program starts the execution.
1. We can declare the three variables
i.e. connection, preparedstatement, resultSet .Here, connection is used
to establish the connection to the database. preparedstatement s used
to execute the SQL queries. resultSet is used to stores the results returned by database
query.
1. We are use the try-catch block to handle the potential errors that will be occur during
the database operations.
1. We are get the database connection from ConnectionManager class. Make sure it is
properly configured.
1. If you are getting the connection successfully, we can prepare an SQL statement for
retrieve data from database table employees.
1. We are execute SQL query and store the results in resultSet.
1. We loop through resultSet to retrieve the each row data such as ID and name and it prints
in the console window.

63
1. If any errors are occurred in the above steps SQLException will be catch the exception and
prints the message in the console window.
1. Make sure that database resources are properly closed in the finally block to avoid the
risks.
1. After finish the program, we can close the connection pool which is managed by
the ConnectionManager.
Step 5: Run the Code
1. After complete the implementation of code, you need to run the code.
1. For run the code, right click on the project the Run As > Java Application.
Here is the Output shown below in your console window:

Note:
1. If you get "Failed to get connection", it means application is failed to establish a connection
to the database.
1. You need to check the following troubleshoot the issues:
 Verify Database URL
 Check Database Credentials
 Database Server Running
 Firewall and Network Issues
 Database Driver
 Database Configuration
 Error Logging

64

You might also like