Updated date:

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

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

Table of Contents

<< Lesson 55 | Lesson 57 >>

Lesson 56: How To Code For Save And Delete Buttons In Java NetBeans

So far, you have been able to code for table navigation buttons: First, Next, Previous and Last record navigation buttons. We have also coded for an Update button to successfully update a table in Java NetBeans.

In the previous lesson, we discussed on how to code for New and Cancel buttons which are important when inserting a new record into a table. To make the form user-friendly, we let the user know what action to execute on the form by enabling or disabling buttons appropriately.

How To Code For Save And Delete Buttons In Java NetBeans

How To Code For Save And Delete Buttons In Java NetBeans

A database application will not be complete without an option to save a record and an option to delete a record. These two functions go hand in hand and they are some of the most delicate operations in any application.

In this lesson, we shall learn how to code for Save button to save a new record and how to code for Delete button for deleting an existing record in Java NetBeans programming. Below is the form we are working on up to this point.

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

How To Save A New Record In Java NetBeans Programming

To insert a new record into a table in Java NetBeans, we have to position the Cursor to a new empty insertion row.

We begin by creating a blank row in ResultSet where we insert this new record before committing it permanently in the table. To create a blank row in ResultSet, we use the following statement.

Rset.moveToInsertRow( );

We then get the new data from the form text fields but before we can update ResultSet, we need to check if the user has entered the required details and avoid saving an empty record. We can check this using IF … ELSE statement with OR (||) logical operators. If the required data is entered, we first update ResultSet and them insert and commit the new record in the table.

Rset.insertRow( ); //Insert row into table

Rset.close( ); //Close ResultSet

state.close( ); //Close connection

From the above code, notice that we are also closing ResultSet and Connection. This is because the type of Connection Driver we have used (ClientDriver) require closing of connection after committing a record otherwise we might risk not saving a record.

Since we still need to maintain our form with data, what we’ll do is to re-load data from the table and populate the form again preferably from the last record.

The last bit of code in the Save button is to enable or disable appropriate buttons ready for next user’s action. Here is the complete code for Save button, you can just copy and paste inside the Save button code stub.

Save button code for saving new records in Java NetBeans

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
    //Get data from form text fields
    String newId = txtID.getText( );
    String newName = txtName.getText( );
    String newFaculty = txtFaculty.getText( );
    String newCourse = txtCourse.getText( );
    String newCity = txtCity.getText( );
    String newAddress = txtAddress.getText( );
    String newTelephone = txtTelephone.getText( );
    String newRem = txtRem.getText( );

    //Check if user has entered required data
if(newId.equals("")||newName.equals("")||newFaculty.equals("")||newCourse.equals("")
        ||newAddress.equals("")||newTelephone.equals("")){
    JOptionPane.showMessageDialog(this, "Please enter required details");
}else{
    int newId2 = Integer.parseInt( newId ); //Change ID to int before saving

    try {
        //Update ResultSet with new data
        Rset.moveToInsertRow( );
        Rset.updateInt( "STDID", newId2 );
        Rset.updateString( "STDNAME", newName );
        Rset.updateString( "FACULTY", newFaculty );
        Rset.updateString( "COURSE", newCourse );
        Rset.updateString( "CITY", newCity );
        Rset.updateString( "ADDRESS", newAddress );
        Rset.updateString( "TELEPHONE", newTelephone );
        Rset.updateString( "REMARKS", newRem );
    
        Rset.insertRow( ); //Insert row into table
        Rset.close( ); //Close ResultSet
        state.close( ); //Close connection 
    
        //Re-load table data
        state = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        String SQL = "SELECT * FROM APP.Students";
        Rset = state.executeQuery( SQL );
       
        Rset.last( ); //Got to last record and get data
        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");
        
        //Populate form with data again
        txtID.setText(Id2);
        txtName.setText(sName);
        txtFaculty.setText(sFaculty);
        txtCourse.setText(sCourse);
        txtCity.setText(sCity);
        txtAddress.setText(sAddress);
        txtTelephone.setText(sTelephone);
        txtRem.setText(sRemarks);
    
        //Disable/Enable appropriate buttons
        btnFirst.setEnabled( true );
        btnPrev.setEnabled( true ) ;
        btnNext.setEnabled( true );
        btnLast.setEnabled( true );
        btnUpdate.setEnabled( true );
        btnDel.setEnabled( true );
        btnNew.setEnabled( true );
        btnSave.setEnabled( false );
        btnCancel.setEnabled( false );

        JOptionPane.showMessageDialog(this, "Record saved successfully");
        }
    catch (SQLException err) { //Handle errors here
        JOptionPane.showMessageDialog(this, err.getMessage( ));
        }
    }
}  

