JTable Pagination in Java JDBC and MySQL Database

JTable Pagination in Java JDBC and MySQL Database

Here we will see how to develop JTable Pagination in java.

We will use JDBC prepared statement and MySQL Database.

We used NetBeans IDE and Jdk 1.8 to develop this project.

Our Project Structure is as below

Pagination in JTable
Fig: Pagination in JTable

To develop this project we used Book Example.

Project Development Steps are

  1. Create table in MySQL Database
  2. SetUp Pagination Project
  3. Create Model (Pojo) Class
  4. Create a DAO class to Perform JDBC Operations
  5. Create Frame to show data in JPanel
  6. Implement Pagination Concepts.

1 Create Table in MySQL Database

We created ebhor database and table called book as below

Inserted 100 records on it.

You can use any “MySQL Data Generator like generatedata.com generate 100 rows or as many as you want.

How to import data in MySQL database
Fig: How to import data in MySQL database

In above figure screen when you scroll down you will find Go button click on it.

Go to browse to see data in table .

After uploading data check you data by clicking on browse in PHPMyAdmin.

Browse the PhpMyAdmin database
Fig: Browse the Book table

Book table created and 100 Records are uploaded in table.

2. SetUp Pagination Project

Create a new Java Project in Netbeans IDE

Select Java in categories and Java Applications in Project.

Fig: New Project Start in NetBeans
Fig: New Project Start in NetBeans

Provide name “Pagination” to your project

Click on Use Dedicated Folder for Storing Libraries.

How to assign Project Name in NetBeans
Fig: Assign Project Name in NetBeans

Now at left side on project explorer

click on Pagination Project.

there create packages

ebhor.model
ebhor.dao
ebhor.frame
ebhor.pagination

Now right click on library and and click on menu Add Jar/Folder…

Now include mysql-connector-java-5.1.14-bin.jar Jar file

How to add mysql-connector-java-5.1.14-bin.jar in NetBean IDE
Fig: Adding mysql-connector-java-5.1.14-bin.jar in NetBean IDE

Next we will create a Pojo class.

3 Create a Model to hold Data

Inside ebhor.model package create a POJO Class Book

Book class contains field id, name, author publication, addDate field.

All fields getter setter , constructos and toString()

Book.java

4 Create a DAO Class to Perform JDBC Operations

Here establish a connection with database.

Extracting data from database are handling .

Inside ebhor.dao following classes are there

ConnectionFactory.java

This class contains a method getConnection() creates connection with MySQL database using database username, password and database name.

getConnection() returns connection Object.

BookDAO.java

This class contains two methods

1 fetchBySize() – This method takes two integer arguments

  1. start is used to select start row in book table.
  2. size is used to select specified number of elements from start.

If you pass parameter fetchBySize(11,10) then it will select 10 records from MySQL with starting table row of 11.

Result set values are stored in DefaultTableModel Object.

DefaultTableModel value can easily represent data in JTable.

2. getRowCount() this method is used to find total number of rows in table.

5 Create Frame to show data in JPanel

UI designing and Action handling work is done here.

BookFrame.java is created in ebhor.frame package

BookFrame.java contains following methods

1 A Default Constructor –

Here a main JPanel is created with GridLayout.

Two other JPanel is created.

tablePanel -to place JTable and pagingPanel to place Paging buttons.

Inside this getCount() and getPageData() is called.

2 getCount() –

This method work is to find book table record count by calling getRowCount() from BookDAO.java.

It also calculate the total pages for pagination based on PAGE_SIZE field.

3. getPageData() –

Work of this method is to get records from Book Table. and set it to JTable based on page number.

To update pagination details getPaginationDetails() is get called.

4 getPaginationDetails() –

This method is used to get dynamic page numbers from Pagination.java.

According to numbers it generates buttons and add actionListeners to buttons.

Also handle button disable and enable features for first and last page number.

5 ActionPerformed()-

Handle the click actions of dynamically generated buttons.

6 public static void main() –

This function is starting execution point for our program.

6 Implement Pagination Concepts

ebhor.pagination.Pagination class is created to implement pagination concept.

public static int[] getPageNos(int currentPage, int totalPages) is used to implement pagination concept.

it takes two argument currentPage and totalPages to get next set of page numbers and return integer array.

Pagination.java

Read More

Login form in Java Swing and MySql Database with source code

Registration Form in Java Swing with MySql Database

Registration Form in Java Swing with MySql Database

Registration Form in Java Swing is covered in this Post.

To develop this project we used NetBeans IDE.

Steps to develop Registration Form in Java Swing is as below

  1. Create User Interface (UI) Using JFrame
  2. Collect all data in Model sent from UI
  3. Validate and Process Received data
  4. Saving data to MySql Database
