Applet Life Cycle in Java with Example

Applet in Java

Applet in Java is a special Java program that are primarily used in a internet programming.

Applet Life Cycle is very important to know in Java Applet Programming. 

As we have already seen how to run program from command prompt, but there were no GUI.

To provide Graphical user interface(GUI) Java Applet is used.

Applet program runs on a web browser at client side. Applet program are used to make the web site more dynamic.

1 Life Cycle of Applet Stages

When the applet program is loaded is passes through several stages:

Java Applet Life Cycle
Java Applet Life Cycle

A Applet Born State

Also known as initialization state.  

It is the first state of applet lifecycle.

Applet enters in a born/ initialization state when it is first loaded.  

Applet moves in a born state when init() method of Applet class executes.

Applet initialization occurs once in a  applet lifecycle.

Inside the init() method we initialize all the variables.

Syntax of init() method in Java Applet

B Applet Running State

  Applet enters in a running state from born state when a start() method of Applet class executes.  

Running sates call automatically when the initialization phase completes. 

Applet also comes in a running state from idle state when idle applet again get processor.

Running sates call automatically when the initialization phase completes. 

Applet also comes in a running state from idle state when idle applet again get processor.

Syntax of start()              

C Applet Idle State

A running appletenters in a idle sate from running state when execution of start complete.

In a another words when we leave the page of running applet then automatically it enters in a idle sate from running state.

Applet moves in idle state when  stop() method executes and it moves idle to running state when again start() calls.

Syntax of stop()               

D Applet Dead State

  An applet is moved to dead state when we quit the web browser.  When applet moves in a dead state it removed from memory. 

The Applet will be terminate when destroy () method calls. In a applet lifecycle, applet terminates/destroys ones.

Syntax of destroy()        

E Applet Display State

The Display state executes immediately after when applet enters in a running state.

In this state we display the information on the output screen using paint() method.

2 Applet Life Cycle Program in Java Example

Lets see one program to demonstrate the life cycle of applet.

Compile and Run

>javac AppletLifeCycle.java
>appletviewer AppletLifeCycle.java

Applet Life Cycle in Java Example
Fig: Java Applet Life Cycle Example

Output At Console

On running Applet It will print first 3 line from output.

On closing applet it will call stop and destroy method.

init() method can be used to initialize various values and objects that are going to use in program.

Similarly to release resource we can use destroy().

Example: Write a program to read file and show in java applet.

Output

Fig: Reading File in showing in an applet

Read More

  1. JComboBox in Java Swing
  2. JTable in Java Swing
  3. JTable Pagination in Java JDBC
  4. Registration Form in Java Swing
  5. Login form in Java Swing
  6. Simple Calculator in Java Applet

Write a java program to reverse a string

Using StringBuffer or StringBuilder class

Output

Using Loops(Iteration)

Copy and reverse the string

Here getting input from user

converted into character array using toCharArray() of String

Initialize the other character array with same length as c character array.

Loop char array c in reverse order and r in forward order.

this will copy character array c in reverse order to r.

converted char array r to String

print both character array

Output

Read More

  1. Duplicate Number between 1 to n numbers
  2. Print vowels in a String
  3. Sum of two numbers using command line arguments
  4. Prime number program in java using while loop
  5. Print vowels in a String
  6. Square Star Pattern

Exception Handling try catch finally blocks in Java

What is try block

A try block is used to surround a set of statements where exceptions may occur.

A try block used with catch and finally block

Also Read

Exception Handling in Java: Hierarchy Example and Types

What is a catch block

A catch block is created followed by a try block.

Whenever an exception is thrown from try block it catches in the appropriate catch block

There can be more than one catch block for a try block.

Syntax of try catch block

Java finally block

Java finally block is also associated with a try block.

Finally block is used to release resources that are used in a try block.

like closing a file. closing database connection

Finally block gets always executed when there is exception or not in try block.

We can use try and finally or try catch and finally.

Syntax of try-catch and finally

1 try and finally

2 try catch and finally

try catch java examples

ArithmeticException Example in Java

Output

Exception occurs at the line “a = 42 / d; “ , then this exception is thrown, program control transfer from  try block to catch block.

Once  catch block has executed program control continue with the next line in a program following entire try/catch statement.

In the line “catch (ArithmeticException e) “  e is a reference of exception “ArithmeticException”.

