ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

Updated on October 23, 2019
dwachira profile image

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

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

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.

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.

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

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

Comments

    0 of 8192 characters used
    Post Comment
    • profile image

      Giuseppe 

      6 years ago

      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.

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      These lessons will be provided later.

    • profile image

      Wolfgang 

      7 years ago

      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

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      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.

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      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.

    • profile image

      Mida 

      7 years ago

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

      kidscrafts 

      7 years ago from Ottawa, Canada

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

    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)