Updated date:

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 53

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

Table of Contents

<< Lesson 52 | Lesson 54 >>

Lesson 53: How to code for table navigation buttons in Java NetBeans

This far so good, you are able to connect to a database and table in Java NetBeans and you are able to populate a Java form with records from the table.

We’ll now learn how to code for record navigation buttons in Java to make it easy for users to naviagate through records.

From the form we had in previous lesson, we added navigation buttons to navigate to First, Previous, Next and Last record. We also added record manipulation buttons to Delete record, add New record and Save record.

Java Table Navigation Buttons

Java Table Navigation Buttons

To begin with, we’ll start by coding for record navigation buttons starting with the Next button.

The Next button is a forward navigation control that enables application users to move to the next records.

You can customize navigation buttons to have a text caption, image caption or both. So far, here is the current Java form with table records in run mode.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-53

To code for Next button, we need to know if there is a next record and if so, we move record Cursor to the next record and populate the form text fields with values from that record. We can use IF … ELSE statement to check if there is a next record.

The entire code for Next button is better embedded inside a try … catch block to handle navigation errors when they occur. If there is no next record, we just move back one step since the record Cursor would have moved past the last record. The try … catch block with IF … ELSE statement should look as follow:

try {
if ( Rset.next( ) ) {

}
else {
Rset.previous( );
JOptionPane.showMessageDialog(this, "End of File");
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(this, err.getMessage());
}

What we have above is an empty IF … ELSE statement inside try … catch block. The code to navigate next is not included but basically it should be a familiar code that you have met before. Include the following code from previous lesson and run the form.

package database_connect;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
public class StudForm extends javax.swing.JFrame {
        Connection conn;
        Statement state;
        ResultSet Rset;

    public StudForm() {
        initComponents();
        DoConnect();
    }
    public void DoConnect( ) {
       try{
        String host = "jdbc:derby://localhost:1527/School";
        String dName = "admin";
        String dPass = "admin";
        Connection conn = DriverManager.getConnection( host, dName, dPass );
        Statement state = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        String SQL = "SELECT * FROM APP.Students";
        ResultSet Rset = state.executeQuery( SQL );
       
        Rset.next( );
        int Id = Rset.getInt("StdID");
        String Id2 = Integer.toString(Id);
        String sName = Rset.getString("StdName");
        String sFaculty = Rset.getString("Faculty");
        String sCourse = Rset.getString("Course");
        String sCity = Rset.getString("City");
        String sAddress = Rset.getString("Address");
        String sTelephone = Rset.getString("Telephone");
        String sRemarks = Rset.getString("Remarks");
        
        txtID.setText(Id2);
        txtName.setText(sName);
        txtFaculty.setText(sFaculty);
        txtCourse.setText(sCourse);
        txtCity.setText(sCity);
        txtAddress.setText(sAddress);
        txtTelephone.setText(sTelephone);
        txtRem.setText(sRemarks);
       }
   catch ( SQLException err ) {
        System.out.println( err.getMessage( ) );
  }
}
                                      
private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {                                        
try {
    if(Rset.next( )){
        int Id = Rset.getInt("StdID");
        String Id2 = Integer.toString(Id);
        String sName = Rset.getString("StdName");
        String sFaculty = Rset.getString("Faculty");
        String sCourse = Rset.getString("Course");
        String sCity = Rset.getString("City");
        String sAddress = Rset.getString("Address");
        String sTelephone = Rset.getString("Telephone");
        String sRemarks = Rset.getString("Remarks");
        
        txtID.setText(Id2);
        txtName.setText(sName);
        txtFaculty.setText(sFaculty);
        txtCourse.setText(sCourse);
        txtCity.setText(sCity);
        txtAddress.setText(sAddress);
        txtTelephone.setText(sTelephone);
        txtRem.setText(sRemarks);
    }
    else {
        Rset.previous( );
        JOptionPane.showMessageDialog(this, "End of File");
    }
    }
   catch (SQLException err) {
        JOptionPane.showMessageDialog(this, err.getMessage());
    }
}                                       

Does the form run as expected? It is a BIG NO! Trying to run the form with the above code will throw a lot of errors. Why all the errors? you ask, we’ll find in a moment.

Java Variable Hiding Error

Errors caused by variable hiding in Java programming are tricky to note especially for beginners, in fact searching on Google for "Java variable hiding" will bring up a lot of explanations on this tricky error. The form is throwing errors because we have some local variables in a method (in this case, the DoConnect( ) method) hiding fields or global variables. Take a look on the image below:

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-53

In the image above, we have 3 field variables declared in the form, these are:

Connection conn;

Statement state;

ResultSet Rset;

But notice we are re-declaring these variables again in the method DoConnect() therefore hiding the field variables with local variable whose scope is limited to the method only.

Doing so will cause the ResultSet Rset to have a null value because it would appear like we are declaring a new variable for ResultSet.

In this case, the errors are from the ResultSet Rset in the method DoConnect() because we are trying to force the record Cursor to navigate Next through null values.

To resolve the error, remove variable hiding to un-null ResultSet Rset by writing ResultSet Rset just as Rset in the method DoConnect() i.e. without the object name.

To be safe, do the same to the other hidden variables and your code should now look as shown below. Try the form now and this time it should work and you should be able to scroll records forward without errors.

package database_connect;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
public class StudForm extends javax.swing.JFrame {
        Connection conn;
        Statement state;
        ResultSet Rset;

    public StudForm() {
        initComponents();
        DoConnect();
    }
    public void DoConnect( ) {
       try{
        String host = "jdbc:derby://localhost:1527/School";
        String dName = "admin";
        String dPass = "admin";
        conn = DriverManager.getConnection( host, dName, dPass );
        state = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        String SQL = "SELECT * FROM APP.Students";
        Rset = state.executeQuery( SQL );
       
        Rset.next( );
        int Id = Rset.getInt("StdID");
        String Id2 = Integer.toString(Id);
        String sName = Rset.getString("StdName");
        String sFaculty = Rset.getString("Faculty");
        String sCourse = Rset.getString("Course");
        String sCity = Rset.getString("City");
        String sAddress = Rset.getString("Address");
        String sTelephone = Rset.getString("Telephone");
        String sRemarks = Rset.getString("Remarks");
        
        txtID.setText(Id2);
        txtName.setText(sName);
        txtFaculty.setText(sFaculty);
        txtCourse.setText(sCourse);
        txtCity.setText(sCity);
        txtAddress.setText(sAddress);
        txtTelephone.setText(sTelephone);
        txtRem.setText(sRemarks);
       }
   catch ( SQLException err ) {
        System.out.println( err.getMessage( ) );
  }
}
                 
private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {                                        
try {
    if(Rset.next( )){
        int Id = Rset.getInt("StdID");
        String Id2 = Integer.toString(Id);
        String sName = Rset.getString("StdName");
        String sFaculty = Rset.getString("Faculty");
        String sCourse = Rset.getString("Course");
        String sCity = Rset.getString("City");
        String sAddress = Rset.getString("Address");
        String sTelephone = Rset.getString("Telephone");
        String sRemarks = Rset.getString("Remarks");
        
        txtID.setText(Id2);
        txtName.setText(sName);
        txtFaculty.setText(sFaculty);
        txtCourse.setText(sCourse);
        txtCity.setText(sCity);
        txtAddress.setText(sAddress);
        txtTelephone.setText(sTelephone);
        txtRem.setText(sRemarks);
    }
    else {
        Rset.previous( );
        JOptionPane.showMessageDialog(this, "End of File");
    }
    }
   catch (SQLException err) {
        JOptionPane.showMessageDialog(this, err.getMessage());
    }
}
programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-53

Code For Previous Button (Table Backward Navigation)

Coding for Previous button will be easy now, you only need to copy the code we have in the Next button and make minor changes. The Rset.next() in the IF part of the IF … ELSE statement should be replaced by Rset.previous() and the Rset.previous() in the ELSE part of the IF … ELSE statement should be replaced by Rset.next(), simply, we are doing the opposite of Next button. Here is the code for Previous button. Notice we have also modified the message in JOptionPane dialog box to “Start of File” instead of “End of File.”

private void btnPrevActionPerformed(java.awt.event.ActionEvent evt) {
try {
    if(Rset.previous( )){
        int Id = Rset.getInt("StdID");
        String Id2 = Integer.toString(Id);
        String sName = Rset.getString("StdName");
        String sFaculty = Rset.getString("Faculty");
        String sCourse = Rset.getString("Course");
        String sCity = Rset.getString("City");
        String sAddress = Rset.getString("Address");
        String sTelephone = Rset.getString("Telephone");
        String sRemarks = Rset.getString("Remarks");
        
        txtID.setText(Id2);
        txtName.setText(sName);
        txtFaculty.setText(sFaculty);
        txtCourse.setText(sCourse);
        txtCity.setText(sCity);
        txtAddress.setText(sAddress);
        txtTelephone.setText(sTelephone);
        txtRem.setText(sRemarks);
    }
    else {
        Rset.next( );
        JOptionPane.showMessageDialog(this, "Start of File");
    }
    }
   catch (SQLException err) {
        JOptionPane.showMessageDialog(this, err.getMessage());
    }
}
programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-53

Coding for First and Last Buttons Navigation

There is nothing major when coding for buttons to move to the First record and Last record. All we want is to jump to the first or last record respectively, so we can use first() and last() methods. We don’t even need the IF … ELSE statement. Below is the code for First and Last buttons. Adjust your form code accordingly.

Coding for First Button Navigation

private void btnFirstActionPerformed(java.awt.event.ActionEvent evt) {
try {
        Rset.first( );
        int Id = Rset.getInt("StdID");
        String Id2 = Integer.toString(Id);
        String sName = Rset.getString("StdName");
        String sFaculty = Rset.getString("Faculty");
        String sCourse = Rset.getString("Course");
        String sCity = Rset.getString("City");
        String sAddress = Rset.getString("Address");
        String sTelephone = Rset.getString("Telephone");
        String sRemarks = Rset.getString("Remarks");
        
        txtID.setText(Id2);
        txtName.setText(sName);
        txtFaculty.setText(sFaculty);
        txtCourse.setText(sCourse);
        txtCity.setText(sCity);
        txtAddress.setText(sAddress);
        txtTelephone.setText(sTelephone);
        txtRem.setText(sRemarks);
    }
   catch (SQLException err) {
        JOptionPane.showMessageDialog(this, err.getMessage());
    }
}

Coding for Last Button Navigation

private void btnLastActionPerformed(java.awt.event.ActionEvent evt) {                                        
try {
        Rset.last( );
        int Id = Rset.getInt("StdID");
        String Id2 = Integer.toString(Id);
        String sName = Rset.getString("StdName");
        String sFaculty = Rset.getString("Faculty");
        String sCourse = Rset.getString("Course");
        String sCity = Rset.getString("City");
        String sAddress = Rset.getString("Address");
        String sTelephone = Rset.getString("Telephone");
        String sRemarks = Rset.getString("Remarks");
        
        txtID.setText(Id2);
        txtName.setText(sName);
        txtFaculty.setText(sFaculty);
        txtCourse.setText(sCourse);
        txtCity.setText(sCity);
        txtAddress.setText(sAddress);
        txtTelephone.setText(sTelephone);
        txtRem.setText(sRemarks);
    }
   catch (SQLException err) {
        JOptionPane.showMessageDialog(this, err.getMessage());
    }
}  

Run the form and at this point, the first four navigation buttons should be working. These are the most common record navigation movements in any database application and being able to code this far is an achievement in Java programming. As you might have noticed, we have duplicated big chunks of code which is not necessary.

A good programming convention to avoid code duplication would be to create a method that we’ll keep on calling every time we need such code, i.e. we should not have a lot of duplicated code in the program but for beginners, this will do for now. In the next lesson, we shall tackle on Delete, New, Save and Update buttons.

<< Lesson 52 | Lesson 54 >>

Other related Hubs...

  • How to work with Java Option Panes in Java NetBeans
    This tutorial discusses how to accept user inputs and how to display outputs using JOptionPane class in Java NetBeans. User input and output dialog boxes are very useful in Java NetBeans programming.
  • How to handle user inputs in Java NetBeans
    This tutorial discusses how to handle user inputs in Java NetBeans using the Scanner class of the Java library and how get and display user inputs in Java NetBeans programming.
  • Java Programming: Java NetBeans and Databases
    Creating databases and tables in Java and how to manipulate databases in Java using API is one of the “must have” skills for Java programmers. This article discusses how to work with Java JDBC and Java DB database.
  • Working with Java NetBeans GUI controls: Combo box
    Java NetBeans provides different Graphical User Interface (GUI) controls which can visually simplify programming and enhance the functioning and user-friendliness of the final application.

Comments

Danson Wachira (author) from Nairobi, Kenya on April 30, 2013:

Hi Bala,

Thanks for the visit and comment, your request is noted and will be considered.

Bala on April 28, 2013:

Hi, thanks for adding lesson 53 data navigation. Will you pl post how to work with multiple table and do navigation.

Danson Wachira (author) from Nairobi, Kenya on April 27, 2013:

@kidscrafts,

Thanks for stopping here and commenting. I also do hope that this tutorial will help some students somewhere. Have a good weekend too.

Danson Wachira (author) from Nairobi, Kenya on April 27, 2013:

@faizal tahir,

If you are using MySQL as backend then you need to have a rs2xml.jar file in your project to access jTable data. Usually, the DbUtils object is used to set the results of jTable dataset. To include this jar file in the project we use: import net.proteanit.sql.DbUtils; If you have a jTable named say jTable1 and a ResultSet named say Rset, then you can set the results of the jTable using the statement: jTable1.setModel(DbUtils.resultSetToTableModel(Rset)); I hope this help. Thanks for the visit and comment.

Danson Wachira (author) from Nairobi, Kenya on April 27, 2013:

@james, More lessons coming up soon, keep reading. Thanks for the visit and comment.

faizal tahir on April 26, 2013:

dwachira.. can i ask a little bit? if we want to populate jtable from database... we must download rs2xml..? why? what it does? and what is import net.proteanit.sql.dbutils?

james on April 26, 2013:

im looking forwaRd to watch your next lesson... very interesting topic..

kidscrafts from Ottawa, Canada on April 26, 2013:

Your Java NetBeans hub is well organized with the code and pictures as usually! You are for sure helping a lot of people! I hope they appreciate it!

Have a great weekend!

Danson Wachira (author) from Nairobi, Kenya on April 26, 2013:

Hi Bill,

Thanks a lot and do have a nice one too. If i can share some knowledge with aspiring programmers and pass some help then am more than rewarded here. I appreciate the visit and comment.

Bill Holland from Olympia, WA on April 26, 2013:

I just wanted to stop by and wish you a wonderful weekend my friend, and tell you that you do a great job with these instructional hubs.

Related Articles