When we print the value of “e “ it will print  ( java.lang.ArithmeticException:/by zero                                                                    at  Test.main(Test.java:6) )

  • ArithmeticException is an exception class which resides in java.lang package.
  • “/by zero”  is a type of arithmetic exception (divided by zero).
  • “Test” is the name of the class.
  • “main” is a method in which an exception occurs.
  • 6 is line number in which exception occured.

Java try catch multiple exceptions

1 Try and multiple catch blocks

In java programming, when within a try block multiple exceptions occur then for handling those multiple exceptions we use multiple catches with a single try block.

When we pass no command line argument (during run time) than the length of command line argument (args.length) is zero means value of variable “a” is 0.

Than the output is:

When we pass one or more command line argument ( in this program one command line argument is passed “test” during run time) than the length of command line argument (args.length) is one means value of variable “a” is  1.

Than the output is:

2 Java try catch multiple exceptions

Unreachable Code in Exception Handling

In Java programming, in a sequence of catch statement exception subclass must come before its super class.

In a series, if exception super class comes before  its subclass than exception sub class would never be reached.

It is known as unreachable code. In Java programming, unreachable code is an compile-time error.    

Example unreachable code in Exception Handling

If we will try to compile this program we will receive an error message stating that the second catch statement is unreachable because ArithmeticException is a subclass of the Exception class. 

     Then the first catch statement will handle all exception-based errors, including Arithmetic Exception therefore second catch statement will never execute.

 To solve the problem, reverse the order of the catch statement.  

Nested try catch Java statements

In java programming, it is possible to create a try block within another try block. Such try block is known as nested try.

Nested try catch Example

If there is no command line argument present then the output.

If there is no command line argument present then the output.

Read More

User-Defined Exception in Java with Examples

Q : When a statement within a try block causes an exception, the remaining statements in the try block

Ans: Will Not be executed

Q: In a try/catch construct, after the catch statement is executed:

Ans: Statement just after the catch is executed

Q: Can you have multiple catch blocks on a try statement

Ans: Yes, as per the need we can have multiple catch blocks on a try statement

Q: To catch an exception, the code that might throw the exception must be enclosed in a ____________

Ans: try block

Q: If an exception occurs in a try-catch block, the code in the finally clause ________.

Ans: Get Executed. If with try block finally is associated then it always gets executed no matter it throws an exception or not.

Q: A try block may be followed by a finally block, without a catch block (Java try without catch).

Ans: Yes we can use try and finally without a catch block.

Q: Exceptions can be thrown by ________.

Ans: Throw statement is used to throw an Exception

Q: When is the code within a catch block executed?

Ans: If an exception occurs within the code in the try block then matched exception in the catch block gets executed.

Java unreported exception How to Handle it

The unreported exception is due to you have checked exception in your program and you are not handling it.

You can handle it

  1. By using try catch block
  2. By using throws keyword in method

unreported exception

Which of the following Throwables needs to be declared?

  1. Error
  2. RuntimeException
  3. CheckedException 
  4. Exception

Answer is 3

More MCQ

Read More

  1. Exception Handling in Java: Hierarchy Example and Types
  2. Exception Handling in Java with Examples
  3. Throw and Throws Keywords in Java
  4. How To Fix Internal Exception: java.io.ioexception In Minecraft

Throw and Throws Keywords in Java

In java programming, If the exception occurs within the try block it is thrown.

a throw keyword is used to throw an exception

A system-generated exception is automatically thrown by the java run time system but if we want to manually throw an exception, we can do so by using the throw keyword. 

Exception Handling try catch finally blocks in Java

Syntax of throw

           throw    ThrowableInstance;

here, ThrowableInstance must be an object of type Throwable or subclass of Throwable.

Example of throw keyword

In this program new is used to create an instance of NullPointerException and we get two chance to deal with the same error.

In the line  “throw new NullPointerException(“demo”);” 

throw keyword is used to throw  NullPointerException(“demo”). Here we set “demo” is a name of exception.

This NullPointerException(“demo”) catch by catch() method which resides in a demo() method.

 Line “throw e;”  re-throw the exception which is catch by catch() method which resides in a main() method.

Throws Keyword in Java

In a java programming, throws keyword list the type of exception that a method might throw.