Project Explorer for Registration Form

Here we have added three external Jar files

  1. mysql-connector-jar-5.1.14-bin.jar – To connect Java program with MySql Database
  2. jBCrypt-0.4.jar – To encrypt password
  3. jdatepicker-1.3.4.jar– To include date picker in JFrame

To Develop Registration form we are considering example of Student.

We will create basic interface to collect student data in JFrame.

Our Final UI JFrame will as below

Registration Form in Java Swing

1 Create User Interface using JFrame

A. Create a basic structure for frame

In main method we created RegisterFrame class object.

set title, visibility, specified frame coordinated and height and width with bounds and other properties.

Created constructor RegisterFrame() to create and initialize frame components (JLable, JTextBox, JButton, …) .

Method setBounds() is used to set location, width and height of components.

addComponents() is used to add components to Container.

Output of above code is as below

JFrame Basic Size
Fig: JFrame height and width

This is basic layout for our Registration form.

B. Adding Components to JFrame

Components JLabel, JTextField, JRadioButton, JPasswordField, JCombobox, JButton etc are used here.

To select Date from Date Picker additional Jar jdatepicker-1.3.4.jar is added to project.

B Add the basic component in JFrame

  1. Components are Declare as Instance variable
  2. Objects of components are created inside Default Constructor
  3. setBounds() is used to set position ,width and height of components.
  4. addComponents() is used to add components in Container.
  5. addActionListener() is used to add action listener on registerButton.
  6. actionPerformed() is over ridden to handle event

Last two steps are handled later on.

After adding basic components it will create Frame as below

Adding Components in JFrame
Fig: Adding Basic Components in JFrame

C Add JDatePicker in JFrame

First check jdatepicker-1.3.4.jar is added in project

Imports for JDatePicker

Adding JDatePicker in constructor

complete code after adding JDatePicker

DateLabelFormatter class is used to show date selector.

JDatePicker Example
Fig: JDatePicker Addition in JFrame

It will complete our UI

2 Collect all data in Model sent from UI

To collect data Register button is clicked and all data from text box and other input fields are collected and set to student Model.

Lets First See student model Students.java

This class contains basic fields of student, constructors, getter and setter methods and to string method.

Adding following code to RegisterFrame.java

  1. ActionLister is added for registerButton
  2. actionPerformed() is overridden to handle click event on register button

Based on genderFemale and genderMale is selected gender variable.is set based on that.

Similar way storing programName, branchName and semesterName from respective dropdown list.

To get value from JDatePicker datePicker.getJFormattedTextField().getText() is used.

It returns value in string to convert string date to java.sql.date Date.valueOf(dobString) is used.

3 Validate and Process Received data

Received data is stored in Student object.

We have already validated dob field.

Other fields are validated in Validation.java

  1. All fields are checked for Empty.
  2. Name length must be more than 4 and less than 20
  3. Validation for Mail id
  4. Mobile Number must be 10 digits long
  5. Password must be between 8 to 20 characters
  6. Password must contain One digit one upper case letter and special symbol
  7. RePassword and password must match

Creating object of validation and and checking for errors if error occurs then it is shown using showMessageDialog().

Processing Data

Processing data is done before and after validation

  1. Based on male and female JRadioButton we assigned male or female to gender variable.
  2. Get Dob from JDatePicker as string and then converted again to java.sql.Date.
  3. BCrypt is used to encrypt password and set to encPassword().

4 Saving data to MySql Database

Validated and processed data and stored in Student object.

To save data of student object first create student table as given below.

ConnectionFactory.java

This file is used to connect java with database and returns the connection object.

Database name :ebhor
Username: ebhor_user
Password: 21V6

RegisterDAO.java

registerStudent() takes a student object and save each field to database using java preparedStatement();

RegisterFrame.java

Receiving response from registerStudent().

Finally Saving data on student table

Student Registration Example
Fig: Registration Done
MySql student table perview
Fig: MySql student table perview

Download Registration Form in Java Swing

Read More

Login form in Java Swing and MySql Database with source code

Simple Calculator in Java Applet

Login form in Java Swing and MySql Database with source code

Login form in Java Swing and MySql Database

We considered a small example with student details to login From Java Swing and redirecting to another frame after login.

We have covered

  • Login Page design using JFrame
  • Validation on Login Page
  • Event Handling for Login button
  • Accessing Student details from MySQL database
  • Matching encrypted password using jBCrypt.

To make our project functionating, we have included additional jar files mysql-connector-java jar file and jBCrypt jar file.

You can check both jar version in below Project Explorer.

Login form in java swing with source code example is developed using NetBeans IDE.

Project Explorer for this project is as below.

Project Explorer for Login form in Java Swing
Fig: Project Explorer

