ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

Updated on October 16, 2019
dwachira profile image

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

Lesson 55: Coding For Cancel And Add New Record Buttons In Java NetBeans

After learning how to successfully update a table record in Java NetBeans in the previous lesson, we shall now learn how to code for New and Cancel buttons in Java NetBeans. Any database application should be able to accept new data to be inserted in to a table.

We already have the Save button on the form but we’ll need another button to cancel the process of adding a record in case the user decides so. Create a space on the form preferably next to the New button and drop a button with Cancel as the caption.

How To Code For Cancel And Add New Record Buttons In Java NetBeans
How To Code For Cancel And Add New Record Buttons In Java NetBeans | Source

How To Code For Insert New Record Button In Java NetBeans

Inserting a new record into a table will involve three buttons; New button will be used to clear the form ready for data entry, Save button will be used to insert the new record into a table and the Cancel button will be used to cancel insertion of a new record. Here is the current form now with the Cancel button added.

We’ll need to enable or disable some buttons but to know which buttons to enable or disable and when, we’ll need to understand the logical movement of the user on the form.

When the form loads, all the buttons should be enabled accept Cancel and Save buttons which should be disabled.

The Cancel and Save buttons should only be enabled when New button is clicked which automatically disables all the other buttons including itself so, the user can only save the record or cancel the process.

This follows the logical use of the form: it is impossible for the user to insert a new record while at the same time navigating through the records. We can separate these two operations by enabling or disabling buttons.

Java Control Properties
Java Control Properties

Locate for enabled property for Cancel and Save buttons as shown above and uncheck the enabled checkbox to disable each of them. So, when the form runs Cancel and Save buttons will be disabled as shown below.

When the user click on New button, all buttons including New button should be disabled except Cancel and Save buttons.

We cannot disable these buttons through their properties when the form is running but we can disable them programmatically through a code event in the New button.

Double click on New button to reveal the code stub and add the following code. A value of false means we are disabling the button and a values of true means we are enabling the button.

btnFirst.setEnabled( false );

btnPrev.setEnabled( false ) ;

btnNext.setEnabled( false );

btnLast.setEnabled( false );

btnUpdate.setEnabled( false );

btnDel.setEnabled( false );

btnNew.setEnabled( false );

btnSave.setEnabled( true );

btnCancel.setEnabled( true );

The above code and image show toggling of buttons only but there is more to that. When the user clicks on New button, all text fields should be cleared ready for new record. We need to get the current table row (an integer number) so that if the user happens to click on Cancel button we can re-populate the form with previous data. We’ll create a global Int variable to store the current table row as shown below.

To get the current table row when New button is clicked, we can use the getRow() method of ResultSet as shown below:

curRow = Rset.getRow( );

And to clear any field, we just replace the value with an empty string ("") for example, to clear Name field on the form we use:

textName.setText("");

We can also make data entry easier for users by populating some fields automatically for them.

For example, when the user click on New button, the field for Student ID should be occupied by the next available integer for Student ID. To do this, we just increment the last Student ID by 1 and set this number as the value for Student ID field, see the code below.

Rset.last( ); //Go to last record

int Id = Rset.getInt("StdID")+1; //Increment last record by 1

String Id2 = Integer.toString(Id); //Change integer to string

txtID.setText(Id2); //Set this number as new Student ID

The complete code inside New button should be contained in a try … catch block and should look as shown below:

private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {                                       
try{
    curRow = Rset.getRow( ); //Get current row
    Rset.last( ); //Go to last record
    int Id = Rset.getInt("StdID")+1; //Increment last record by 1
    String Id2 = Integer.toString(Id); //Change integer to string
    txtID.setText(Id2); //Set this number as new Student ID
     //Clear all other text fields ready for new record
    txtName.setText("");
    txtFaculty.setText("");
    txtCourse.setText("");
    txtCity.setText("");
    txtAddress.setText("");
    txtTelephone.setText("");
    txtRem.setText("");
    
    //Disable/Enable appropriate buttons
    btnFirst.setEnabled( false );
    btnPrev.setEnabled( false ) ;
    btnNext.setEnabled( false );
    btnLast.setEnabled( false );
    btnUpdate.setEnabled( false );
    btnDel.setEnabled( false );
    btnNew.setEnabled( false );
    btnSave.setEnabled( true );
    btnCancel.setEnabled( true );
   }
catch (SQLException err) { //Handle any error here
    JOptionPane.showMessageDialog(this, err.getMessage());
   }
}     

Run the form now and the New button should be working as expected. Notice Student ID field has the next available integer for Student ID and that users don't have to type.

How To Code For Cancel Button Or Undo Button In Java NetBeans

The Cancel button will more or less operate to the opposite of New button. Using the row number in variable curRow, we’ll populate the form again with data from the current absolute row and then enable and disable appropriate buttons. This code should be inside a try … catch block. Here is the complete code for the Cancel button.

private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {
try{
    Rset.absolute( curRow ); //Get data from absolute row
    
    //Set data in for text fields
    txtID.setText( Integer.toString( Rset.getInt("STDID" )));
    txtName.setText( Rset.getString("STDNAME") );
    txtFaculty.setText( Rset.getString("FACULTY") );
    txtCourse.setText( Rset.getString("COURSE") );
    txtCity.setText( Rset.getString("CITY") );
    txtAddress.setText( Rset.getString("ADDRESS") );
    txtTelephone.setText( Rset.getString("TELEPHONE") );
    txtRem.setText( Rset.getString("REMARKS") );
    
    //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 );
    }
catch (SQLException err) {
    JOptionPane.showMessageDialog(this, err.getMessage());
    }
}

At this point the Cancel and New buttons should work as expected and they should also be able to synchronize in toggling appropriate buttons. As a test, run the form, click on Next button to record number two, then click on New button and then Cancel button. The form should return to its previous record and enable or disable appropriate buttons as shown above. In the next lesson, we’ll code for Save and Delete buttons.

<< Lesson 54 | Lesson 56 >>

Comments

    0 of 8192 characters used
    Post Comment
    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi kidscrafts,

      Good to hear that you do some programming, probably i should do JavaScript next, i know you can make it with little effort. Thanks for the visit and comment.

    • kidscrafts profile image

      kidscrafts 

      7 years ago from Ottawa, Canada

      I can recognize some of the words in your code because of the course of Java Script I took about 15 years ago.... but without practice it doesn't help. At least, I am still able to work with the code in HTML when things are not going smoothly with Dreamweaver :-)

      I love the way you organize your course.... that's why I suggested an e-book in my other message.

      I wish my Java Script teacher was as organized as you are... that course was a nightmare! The guy was not organized at all :-(

    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)