Notice that in the above code, the try … catch block is inside the IF … ELSE statement in the ELSE part. This is so because we want to abort saving of record if user has not entered the required details. Run the form now and you should be able to save new records.

After adding a few records, you can close the form and check the table in the database to confirm that the records are posted and saved although this is absolutely not necessary.

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

How To Delete A Record In Java NetBeans Programming

To delete a record, we can use the deleteRow() method of ResultSet using the following statement.

Rset.deleteRow( );

Again, the issue of Connection Driver comes up. For this type of driver, if we delete a record using the above statement and leave it at that, we’ll end up with a blank row in the table.

Moving Next or Previous through records on the form will display a blank row which should not be the case. We can resolve this just like we did when we saved a record.

After deleting a record we need to close ResultSet and Connection and then re-load data and populate the form again. Here is the complete code for Delete button. Notice in the code that we are asking the user using JOptionPane to confirm deletion of a record. If the user select "Yes" we delete the record. The try ... catch block is inside the IF statement.

Delete button code for deleting records in Java NetBeans

private void btnDelActionPerformed(java.awt.event.ActionEvent evt) {                                       
//Ask user to confirm record deletion
int temp = JOptionPane.showConfirmDialog(null, "Delete record?" , "Confirm deletion" , JOptionPane.YES_NO_OPTION);
if (temp == 0) //Here we check which option was selected by user: Yes = 0
{
  try {
      Rset.deleteRow( ); //Delete table record
      Rset.close( ); //Close ResultSet
      state.close( ); //Close connection 
    
      //Re-load table data
      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");
        
      //Populate form with data again
      txtID.setText(Id2);
      txtName.setText(sName);
      txtFaculty.setText(sFaculty);
      txtCourse.setText(sCourse);
      txtCity.setText(sCity);
      txtAddress.setText(sAddress);
      txtTelephone.setText(sTelephone);
      txtRem.setText(sRemarks);
      JOptionPane.showMessageDialog(this, "Record deleted successfully");
      }
  catch (SQLException err) { //Handle errors here
      JOptionPane.showMessageDialog(this, err.getMessage());
      }
   }
}  
programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-56
programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-56
programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-56

As you can see from the above images, we are able to successfully delete record 1 from the table. If you have been with this Java programming tutorial since Lesson 1, then you have gained valuable fundamental programming skills in Java NetBeans. The trick to being a good programmer is to practice and practice until you get used to coding and syntax.

With the knowledge that you have acquired here, I believe you can develop a simple database application using Java NetBeans without any problem. I would recommend that you move to the next level and learn advanced programming in Java NetBeans. Over the coming lessons, we shall develop various Java applications and projects using most of the knowledge acquired from this tutorial. I hope you found this tutorial to be helpful. Please feel free to share this tutorial and help other learners.

<< Lesson 55 | Lesson 57 >>

Other related Hubs...

Comments

Giuseppe on July 27, 2013:

I attended the course on the database and I found them very effective. Thanks for that. Unfortunately the corresponding jar file that I built does not work, since you need to activate java NB within Netbeans 7.3. I ask politely if you can explain how embeded java NB within the application in order to distribute its jar file.

Thanks for your attention.

Danson Wachira (author) from Nairobi, Kenya on July 07, 2013:

These lessons will be provided later.

Wolfgang on June 17, 2013:

Hi,

I try to learn Java together with Netbeans and found your tutorial. It is the best I found. I´m a German, my English is not the best, Java and Netbeans new. But after working through your tutorial I feel that I know the basics.

At the end of lesson 56 you talke about coming lessons. Where can I find them?

Wolfgang

Danson Wachira (author) from Nairobi, Kenya on May 02, 2013:

Hi Mida,

I am glad that this tutorial was helpful, i will take your request into consideration and i will let you know. Thanks for the visit and comment.

Danson Wachira (author) from Nairobi, Kenya on May 02, 2013:

Hi kidscrafts,

I have been having some free time of late, i kind of took advantage of that to post a few lessons here, i know they will help when i don't have that time to write. Thanks for stopping by and commenting.

Mida on May 02, 2013:

I have been with you all the way through this tutorial and i want to thank you for you have helped me a lot in programming. I wish if you can do a tutorial in Advanced Java programming, i will be very thankful. You have been an excellent online tutor, THANK YOU!!!

kidscrafts from Ottawa, Canada on May 01, 2013:

You are quite busy these last few days producing your course! Good for you!

Related Articles