Java Swing CheckBox Tutorial Using NetBeans

 Java Swing CheckBox tutorial Step by Step

In this tutorial, you will learn to use Java Swing checkboxes in Java using NetBeans IDE. This Java application will show few food items along with their prices. User is asked to select the food items to purchase. On selecting the food items, the bill amount for the selected food items will be displayed as shown in below figure:

Check Boxes showing food items

Bill Amount displayed on selecting any check box

I am using NetBeans IDE for creating Java application. To create this application, follow the below given steps:

  1. Launch NetBeans, select File->New Project option
  2. The Choose Project dialog box will open up. Because, we want to make a Java desktop application, select “Java” option from the Categories pane and “Java Application” option from the Projects pane. Select Next button to move further. The next dialog box will ask the Java application’s name and the location on the drive where we want to create the application. Let us assign the name, “checkBoxDemoApp” to this java application and let it be created at the default location as shown in below figure.
Entering information for the new Java application

Creating a new java application

Click Finish button to create the application. The NetBeans IDE will automatically create a Java class file for you by name, java with some default code. The Projects window will appear as shown below:

Files and packages generated by NetBeans IDE

Projects window showing the auto-generated files and packages

Adding a JFrame Form

To create a GUI (Graphical User Interface) , we will be using Java Swing toolkit. To work with Java Swing toolkit, you need to add a JFrame form to the application. Hence, right click the package, checkboxdemoapp in the Source Packages node in the Projects window and select New->JFrame Form option from the context menu that pops up. You will be asked to specify the class name for the new JFrame form. Let us enter FastFood as the class name. Keeping the rest of text boxes in the dialog box to their default values (see below figure), click Finish button to create a JFrame form.

Adding a JFrame form to the Java application

Adding a JFrame form for creating GUI

A Java class file, FastFood.java file will be added to the project with some default code. The Projects window will now appear as shown below:

Projects window after adding JFrame form to Java application

Projects window after adding JFrame form

Also, a blank JFrame form will be created and opened in Editor window with a toolbar that contains several buttons. We will be working primarily with following two toolbar buttons:

  • Design – This button will enable us to work with GUI components. We can drag GUI components from the Palette window and drop them on the form
  • Source – This button will show the class’s source code. We can write Java code for any component, edit, debug code etc. in this mode

Creating GUI

In this application, we will be requiring two Label components and three Check Box components. Three Check Box components will display three food items along with their price. Out of the two Label components, one will be used for displaying title and the second Label component will be used for displaying the bill amount of the selected food items.

Select the JFrame form i.e. FastFood.java file from the Projects window followed by selecting the Design toolbar button from the Editor tab. Being in Design mode, drag a Label component  from the Swing Controls category of the Palette window and drop it on the JFrame form. Repeat the procedure for the second Label component. Similarly drag a Check Box component from the Swing Controls category and drop it on the JFrame form. Repeat the procedure for two more Check Boxes because we want three Check Box components in this application. To increase visibility of these GUI components, we need to increase their font size. So, select all the five components i.e.  Ctrl+click each component on the JFrame form and select font property from the Properties window. Select the desired font and size as shown in below figure:

After increasing the font size, position the five components on the JFrame form to appear as shown in below figure:

JFrame form with three check box and two label components

Three Check Box and two Label components added to the JFrame form

Setting Java Swing Component’s Properties

Next step is to change the text of these components. You can change the text of any component by either of the following two ways:

  • Right click the component on the JFrame form and select Edit Text option from the context menu that pops up. You can overwrite the text of the component followed by hitting Enter key
  • Click the component on the JFrame form and select the text property from the Properties window. Type the desired matter in the text property of the component.

Using any of the above method, let us change the text property of the components as given below:

  • Set the text of first Label component to “Select Food Items”.
  • Set the text of first Check Box to “Burger $5”
  • Set the text of second Check Box to “Hot Dog $7”
  • Set the text of third Check Box to “Pizza $10”
  • Delete the text property of the second Label component as its text property will be set through Java code. It is through this Label component that we will be displaying the total bill amount of the selected food items.

After setting the text property of all the five components, the  JFrame form will appear as shown below:

Java Swing components on JFrame form after setting text

Java Swing components after setting text