throws keyword inform that method throws mentioned exceptions

In the throws clause, we declare all the exceptions that a method can throw.

  Syntax of throws:         

                                               

Here, exception1, exception2 are comma, list of the exception that a method can throw.

Example of throws

Explaination: We throws NullPointerException in the line “throw new NullPointerException(“demo”);” .

Here we set “demo” is a name of thread.

This line “throw new NullPointerException(“demo”);” throw the exception which is handled by catch block associated with try within main().

Difference between throw and throws in Java (throw vs throws)

throw keyword is used to throw an exception from method or from a block

throw is used inside method

throw new NullPointerException("demo");

throws keyword is used to inform that a method throws exception(s)

thorws keyword i s used in method header

public Scanner​(File source) throws FileNotFoundException

What is the purpose of the throw statement?

Throw is used to throw an exception from a method or from block of code

what is the difference between throwing an exception and catching an exception?

Throwing an exception can use to throw an exception using the throw keyword.

this can be implicit or explicit

45/0 <- throw ArithmeticException 

throw ArithmeticException(“Denominator can not be zero”);

To catch an exception one or more catch blocks can be used so that program executes properly.

The ______ keyword is used to manually throw an exception in java

The Throw keyword is used to manually throw an exception.

Read More

  1. Exception Handling in Java: Hierarchy Example and Types
  2. Exception Handling in Java with Examples
  3. Exception Handling try catch finally blocks in Java

Reference

How to Throw Exceptions

            

User Defined (Custom) Exceptions in Java with Examples

In Java programming, it is possible to create our own exception and such exception are called user defined exception in Java.

Exception class is a predefined class. Any user defined exception created by us must be a subclass of the predefine Exception class and created by extending the Exception class.

Read More

  1. Exception Handling in Java: Hierarchy Example and Types
  2. Exception Handling in Java with Examples
  3. Exception Handling try catch finally blocks in Java
  4. Throw and Throws Keywords in Java

What is user defined (custom) exception in java

An Exception that is defined by the user/ programmer is known as user defined or custom exception.

example

  1. Checking user age if not valid age throw an exception
  2. If not in a specified time period then throw an exception
  3. If the user name and password is incorrect then throw an exception

All above exceptions are created by the user and throw when required.

How to throw user defined exception in java

 The throw and throws keyword are used for implementing user defined exception. 

throw: throw keyword is used to throw an exception explicitly from a method or from a block.   

for instance

 Here new NumberIsGreaterException();

is creating new exception and throwing it.

throws: throws keyword is used with method signature that informs that the method can throw mentioned exception.   

Here Scanner is class and above mentioned Scanner represents the constructor call, On the constructor call of above we have to handle File not found Exception.

how to create user defined exception in java

  1. Create a class
  2. Extend the Exception class
  3. Create a String argument constructor to pass custom message.

Examples of User Defined Exception in Java

Example1:   write a program to take a number from user by using command line argument during run time. if user will enter  more than 100 then grnerate user defined exception MyException.

Explaination: In the above program, name of user define exception is NumberIsGreaterException. 

In the above program user enter  the number 111 during run time using command line argument.

Here value of “m” is greter than 100 therefore  “throw  newNumberIsGreaterException ();” this throw statement throw the exception and catch by catch block, but before thorw “NumberIsGreaterException ()” constructer will call.

User defined exception in java program to check age is valid or not

InvalidAgeException.java

CheckAge.java

Output

user defined exception in java example to check a time is in range or not, if time is not in range then throw custom exception

InvalidTimeException.java

CheckTime.java

Output

Example: Write a program to create user defined exception in Java to check a given name exists or not. If name doesn’t exists then throw a custom exception.

InvalidNameException.java

CheckName.java

Output

How to write custom exception in java?

or

How to create custom exception in java?

or

How to create your own exception in java?

  1. Create a class
  2. Extend Exception class
  3. Create a constructor to show/pass custom message

Thread Life Cycle in Java

Thread Life Cycle in Java tells the various information of thread form born to terminate.

Thread life cycle contains the several stages and at a time any thread can be present  in a single state.

States of Thread life cycle

  1. Born
  2. Ready
  3. Running
  4. Blocked
  5. Sleep
  6. Wait
  7. Dead
Java Thread Life Cycle
Java Thread Life Cycle

