ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

Updated on October 16, 2019
dwachira profile image

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

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 | Source

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.

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:

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());
    }
}

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());
    }
}

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 >>

Comments

    0 of 8192 characters used
    Post Comment
    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi Bala,

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

    • profile image

      Bala 

      7 years ago

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

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      @kidscrafts,

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

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      @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.

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

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

    • profile image

      faizal tahir 

      7 years ago

      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?

    • profile image

      james 

      7 years ago

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

    • kidscrafts profile image

      kidscrafts 

      7 years ago from Ottawa, Canada

      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!

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      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.

    • billybuc profile image

      Bill Holland 

      7 years ago from Olympia, WA

      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.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)