Each of the Java Swing components that we have dropped on the JFrame form is assigned a default variable name such as jLabel1, jLabel2, jCheckBox1, jCheckBox2 and so on. We need to assign meaningful variable name to these components. To assign a variable name to any component, simply right click on it and choose Change Variable Name option from the context menu that opens up. Let us set the variable name of the first Check Box to jCheckBoxBurger, that of the second Check Box to jCheckBoxHotDog and that of the third Check Box to jCheckBoxPizza. Also, set the variable name of the second Label component to jLabelResponse.

We want that whenever any of the checkbox is checked or unchecked, the bill amount of the selected checkbox be displayed.

Writing Java Code

Currently, we are in Design mode and to write code, we need to switch to Source mode. To switch to Source mode, either you click Source toolbar button from the Editor window or simply double click on any Java Swing component in the JFrame form. On double clicking the component, you will be taken to the Source mode to write code for that component. We will begin writing code for jCheckBoxBurger component.  So, double click the jCheckBoxBurger and you will be taken to Source mode. Write the following code :

int billAmount=0;

private void jCheckBoxBurgerActionPerformed(java.awt.event.ActionEvent evt) {                                               

         if (jCheckBoxBurger.isSelected()) {

            billAmount=billAmount+5;

        } else {

            billAmount=billAmount-5;

        }

         jLabelResponse.setText(“Bill Amount is $”+String.valueOf(billAmount));

}  

Description of above code

You define a global integer variable called billAmount and initialize it to 0. The jCheckBoxBurgerActionPerformed method will be invoked whenever some action is performed on the jCheckBoxBurger i.e. whenever it is checked or unchecked. In the jCheckBoxBurgerActionPerformed method, we determine if the checkbox is checked or not. If the checkbox is checked, integer value 5 is added to the billAmount variable. If the check box is unchecked, value 5 is subtracted from the billAmount variable.

After writing the code for jCheckBoxBurger, we need to write code for the jCheckBoxHotDog. So, from the Code mode, we will go back to the Design mode by clicking the Design toolbar button from the Editor window. From the Design mode, double click on the jCheckBoxHotDog and write the following code in the jCheckBoxHotDogActionPerformed method that is automatically created in the Code mode:

private void jCheckBoxHotDogActionPerformed(java.awt.event.ActionEvent evt) {                                               

      if (jCheckBoxHotDog.isSelected()) {

            billAmount=billAmount+7;

        } else {

            billAmount=billAmount-7;

        }

         jLabelResponse.setText(“Bill Amount is $”+String.valueOf(billAmount));

}        

Again, go back to the Design mode by clicking the Design toolbar button. Double click on the jCheckBoxPizza and write the following code in the Code mode:

private void jCheckBoxPizzaActionPerformed(java.awt.event.ActionEvent evt) {                                   

if (jCheckBoxPizza.isSelected()) {

            billAmount=billAmount+10;

        } else {

            billAmount=billAmount-10;

        }

         jLabelResponse.setText(“Bill Amount is $”+ String.valueOf(billAmount));

    }    

After writing code for all the three check boxes, our project is ready to run. You can run the project by choosing any of the following three options:

  • Selecting Run Project toolbar button from the toolbar at the top
  • Press F6 key
  • Select Run->Run Project option from the menu bar

Running the Java Swing Application

If you run the project now, you will not get any output because the main class of the project at the moment is CheckBoxDemoApp.java  and we have not written any code in this java file. So, we first need to change the main class file. So, right click the checkBoxDemoApp project in the Projects window and select Properties option from the context menu that pops up.  From the Properties dialog, select the Run category from the Categories pane.  In the Main Class textbox, you will find the text, checkboxdemoapp.CheckBoxDemoApp which confirms that on running the project, CheckBoxDemoApp.java file will be executed first. Change the content in the Main Class textbox to checkboxdemoapp.FastFood (see below given figure) to indicate that you want FastFood.java file to run first .

Now you are ready to run the project. On running the project, you will get the following three food items in the form of check boxes to select from. Select any number of food items and you get their bill amount :

Bill amount of the selected food items is displayed

Bill Amount displayed of the selected food items

You can download the complete project from the following link: http://bmharwani.com/checkBoxDemoApp.zip

.  .  .

Leave a Comment