Ready:  In this state thread is ready to execute but not running. 

When the start() method calls thread enters from born to ready state.

Running:  When a run() method executes highest priority ready thread assigned a processor and enter in a running state for execution.

Thread can visit more than ones in a running state.

Blocked: When a running thread has a input-output issue it enters in a blocked state from running state and when input-output issue solves it again comes in a running thread.

Sleep : A running thread enter in a sleep state for a specified number of milliseconds when a sleep() method calls.

When sleep time expires then thread moves to ready state.

Wait : When a low priority thread executing and high priority thread comes then high priority thread get preference and enter in a running state. Then low priority thread leaves a running state and moves to wait state for indefinite time.

When a high priority thread execution completes it calls waiting thread for execution by notify () & notifyall () method.

Dead: A running thread is enter in a dead state when its execution completes (run() method completes)   or terminate for any reason.

Multithreading in java example programs

  1. Created a class Thread1 that extends Thread class
  2. main() creates two thread t1 and t2.
  3. To start thread start method is called t1.start() and t2.start()
  4. Start method calls the run method to execute the work
  5. Thread.sleep() send thread to sleep state for 500 milliseconds
  6. From sleep state thread come back to ready then running state
  7. After completing work thread get dead.

Read More

Multithreading in Java

Multithreading in Java Thread Creation Method Use Example

Multithreading in Java

1 What is a Thread in Java

A thread is light weight process that can execute simultaneously. Multithreading in java allows multiple threads to run simultaneously.

  • A program can be divided into two or more parts that can run concurrently and each part of such program is known as thread.
  • In a simple word, thread is a lightweight sub-process.
  •  It is a smallest unit of processing.
  • When these threads execute concurrently for accomplishing a task is known multithreading.
  • In multithreading, each thread defines a separate path of execution. 
  • In multithreading, every thread has a priority between 1 to 10. Thread with highest priority get preference over lower priority thread for execution.
Java Process and Thread Diagram
Fig: Java Process and Thread Diagram

 In a java programming, Thread is a predefined class within a java.lang package.

Operating system (OS) can contain multiple process, in the above figure, there are three process  P1,P2 & P3, within OS and within P3 process there are three threads T1, T2& T3. There is context-switching between the threads.  

2 Difference between Process and Thread

Difference between Process and Thread
ProcessThread
A process has their own virtual address space.Threads are entities within a process it uses its virtual address space of process.
Two processes running on the same system at the same time do not uses address space.Two threads running within a process uses the same address space.
Every process has its own data segmentAll threads within the process uses the same data segment of process.
In multiprocessing, processes use inter process communication techniques to interact with other processes.In multithreading, threads do not uses inter process communication techniques because they not uses separate address spaces. They share the same address space therefore, they can communicate directly with other threads within process.
Processes have considerable overhead.Threads have almost no overhead;
Process is heavy weight.Threads are light weight process (LWP).
Process contains much information about system, resource.Threads carry less state information than process
When we create a child process from a parent process then it requires duplication of the resources of parent process.No duplication of resources is required when we create a child thread from main thread.

3 How to create a thread in Java

We can create a thread by two ways:

  1. By extending Thread
  2. By implementing Runnable interface
How to create a thread in Java
Fig: How to create a thread in Java

Lets see multithreading in java with example

A Creating Thread By Implementing Runnable Interface

  1. We can create a thread by creating a class that implements the Runnable interface.
  2. To implement Runnable, a class only need to implement a single method called run().
  3. Inside run () we will define the code that constitute the new thread.    
  4. When a new thread creates, it do not executes until we call its start () method. When start () method executes it call to run() method.  

Below is the multithreading program in java with implementing runnable interface

Example: Print hello to illustrate multithreading example in java

Output

Creating more than one thread in java :- multithreading in java example

Output

Another Example of Thread is

Result

Description:

Passing “this” as a argument, “DemoThread” is the name of the thread.  

In this program, main thread fineshes last because the main thread sleeps for 1000 milliseconds (1 seconds) between iteration, but the child thread sleeps for only 500 milliseconds.

This cause the child thread terminates earlier than main thread.

B Creating Thread By extending Thread class in java

  1. To create a thread we will create a thread a class that extends Thread class.
  2. To extend Thread class, a class only needs to implement a single method called run (). This extending class must override the run() method
  3. Inside run () we will define the code that constitute the new thread.                                                                                 
  4. When a new thread creates, it do not executes until we call its start () method. When start () method executes it call to run() method.