In above Figure you can see, there is a package name login and its three sub packages dao, frames and model.

login.dao contains following three files

1. ConnectionFactory.java -Used to establish connection from database.

2. LoginDAO.java– Extracts user details from student table from MySQL database.

3. Student.sql– It is sql query to create table structure. Also contains a record of a student.

login.frame package contains following files

1 LoginFrame.java – It contains JFrame to create login Frame.

2. HomeFrame.java – It contains Jframe to create home Frame.

3. Validation.java – This file is used to validate userid and password field of LoginFrame

login.model this package contains a file

1 Student.java – This file contains necessary fields of students its getter setter and toString() method. This is a simple Pojo File.

Libraries contains jar files

1 jdk1.8 – Using jdk1.8 for this project

2. mysql-connector-java – Used to connect MySQL database with Java

3 JBCrypt – Used to encrypt password.

To Start a new Project in NetBeans click on

File->New Project

From Category select Java and at Projects select Java Application

then click on next

then provide project Name and select Use dedicated folder for Storing libraries then click on Finish.

This will create a project.

Create a package login and inside login create three packages frames, model and dao.

Create a Login Frame

Create a login frame in login.frames package.

General methods in side login frame is as below.

1 Declare component like buttons,textbos, password field etc in side LoginFrame class

2. Create a default constructor inside this create object for declared components.

3. Create a method setBounds() to assing positions for components

4. Add all components to Container in addComponent()

5 Method addActionListener() is created to add actionListeners() to components

6 actionPerformed() overridden method is used to handle the event

7 main() is creating object of class and setting title, visibility, frame size, EXIT_ON_CLOSE and resizable properties of frame.

Following code contains the general structure of frame

Add Components to Login Frame

Here components JLabel, JTextField, JButton, Container are declared and its objects are created in default constructor , bounds are assigned in setBounds() and componets are added to container in addComponent().

Java Swing Login Example
Fig: Java Swing Login Example

Learn basic JFrame tutorial here

Add Action Listener and perform check for correct userid and password

Added actionListener for loginButton. Action handling is performed in actionPerformed().

We are overriding actionPerformed() of ActionListener Interface.

IF any event occurs then we check its source by e.getSource() method.

Here we are comparing e.getSource() with loginButton. java button click event is handled here.

If login button is clicked then statements inside if statement is executed.

Inside if statment we are getting values of userNameTextField.getText() and passwordField.getText();

getText() is used to get textbox value as text.

getText() of JPassword field is depricated but for demo purpose we are using it.

after getting userid and password we are mathing both with our user id and password

if (userName.equalsIgnoreCase("Test") && password.equalsIgnoreCase("[email protected]"))

if both are matching then print logged in else unable to login.

login page in java swing
Fig: Login Page in Java Swing

Login is check with different user id and password with its output in console is shown below.

Console Result for different userid and password input
Fig: Console Result for different userid and password input

Our code is working properly.

Now we will validate user id and password field.

Adding Validation for userid and password

For validation created a class Validation.java in login.frames package.

For validation we are considering following rules

  1. User id and password must not be empty.
  2. User id and password must have minimum 4 characters
  3. User id and password must have maximum 20 characters

Here Done only basic validation. Not validating valid mail id .

Later or you can also use login with mobile number or any other unique id.

According to this rule we have written following validateLogin().

This will accept userid and password and check for above conditions.

validateLogin() returns err ArrayList and that list is displayed in LoginFrame.

Updating LoginFrame to add validation

Here we created object of Validation and called validateLogin().

If any error occurs then errors are displayed with

JOptionPane.showMessageDialog(null, errors.toArray());

Output for LoginFrame validation is as below

Validation in login form
Fig: Userid and password validation in login form

Checking user id and password from MySQL database

Create MySQL database and table and insert value that is given below

Student Table Description
Fig: Student Table Description

Model to Assing JDBC value to Student Object

Student.java is added in login.model

This contains basic fields of students and getter setter and toString().

Object of this class is created in LoginDAO.java to assign value that are extracted from student table.

Establishing Connection with MySQL Database

ConnectionFactory.java is used to connect MySQL database with username and password and return Connection object.

Following code is how to connect MySQL database with java

Accessing Student details from MySQL Database

Following JDBC program (LoginDAO.java) is used to get student details from database.

For this we used PreparedStatement of JDBC.

Here we fetch data from database in java and assigned to student object.

Here we checked user detail with mail id, you can use with mobile number or with both.

Comparing user id and password from DAO in LoginFrame.java

  1. Create object for LoginDAO
  2. call checkLogin(userName) to check whether user exists or not.
  3. If user exists then student.getId() will not be zero.
  4. Compare user password with database stored password using BCrypt.
  5. If userid and password is correct then show HomeFrame
  6. else show appropriate message