Simple Thread example in java

Example: Write a thread program in java by extending thread class.

Multithreading in Java example programs

Example: Write a program to show multithreading in java by extending thread class

Multithreading in java example using Thread class

Result

4 Thread Methods in Java

Commonly used methods of Thread class are as follows

Sr NoMethod and Description
1void run()
Work execute as a thread is defined in this method .
2void start()
Used to start a thred which Calls the run() method of the thread or child class.
3static void sleep(long miliseconds)
Suspend the thread for specified amount of time.
4static void sleep(long miliseconds,int nanos)
Suspend the thread for specified amount of time.
5void join()
This method is used to pause the ececution of current thread until it die. void join().
6 void join(long miliseconds)
Pause the execution of current thread for the pecified miliseconds.
7void join(long miliseconds,int nanos)
Pause the execution of current thread for the pecified miliseconds and nano seconds.
8 boolean isAlive()
To checks a thread is alive or not.
9 String getName()
Returns the name of the thread.
10 setName(String name)
Used to set the name of thread.
11 int getPriority()
Get the priority of the thread.
12 void setPriority(int priority)
Set the priority of thread.
13 static Thread currentThread()
Returns the reference of currently executing thread
14 long getId()
Returns the id of the thread.
15 static void yield()
Temporarily pause the currently executing thread and allow other threads to execute.
16 void suspend()
Used to suspend the thread.
17 void resume()
Used to resume the suspended thread.
18 void stop()
Used to stop the thread.
19 void interrupt()
Interrupts the thread.
20 boolead isInterrupted()
Check whether the thead is interrupted or not

Use of thread in java

  1. To Reduce the time of execution of a program
  2. To achieve parallel execution

Read More

Thread Life Cycle in Java

How many ways to create thread in java

There are two ways to create thread in java

  1. By Extending Thread class
  2. By Implementing runnable Interface.

Types of thread in java

  1. Daemon thread provide services to other threads
  2. User defined threads Created by User

How to perform two tasks by two threads ?

Real time example of multithreading in java

  1. When two or more I/O operations are not dependent of each other then we can perform them by different threads.
  2. When tow or more Database read/write operations are not dependent then we can perform using multithreads.
  3. Sending OTP on mobile and email id at same time.
  4. Adding post on social media (fb, twitter, pintrest etc) on one click using publisher software.
  5. Servers are multithreaded they create separate thread to handle each request.

Java multithreading programming exercises

  1. Create Two threads using Thread class.
  2. Create Two threads using runnable Interface.
  3. Implement Produces consumer problem in Java.

Packages in Java -Types Sub Packages and Examples

Packages in Java is one of the important concept. All Java classes and interfaces are arranged in package structure.

What is package in java

Packages is a namespace which contains related classes and Interfaces.

The methods and field of class define inside the package can be accessible in package outside package and in child classes based on access specifier.  

Packages are stored in a hierarchical manner and explicitly imported into a new class definition.

Types of packages in java

Java packages are classified into two types

  1. Predefined or Built-in package
  2. User defined package

1 Java API(Application Programming Interface) packages or Predefined packages or Built-in packages

These packages are defined by the system. Some example of system defined packages are

  1. java.lang: It contains fundamental classes like System, String Math, Number etc. This is the default package in java.
  2. java.util: This package contains collections framework, legacy collection classes, event model and other features.
  3. java.io: Provides system input output with stream classes and files
  4. java.awt: Contain classes for creating user interface graphic and Image classes.
  5. java.net: Contains classes related to networking and sockets
    The Java 1.3 contains nearly 60 predefined packages

Importing packages in Java with Example

import java.util.Scanner; -To import Scanner class

import java.util.*; To import all classes in util package

Here we import is used to import java.util.Scanner;

2 User defined packages in java

These packages are defined by the user.

How to create package in java

Defining as packages: To define a package, place “package” command as the first statement in the source file.

The syntax of packages creation :-

  • The class that is defined in the package must be public. So that is can be accessible by any another of them.
  • Java uses the file system file directories to store packages. We save the program with number.java and compile the package is as javac_d/number.java. Due to this compilation Mypackage directory is automatically created and .class file is stores in that directory.

Once the package creation has completed. Then the package information is including with the help of “import” keyword.  import keyword links the package with our program.

Java Package Example

It is place before the class definition:

Java Package
Java Package Example
  • In this program, package is within x folder and main program is within y folder in c drive.
  • Package name in this program is x.
  • File name and package class name must be same ex: (number.java- source file).

How to compile package in java

c:\> javac folder/filename.java

c:\>java package.filename

Note: If we want to access all the classes of information then the classes are stored in different files with the same package name.

Sub Packages

In Java, it is possible to create a sub packages for the main packages.

Syntax

                 package  pack1.pack2;  

Where pack1 is the main package and pack2 is the sub package.

Java packages sub package example

Result

How many predefined packages in java

As per different java versions there are different packages and classes this SO question is also helpful.

We Inspected javase 14 and find there are 225 predefined packages / sub packages in java.

Which Package is default package in java

The package which is not required to import explicitly is known as default package.

If we write simple program to print hello then there we use System, String class we don’t need to import that. These are defined in java.lang package.

Default Package in Java is java.lang

Which keyword is used for accessing the features of a package

The import keyword is used for accessing the features of a package.

We can import classes and interfaces in our current file using import.

What is Import in Java

Import in a keyword in java. We use import statement to import class or all classes from a package.

How to import a package in java

import java.util.Date; or
import java.util.*;

How to create a package in java (Steps to create package in java with example)

  1. Create a folder with package name
  2. Create java files inside folder
  3. each java files include package definition package packagename;

packages in java with example program 

How to run package program in java (How to execute package in java)

compile d:\>javac foldername/filename.java
run d:\>java packagename.filename

What is java lang package in java

java lang (java.lang) is default package in Java. It contains fundamental classes.

Use of packages in java

  1. Group related classes and interfaces
  2. To avoid Naming conflicts
  3. To provide Access Control

Example of predefined packages in java

Predefined packages are defend by Java Team like

  1. java.lang (default package)
  2. java.util
  3. java.io
  4. java.net
  5. java.math
  6. java.sql
  7. java.time
  8. java.awt
  9. java.text

view all

The package which should be created to categorize the package further

The package which should be created to categorize the package further is sub package

java package java.

sub packages java.land, java.util etc.

Which of the following is used to avoid naming conflicts?

  1. class
  2. Interface
  3. package
  4. templet

Answer is package

Reference

Java Package


JButton in Java Swing with Examples

JButton in Java is defined in javax.swing package .

JButton in child of javax.swing.AbstractButton.

public class JButton
extends AbstractButton
implements Accessible

To create instance of JButton many constructors are provided.

JButton Consturctor

Sr NoConstructors and Description
1JButton()
Creates a button with no set text or icon.
2JButton(Action a)
Creates a button where properties are taken from the Action supplied.
3JButton(Icon icon)
Creates a button with an icon.
4JButton(String text)
Creates a button with text.
5JButton(String text, Icon icon)
Creates a button with initial text and an icon.

Let us see all constructors one by one.

Commonly used AbstractButton methods

Sr NoMethod and Description
1String getText()
get the text of Button
2void setText​(String text)
Sets the button’s text.
3Icon getIcon()
Get the icon of Button
4void setIcon​(Icon defaultIcon)
Set the icon on button
5void addActionListener​(ActionListener l)
Add an action listener to a button
6void setEnabled​(boolean b)
Enable or disable the button based on boolean argument
7void setMnemonic​(int mnemonic)
Set the keyboard Mnemonic for button

Java JButton Examples

How to add Icon to JButton in Java

JButton in Java with constructor
Fig: JButton in Java with constructor

JButton Click and ActionListner Example

JButton Click and ActionListner Example
Fig: JButton Click and ActionListner Example

ActionCommand and Mnemonic Example in JButton

ActionCommand and Mnemonic Example in JButton
Fig: ActionCommand and Mnemonic Example in JButton

Image source https://freeicons.io/

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

  1. JLabel in Java Swing
  2. JComboBox in Java Swing
  3. JTable in Java Swing
  4. JTable Pagination in Java JDBC
  5. Registration Form in Java Swing
  6. Login form in Java Swing
  7. Simple Calculator in Java Applet
  8. Applet Life Cycle in Java