Complete Code for HomeFrame.java is

Showing HomeFrame after Successful Login

In LoginFrame.java if userid and password is correct then we added setVisible(true) for HomeFrame and dispose() the LoginFrame as below

new HomeFrame().setVisible(true); 
this.dispose();

HomeFrame.java is create to login.frames this frame is shown after successfully login.

Fig: User Login Example
Java Home Frame after login
Fig: Redirected to home Frame after successful login

Login form in java swing with source code. Download The Complete Project with Source code

Read More

Simple Calculator in Java Applet

Registration Form in Java Swing with MySql Database

How to find String length in java with and without string method

String length in java

Get String length with String length() method

To find String length in java there is a method length().

This method is used to get length of string.

Signature of length method is:

Length method returns the length of the string. it counts the number of unicode in string.

This is very simple way to get length of a string in java.

Output

Finding the length of unicode string in java

Here we are considering hindi language stored in String. We use length() to get the string length.

You can take any unicode character to check length string length() works properly.

Output

Finding the String length in java of unicode characters

Here we have stored a unicode value in String and finding its length.

Output

Using toCharArray() to find String length in java

toCharArray() is another method in String class to convert String to character array.

Signature of toCharArray() is

In above program String is converted to character array using toCharArray().

Character array is have a field length. This length property finds the length of character array.

Output

Using Function to find the String length in java

In above program you find length of Java String in main method.

Here we have created two static methods length() and length1().

these two methods are accepting string and getting its length.

Using Recursion to find String length

Here we are using recursion to find the length of string.

When a function is called it is checking the lenth of string if string is empty then return zero else call again itself with adding one to return value.

On each recursive call we are eliminating first character from string.

Output

Hope you learn and understand how to get length of string as we discussed different ways to find string length.

Keep Reading other topics.

Inheritance in Java-Types and Examples

Inheritance in Java is the process of acquiring the properties of one class object into another class object.

It allows the hierarchical classification. Inheritance also provides the facility of reusability.

In Java programming, a class that is inherited is called a superclass or sub class or parent class and class that does the inheriting is called sub class or child class.     

If we want to inherit a class, we simply incorporate the definition of one class into another class by using extends keyword.

General form of a class declaration that inherits a super class

Type of Inheritance in Java

There are following type of inheritance

  1. Single level Inheritance
  2. Multi-level Inheritance
  3. Hierarchical Inheritance
  4. Hybrid Inheritance

Note: Java does not support multiple inheritance.        

Single level Inheritance

Property of single level inheritance is as below

  • One Super class and one sub class
  • Sub class inherits the features of super class

java single inheritance
Fig:java single inheritance

Write a program for single level inheritance.

Multi level Inheritance

In multi level inheritance inheritance exists in multiple level.

  • One Super Class
  • It has a child class
  • Child class has a child class

This process may continue and each child class inherits feature of all parent class.

Multilevel Inheritance

program for Multi level inheritance.

Result

Hierarchical Inheritance

java hierarchical inheritance
java hierarchical inheritance

Hybrid  Inheritance

java Hybrid  Inheritance
java Hybrid Inheritance

Result

Note: A subclass can access the public member of super class. A subclass can’t access the private member of super class.

Super Class Cant Access Sub Class Member

A sub class can access all the public member of super class but reverse is not true. Super class cannot access sub class data.

Result

A sub class can’t access the private member of super class.   

Result

Write a program for Hierarchical Inheritance.

Result

String in Java- Constructor methods and examples

Java String is defined in java.lang.String.

Java String is a sequence of characters quoted in double quote (” “).

Java String Constructors

Sr NoConstructor and description
1String()
Create a new empty string object
2String(byte[] bytes)
Construct a string object with byte array
3String(char[] value)
Construct a string object with character array
4String(String original)
Create a string with another string
5String(StringBuffer buffer)
Create a string with StringBuffer object
6String(StringBuilder builder)
Create a string with StringBuilder object

Java String Methods

There are many methods avaible in string class few common and widely used methods are

Java String Method charAt()

This method takes one integer argument and return a character specified at index position.

For any string the index value starts from 0 to string length -1 position.

If passed index value not in valid range then it throws IndexOutOfBoundsException.

For example string Hello Friends contains 13 characters starting from 0 to 12 H is first position with index value 0, F is in seventh position with index value 6 and s is in 13 position with index value 12.


Using number other then 0 to 12( 0 to length()-1) will result in IndexOutOfBountException

Signature:

public char charAt(int index)

Parameters:

index -Integer index value to get character at specified index position.

Return:

Character at passed index value.

Exception Throws:

IndexOutOfBoundsException If index value in not between 0 to String length()-1

Example

Result

Now Print all characters with its index value

Example

Result