Java It
Java It
Learning Objectives
• Identify, name and state the usage of the different components of the
NetBeans IDE.
• Identify and name the various methods and properties associated with
the various form controls
Introduction
In our day to day life, we have to give information innumerable times like fill up bank deposit slips
to deposit money or type in username and password to sign in to our mail account and many more.
Forms are means to accept data (input) from us and respond as soon as we perform an action like
clicking on a button or submitting the form. This chapter deals with teaching the basic process of
designing forms in Netbeans and using them to perform simple manipulations using Java.
NetBeans ID
NetBeans IDE is used to create java applications very easily using the efficient GUI builder. It allows
us to develop applications by dragging and positioning GUI components from a palette onto a
container. The GUI builder automatically takes care of the correct spacing and alignment of the
different components relative to each other. Let us go through the different components of the
NetBeans IDE (Refer to Fig 5.1):
Figure 5.1 NetBeans IDE
1. Title Bar
3. Toolbars
4. GUI builder: It is an area to place components on the form visually. There are two views of
the GUI builder- the Design View and the Source View. We can switch over from one view
to another by simply clicking on the source and design tabs directly above the Design Are a.
5. Palette: Palette contains controls or components used to create GUI applications.
I PROGRAMMING - A REVIEW
6. Inspector Window: This window is used to display a hierarchy of all the components or
controls placed on the current form.
7. Properties Window: Using this window we can make changes in the properties of currently
selected control on the form.
8. Code Editor Window: - It is the area where we write code for our java application.
Components
COMPONENTS (ALSO known as "widgets") are the basic interface elements the user interacts
with: jlabels, jbuttons, jtextfields etc. Components are placed on a container (like the jFrame).
There are two types of controls (Refer to Figure 5.2):
• Parent or container controls: They act as a background for other controls. For
example-Frame. When we delete a parent control, all its child controls get deleted.
When we move a parent control all its child controls also move along with it.
• Child controls: controls placed inside a container control are called child
controls. For example-Text Field, Label, Button etc.
1. Select New Project from the File menu. You can also click the New Project
button in the IDE toolbar.
2. In the Categories pane, select the General node. In the Projects pane, choose
the Java Application type. Click the Next button.
3. Enter the name of the project in the Project Name field and specify the project
location. Do not create a Main class here.
Let us recap the relation between a Project, Form and Components. Each application is treated as
a Project in NetBeans and each project can have one or multiple forms and this fact is clear from
the Projects window as shown in Figure 5.3.
Figure 5.3 Project Window Showing Multiple Forms
Further each form can have one or more elements - some of which may be visible and some
invisible. The visible components are all shown under the Frame Component and the non -visible
components are part of other components.
We use the drag and drop feature of NetBeans to place components on the form to design an
effective interface for our applications. The first step that we undertook while designing our
applications was adding a new jFrame form. The jFrame is a window with title, border, (optional)
menu bar and is used to contain all other components placed by the user on the form. S ome of the
properties of the jFrame form are defaultCloseOperation and Title(Refer Figure 5.4).
Property Description
Any component of GUI front-end (the form itself and the swing containers and controls placed in
the form) of an application is an object. Each of these objects belongs to its corresponding class
predefined in Java. For example, a form is an object of JFrame class, all the textfields are objects
of JTextField class, and so on. Each object has some properties, methods, and events associated
with it using which you can control the object's appearance and behaviour.
Properties of an object are used to specify its appearance on the form. For example, to set the
background colour of a textfield you change its background property; to set its font you change
its font property; and so on.
Methods are used to perform some action on the object. For example to display something in a
textfield you can use its setText() method, to extract the contents of a textfield you can use its
getText() method. Methods can be divided into two categories- getters and setters.
• Getters are the methods which extract some information from the object and return it
to the program. Getters start with the word get. Examples of getters are: getText(),
getForeground(), getModel(), isEditable etc.
• Setters are the methods which set some properties of the object so that the object's
appearance changes. Setters start with the word set. Examples of setters are:
setText(), setForground(), setModel() etc.
Events are the actions which are performed on controls. Examples of events are:
mouseClick, mouseMoved,keyPressed etc. When the user performs any action on a control,
an event happens and that event invokes (sends a call to) the corresponding part of the code
and the application behaves accordingly.
After setting the properties of the jFrame we can start placing components like jButton on the
jFrame form. A button is a component that the user presses or pushes to trigger a specific action.
When the user clicks on the button at runtime, the code associated with the click action gets
executed. The various methods and properties associated with the jButton are summarized in
Figure 5.5.
Property Description
Method Description
We developed simple real life applications wherein on the click of the button we accepted the data
from the user in the jTextField and after processing the data the result was displayed in a jTextField
or a jLabel. jTextField allows editing/displaying of a single line of text. jTextField is an input area
where the user can type in characters whereas a jLabel provides text instructions or information. It
displays a single line of read-only text, an image or both text and image. The various methods and
properties associated with the jTextField and jLabel are summarized in Figure 5.6 and 5.7
respectively.
Property Description
Border Sets the type of border that will surround the text field.
toolTipText Sets the text that will appear when cursor moves over the
component.
Method Description
getText() Retrieves the text in typed in jTextField.
String result=<textfield-name>.getText( );
boolean b =<textfield-name>.isEnabled( );
setEditable Sets whether the user can edit the text in the textField. true
if editable else false.
<textfield-name>.setEditable(boolean b);
<textfield-name>.setText(String t);
<textfield-name>.setVisible(boolean b);
PR
Figure 5.6 Properties and Methods of the jTextField
Property Description
Method Description
getText() Retrieves the text in typed in jLabel.
String result=<label-name>.getText();
boolean b=<label-name>.isEnabled();
<label-name>.setText(String t);
<label-name>.setVisible(boolean b);
The Text Area component allows us to accept multiline input from the user or display multiple lines
of information. This component automatically adds vertical or horizontal scroll bars as and when
required during run time. The various methods and properties associated with the jTextArea are
summarized in Figure 5.8.
Property Description
RAMMING - A REVIEW
Property Description
The radio buttons are used to provide the user several choices and allow him to select one of the
choices (the radio buttons belong to a group allowing the user to select single option). But radio
buttons occupy a lot of space.
Thus, in case of too many options we can use Combo boxes as they help save space and are
less cumbersome to design as compared to radio button. We can use check box and li st when
we want to display multiple options like selecting favourite sports or ordering multiple food items
in a restaurant.
The list is a preferred option over check box in situations wherever multiple options are required
to be selected from a large number of known set of options as they help save space and are
less cumbersome to design as compared to check boxes. The properties and methods of
jRadioButton are summarized below:
Property Description
buttonGroup Specifies the name of the group of button to which the jRadioButton
belongs.
ING - A REVIEW
Method Description
jCheckBox is a small box like component that is either marked or unmarked. When it is clicked,
it changes from checked to unchecked or vice versa automatically. The properties and methods
of jCheckBox are summarized below:
Property Description
background Sets the background color.
selected Sets the check box as selected if set to true, default is false.
I PROGRANG - A REVIEW
Method Description
getText() Retrieves the text typed in
String str = <checkbox-name>.getText();
Property Description
background Sets the background color.
buttongroup Specifies the name of the group of button to which the jComboBox
belongs.
ROGRAMMING - A REVIEW
Method Description
setModel() Sets the data model that the combo box uses to get its list
of elements.
<combobox-name>.setModel
(ComboBoxModel aModel);
Property Description
ROGRAMMING - A REVIEW
Method Description
Object result=
<list-name>.getSelectedValue();
boolean b =
<list-name>.isSelectedIndex(int index);
We use JOptionPane when we want to request information from the user, display information to
the user or a combination of both. It requires an import statement at the top of the program.
import javax.swing.JOptionPane;
OR
import javax.swing.*;
Either of them is acceptable. The difference is that the latter will import the entire library as
denoted by the star whereas the first statement will just import the JOptionPane library.
Method Description
showMessageDialog() Shows a one-button, modal dialog box that gives the user
some information.
Example :
JOptionPane.showMessageDialog(this,"Java and
NetBeans");
OGRAMMING - A REVIEW
showConfirmDialog() Shows a three-button modal dialog that asks the user a
question. User can respond by pressing any of the suitable
buttons.
Example:
Confirm=
JOptionPane.showConfirmDialog(null,"quit?")
showInputDialog() Shows a modal dialog that prompts the user for input. It
prompts the user with a text box in which the user can enter the
relevant input.
Example :
name=
JOptionPane.showInputDialog(this,"Name:");
Object Oriented Programming follows bottom up approach in program design and emphasizes on
safety and security of data. It helps in wrapping up of data and methods together in a single unit
which is known as data encapsulation. Object Oriented Programming allows some special features
such as polymorphism and inheritance. Polymorphism allows the programmer to give a generic
name to various methods or operators to minimize his memorizing of multiple names. Inheritance
enables the programmer to effectively utilize already established characteristics of a class in new
classes and applications.
The major components of Object Oriented Programming are as follows:
1. Class
2. Object
A class is used to encapsulate data and methods together in a single unit. It helps the programmer
to keep the data members in various visibility modes depending upon what kind of access needs
to be provided in the remaining part of the application. These visibility modes are classified as
private, public and protected. Usually, data members of a class are kept in private or protected
visibility modes and methods are kept in the public visibility mode.
An object is an instance of a class that is capable of holding actual data in memory locations.
Class and objects are related to each other in the same way as data type and variables. For
example, when we declare float variable named marks, the variable marks can be thought of as an
object of type float which can be assumed as the class. If we take another hypothetical case in
which Human is a class, Mr. Arun Shah, Mr. Aneek Ram will be the objects of this Human class.
In real java programming, this data will be required to conform to a specific data type as in char, int,
float or double whereas the methods will be a sequence of steps written together to perform a
specific task on the data. Carefully observe the illustration given in Figure 5.15 to reinstate the
theoretical conce pts learnt above.
The JTextField, JLabel, JTextArea, JButton, JCheckBox and JRadioButton are all
classes and the jTextField1, jLabel1, jTextArea1, jButton1, jCheckBox1 and
jRadioButton1 components are all objects. The setText(), setEnabled(), pow(),
substring() are all methods of different classes. This concept is illustrated in Figure 5.16.
Variables
Variables are containers used to store the values for some input, intermediate result or the
final result of an operation. The characteristics of a variable are:
• It has a name.
However, as different materials require different containers, and so we used different data types
to hold different values. Java programming language requ ires that all variables must first be
declared before they can be used.
When programming, we store the variables in our computer's memory, but the computer has to
know what kind of data we want to store in them, since it is not going to occupy the same amount
of memory to store a simple number or to store a single letter or a large number, and they are
not going to be interpreted the same way so variables were used along with data types. The
data types supported by java are summarized as follows:
Data Types
Data type states the way the values of that type are stored, the operations that can be done on
that type, and the range for that type.
ROGRAMMING - A REVIEW
The decision about which numeric data type to use should be based on the range of values
that a variable can take.
These data types are used to store characters. Character data types can store any type of values
- numbers, characters and special characters. When we want to store a single character, we
use char data type and when we want to store a group of characters, we use string data type.
For example, to store grades (A, B, C, D, E) of a student we will use char type but to store name
of a student, we will use string type. The char data type value is always enclosed inside '' (single
quotes), whereas a string data type value is enclosed in "" (double quotes).
Operators
With the introduction of variables and constants there arose a need to performcertain operations
on them. We performed operations on variables and constants using operators. Operators are
symbols that manipulate, combine or compare variables. The operators av ailable in java are
summarized below:
Assignment Operator:
One of the most common operators is the assignment operator "=" which is used to assign a
value to a variable. We assign the value given on the right hand side to the variable specified on
the left hand side. The value on the right hand side can be a number or an arithmetic expression.
For example:
int sum = 0;
Arithmetic Operators:
These operators perform addition, subtraction, multiplication, and division. These symbols are
similar to mathematical symbols. The only symbol that is different is "%", which divides one
operand by another and returns the remainder as its result.
+ additive operator
- subtraction operator
* multiplication operator
/ division operator
% remainder operator
Relational Operator:
A relational operator is used to test for some kind of relation between two entities. A
mathematical expression created using a relational operator forms a relational expression or a
condition. The following table lists the various relational operators and their usage:
> greater than Tests if the value of the left expression is greater
than that of the right.
< less than Tests if the value of the left expression is less than
that of the right.
>= greater than or Tests if the value of the left expression is greater
equal to than or equal to that of the right.
<= less than or Tests if the value of the left expression is less
equal to than or equal to that of the right.
Logical Operator:
A logical operator denotes a logical operation. Logical operators and relational operators are
used together to form a complex condition. Logical operators are:
! !a a is false
Bitwise Operator:
Bitwise operators are used to perform manipulation of individual bits of a number. They can be
used with any of the integral types (char, short, int, etc). They are used when performing update
and query operations of Binary indexed tree.
Creating a new Project
Creating a new Form
To create a new application project called "Book":
1. Choose File > New Project. Alternately, click the New Project icon in the toolbar.
2. From the Categories pane select Java and in the Projects pane, choose Java Application.
Click Next.
3. Enter a name (in this case Book) in the Project Name field and specify the project location by
clicking on the Browse button. By default, the project is saved in the NetBeans Projects folder in
My Documents and so this is the default Project location displayed in this field.
4. Ensure that the Set as Main Project checkbox is selected and clear the Create Main Class
field.
5. Click Finish.
Netbeans creates the Book folder on your system in the designated location. This folder will
contain all of the associated files of the project. The next step is to create a form. To proceed
with building our form, we need to create a container within which we will place the other required
components of the form like a button. For all our applications we will choose the JFrame Form
as the container to place other components.
To create a JFrame Form container:
1. In the Projects window, right-click the Book node and choose New > JFrame Form as shown
in Figure 5.21.
2. Enter Form Example 1 as the Class Name. This will be the name of your form.
3. Enter Book as the package. This should be the name given while creating the Project. 4. Click
Finish.
When we click the Source button, the application's Java source code in the Editor is displayed
with sections of code that are automatically generated by the Netbeans Builder indicated by
gray/blue areas, called Guarded Blocks. Guarded blocks a re protected areas that are not
editable in Source view. Note that we can only edit code appearing in the white areas of the
Editor when in Source view.
Executing a File
Now that the code for the first application is ready let us test our first application. To
execute the application simply select Run>Run File or press Shift+F6 as shown in Figure
5.24.
Figure 5.24 Executing a File
On executing the first example, the window shown in Figure 5.25 will appear. Click on
the button and observe the result.
The window in which we have designed our form is called the Design window and the window
in which we have written the code is called the Source window. We can easily switch between
the two views by simply clicking on the relevant tab as displayed in Figure 5.22.
Changing Properties of Components
Each component of our application including the form has certain attributes associated with it.
The Properties Window displays the names and values of the attributes (properties) of the
currently selected component. We can edit the values of most properties in the Properties
window.
Figure 5.23: Using the text property of a button to change the display
text
We want to change the text displayed on the button. There are four ways of doing the same in
the design view:
● Select the button component by clicking on it. In the Properties window highlight the
text property and type STOP in the textbox adjacent to it as displayed in Figure 5.23.
● Alternatively select the object. Left click on the button to highlight the display text. Type
STOP and press Enter.
● Select the object > Press F2 - to make the display text editable. Type in the new text
and press Enter.
Right click on the button component and select Edit Text from the Drop down menu to make the
display text editable. Type in the new text and press Enter. Using the Properties window, it is
also possible to change the Font and Foreground property of the button as displayed in Figure
5.24.
Figure 5.24 Changing Properties of a Button Using the Properties Window
Now when we execute the file the button with the changed text appears as shown in Figure 5.25.
Figure 5.28 Code to Add Functionality to the Form designed in Figure 5.27
Now execute the Example and observe the result of clicking Morning and Evening Buttons.
As we create applications and add to them new objects such as buttons and textboxes, they are
automatically assigned names such as jButton1, jButton2 and so on by the IDE. But it is good
practice to give names that better match the functionality, such as BExit and BMorning.
Remember that objects on the same form cannot have same name, but two forms might contain
objects with the same name.
Figure 5.29: Code to Display message in a Text Field on the click of a Button
The above code introduces us to a new method called setText(). This method is used to change
the display text of a component (label, text field or button) during run time. The syntax of this
method is given below:
Syntax:
component.setText("text")
The "text" is the display text to be shown for the mentioned component.
Figure 5.30 Form Design to Display a Personalized Time Based Greeting on the Click of a Button
Observe the Figure 5.30 carefully. we have used a new component - a label and the two text
fields. A label is a component which is used to display simple text or as a label for another
component. Out of the two text fields one of them has a white background while the other has
the same background colour as the form. The difference in the background colour tells us that
one of the text field is editable while the other is not. In simple words editable means that the
user can change the text displayed in the text field at run time. The text fiel d at the top has to
accept the name of the user and is editable. The text field at the bottom has to display the
greeting and is non-editable.
Figure 5.31 displays the properties of both the text fields.
After completing the designing of the form, now we are ready to add the code. Remember that
we had to use the getText() method in our code. Again double click on the three separate buttons
one by one to attach relevant code to each one of them. Observe the coding given in Figure
5.33.
The code teaches us another useful method - getText(). This is used to return the text contained
in the referred text component. It is generally used to retrieve the value typed by the user in a
textbox or label. The syntax for this method is given below:
Syntax:
jtextField1.getText()
This command is used to retrieve the value of the text Field named jtextField1.
Let us now understand the code. We want to display the message in the second text field along
with the name of the user which has been entered in the first text field. jTextField1.getText()
● Retrieves the name entered by the user in the first text field using getText().
"Good Morning" + jTextField1.getText()
● The message "Good Morning" is concatenated with the name retrieved from the first
text field using the + symbol.
jTextField2.setText("Good Morning" + jTextField1.getText())
● The display text of the second text field is set to the concatenated message
using setText().
Figure 5.34 displays an alternative method of concatenating the message and the contents of
the text field.
Figure 5.34 Code to Display Personalized Time Based Greeting on Click of a Button
using concat() method
This alternate uses the concat() method to add the two strings together. The syntax of this
method is:
Syntax:
string1.concat(string2)
This will result in adding the string2 at the end of the string1. For example: "sham".concat("poo")
returns shampoo
And
"to".concat("get").concat("her") returns together
Finally, our code is ready for execution. Figure 5.35 displays the output when the user enters
the name and clicks on the Morning button.
After both the radio buttons have been associated together, clicking on any one of them will
show an association between them informing us that they belong to a group. Add one more
non-editable text field to display the name along with the title. Double click on each of the two
radio buttons one by one to associate them with the appropriate code displayed in Figure 5.37.
Figure 5.38 Code for displaying Multiline Text in a Text Area on the click of a Button
Figure 5.39 shows the sample output of the code given in Figure 5.38.
Figure 5.39 Sample Run of the Text Area Application
Handling a Password Field Component
We can use the Password Field if we want that the text input by the user should not be displayed
as characters but as special characters (so that it is not readable by anyone). This component
allows confidential input like passwords which are single line. Let us design a simple application
which displays a simple message when the user inputs a user name and password. Figure 5.40
displays the sample run of the application. Remember that no checking is being done, rather a
simple message is to be displayed on the click of the LOGIN button and the application should
be terminated on the click of the CANCEL button.
Figure 5.45 Code for the Amount Calculator Using Numbers with Decimals
The code has introduced us to one new method:
● Double.parseDouble() - to convert a value to Double type We are already familiar with
setText(), getText()and toString() so now we are ready to understand the code.
jTextField1.getText() and jTextField2.getText()
● Retrieves the value entered by the user in the first and second text fields respectively
using getText(). These values by default are treated as strings i.e. a group of characters
and not as numbers
Double.parseDouble( jTextField1.getText()) and
Double.parseDouble( jTextField2.getText())
● The string values need to be converted to numbers with decimals and this is achieved
using the parseDouble() method. After converting both the values they are multiplied to
get the total amount payable.
Double.toString(Double.parseDouble( jTextField1.getText()) *
Double.parseDouble( jTextField2.getText()))
● The value calculated is a number with decimals which is to be displayed in a text field. So
before displaying it needs to be converted to a string type and this is achieved using the
toString() method.
jTextField3.setText(Double.toString(Double.parseDouble( jTextField1.getText()) *
Double.parseDouble( jTextField2.getText()))
● The converted value is displayed in the third text field using the setText() method.
Variable Declaration
We have learnt that variables are capable of storing values, which we need to use. To reference
a variable, it should have a name. Moreover, variables in java can only accept a value that
matches its data type. So before we use a variable we must decide on its name and its data
type. Giving this information to the language compiler is called variable d eclaration. Thus, the
declaration of a variable tells us about the name of the variable which is necessary to reference
it, the type of data it will store and optionally an initial value. Given below are some commonly
used ways of variable declaration.
● Keywords or words, which have special meaning in java, should not be used as
the variable names.
● After the first initial letter, variable names may contain letters and digits (0 to
● 9) and (_,$), but no spaces or special characters are allowed.
Using the above conventions and rules following is an indicative list of acceptable and
unacceptable variable names.
Java variable names are case sensitive, so sum1 and SUM1 aren't the same variable.
As is clear from the sample run, we need to concatenate the message and the selected
character depending upon the button clicked by the user. Let us now design the application:
First add a new JFrame form and set its title property to "Magic Text". Design the form as
shown in Figure 5.48 with the following components:
▪ five buttons - four to concatenate message with different characters and one to exit
from the application
Now try to develop a similar application with four buttons to perform the basic mathematical
operations of addition, subtraction, multiplication and division of any two numbers entered by the
user. First design the form with the following components:
▪ two editable text fields to accept the two numbers .
▪ four buttons to decide the operation, one button to reset the fields and one
button to exit out of the application.
▪ one non-editable text field to display the result.
▪ appropriate labels to direct the user.
When the user enters two numbers and clicks on the + button, the sum of the numbers is
displayed in the jtextField3 which has been disabled (by setting its editable property to false) as
shown in Figure 5.49.
When the user clicks on the RESET button the contents of all the Text Fields are cleared.
Now write the code for each button of the basic calculator shown as follows:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
// Code to add Number1
and Number2: double
Number1,Number2,Result;
Number1=Double.parseDouble(jTextField1
.getText());
Number2=Double.parseDouble(jTextField2.getText()
); Result=Number1+Number2;
jTextField3.setText(Double.toString(Result));
}
steps of computation remain the same. So we will explain one (coding for the first button) in detail
here:
double Number1,Number2,Result;
Number1=Double.parseDouble(jTextField1.getText()); and
Number2=Double.parseDouble(jTextField2.getText());
● retrieves the value entered by the user in the first and second text field using
getText(). These values by default are treated as strings i.e. a group of
characters and not as a number so the string values need to be converted to a
double type and this is achieved using the parseDouble() method. After
converting it to a double type the values are assigned to the variables declared in
the first line of code
Result=Number1+Number2;
● The two values stored in the variables are added and the calculated value is
stored in the variable Result.
jTextField3.setText(Double.toString(Result));
● The value stored in the variable Result is of type double so it is first converted to
type string using the toString() method and then the display text of the third text
field is set to the converted value using setText().
The working of the other three buttons (second, third and fourth) is similar to the one explained
above. We are already familiar with the working of the STOP button so let us give a quick look
to the coding of the RESET button
jTextField1.setText(""); and
jTextField2.setText(""); and
jTextField3.setText("");
● The display text of all the three buttons is set to an empty string (i.e.
blank) using the setText() method.
In all the applications developed so far we have used a single type of data and done simple
calculations. Next let us explore the use of multiple data types and using these data types try
to perform complex calculations.
Observe the form shown in Figure 5.50 and design a similar form.
The aim of the application is to accept the principal amount, rate and time in three separate text
fields and calculate the simple interest on the click of a button. The calculated interest is
displayed in a disabled text field. The coding for the same is given in Figure 5.51 .
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
double Principal,Rate,SInterest;
byte Time; //Expected value not more than 127 Years
Principal=Double.parseDouble(jTextField1.getText());
Rate=Double.parseDouble(jTextField2.getText());
Time=Byte.parseByte(jTextField3.getText());
SInterest=(Principal*Rate*Time)/100; //Formula to calculate SI
jTextField4.setText(Double.toString(SInterest));
Control Structures
We use control structures when we want to control the flow of the program. There are types of
control structures: Selection statements and Iteration statements.
Selection Statements:
A selection statement selects among a set of statements depending on the value of a controlling
expression. The selection statements are the if statement and the switch statement, which are
discussed below:
Simple if Statement - The if statement allows selection (decision making) depending upon the
outcome of a condition. If the condition evaluates to true then the statement immediately
following if will be executed and otherwise if the condition evaluates to false then the statements
following the else clause will be executed. The selection statements are also called conditional
statements or decision statements.
The syntax of if statement is as shown below:
Syntax:
if (conditional expression)
{
Statement Block;
}
else
{
Statement Block;
}
RAMMING -REVIEW
Points to remember about if statement:
• The else clause is optional and needs to be included only when some action is to
be taken if the test condition evaluates to false.
Let us now design another application: “Vote Eligibility Checker” where we are accepting the
age from the user and we want to validate whether the person is eligible to vote or not. We
are accepting the age of the user in a text field and testing whether the age entered by the
user is greater than 18 or not. If the age is greater than 18 then the message "You are eligible
to VOTE" is displayed. If the age is less than then the message “You are NOT eligible to VOTE”
is displayed. In such situations when we have to take action on the basis of outcome of a
condition, we need to use a Selection statement. Design the form and set the properties of
the components so that the form looks exactly like the one displayed in figure 5.52.
Private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// Code to check eligibility to vote with else condition: if
(Integer.parseInt(jTextField1.getText())>=18)
JOptionPane.showMessageDialog(null,"You are eligible To
VOTE");
else
JOptionPane.showMessageDialog(null,"You are NOT eligible
To VOTE");
}
Let us now understand the single line code in detail.
Integer.parseInt(jTextField1.getText())
● retrieves the value entered by the user in the text field using getText ().This value
by default is treated as a string and not as a number so it needs to be converted to
an integer type and this is achieved using the parseInt() method.
if (Integer.parseInt(jTextField1.getText()) >=18)
● check whether the value retrieved from the text field is greater than or equal to 18
or not. The if statement is used to check the condition and if the condition
evaluates to true then we specify what action is to be taken
if (Integer.parseInt(jTextField1.getText()) >=18)
JOptionPane.showMessageDialog(null, "You are eligible to VOTE")
● This if statement is used to check whether the value retrieved from the text field
is greater than or equal to 18 or not and if it is then it displays the message
"You are eligible to VOTE" using the showMessageDialog() method.
else
JOptionPane.showMessageDialog(null,"You are NOT eligible to VOTE");
● The else statement is executed if the value retrieved from the text field is less
than 18 and if it is then it displays the message "You are NOT eligible to VOTE"
using the showMessageDialog() method.
Nested if . . . else - These control structures are used to test for multiple conditions as against
the simple if statement which can be used to test a single condition. The syntax of n ested if else
is as follows:
Syntax:
if (conditional expression1)
{
statements1;
}
else if (conditional expression2)
{
statements2;
}
else if (conditional expression3)
{
statements3;
}
else
{
statements4;
}
Let us now develop another application called the Week Day Finder in which we will learn how
to use if statement when we have multiple test conditions. The Week Day Finder will display the
name of the week in a disabled text field depending upon the day selected by the user. The days
are displayed as radio button options, which have to be selected. So, the form will have 7 radio
buttons and depending on the button selected the day of the week will be displayed.
Design the form as shown in Figure 5.53. and set the properties of the components according
to the functionality required as shown in Figure 5.53. Monday is displayed when the radio
button corresponding to Day One is selected as shown in Figure 5.53 as it is the first day of
the week. If we select the radio button corresponding to Day Six then Saturday is displayed,
as it is the sixth day of the week.
It is clear from the above form that we have to test for multiple conditions. If jRadioButton1 is
selected then Monday will be displayed and if jRadioButton2 is selected then Tuesday will be
displayed and so on. All the select conditions will be checked from top to bottom and wherever
the condition evaluates to true, the statements corresponding to that jRadioButton will get
executed. What happens in case none of the jRadioButton is selected?
After understanding the working let us now write the code for the Week
Day Finder application as shown in Figure 5.54.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
// To find the day of the
week if
(jRadioButton1.isSelected())
jTextField1.setText("Monday");
else if (jRadioButton2.isSelected())
jTextField1.setText("Tuesday");
else if (jRadioButton3.isSelected())
jTextField1.setText("Wednesday"
); else if
(jRadioButton4.isSelected())
jTextField1.setText("Thursday")
; else if (jRadioButton5.isSelected())
jTextField1.setText("Friday");
else if (jRadioButton6.isSelected())
jTextField1.setText("Saturday")
; else if (jRadioButton7.isSelected())
jTextField1.setText("Sunda
y"); else
jTextField1.setText("Day - Not Selected");
}
The above code introduces us to a new method called isSelected(). This method is
used to check whether a particular radio button is selected or not. The syntax of this
method is given below:
Syntax:
jRadioButton.isSelected()
This method returns a boolean value i.e. true or false. The true indicates that the
radio button is selected and false indicates that the radio button is not selected.
Let us now understand the code in detail. Since the code in each subsequent else is
almost the same except the display text, so we will try and understand the first three
lines.
if (jRadioButton1.isSelected())
if (jRadioButton1.isSelected()) jTextField1.setText("Monday")
else if (jRadioButton2.isSelected())
● If the first radio button is not selected then check whether the
second radio button is selected or not
Switch Statement –
case Value1:statements1 ;
break ;
case Value2:statements2 ;
break ;
.
.
default:statements3 ;
}
After understanding the working of switch statement, let us now develop a discount calculator
using the switch statement. Design the form as shown in Figure 6.30. The Customer is given
a discount on the Bill Amount depending upon the Customer Type selected from the combo
box. Discount is calculated as follows:
Platinum 30%
Gold 20%
Silver 10%
When the application is executed the discount amount is deducted from the Bill Amount
depending upon the Customer Type selected by the user.
When Customer Type is Silver the customer gets a discount of 10% as shown in figure 5.55.
When Customer Type is Gold the customer gets a discount of 20% and when
Customer Type is Platinum the customer gets a discount of 30% on the Bill Amount.
Let us now write the code for the discount calculator as shown in 5.56.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
// Code to calculate discount depending upon customer type:
double FinalAmount=0;
double BillAmount = Double.parseDouble(jTextField1.getText());
switch(jComboBox1.getSelectedIndex())
{
case 0: FinalAmount=BillAmount; //No Discount for
new customer break;
case 1: FinalAmount=0.90*BillAmount; //10% Discount
for silver break;
case 2: FinalAmount=0.80*BillAmount; //20%
Discount for gold break;
case 3: FinalAmount=0.70*BillAmount;//30%
Discountfor platinum break;
default:FinalAmount=BillAmount;
}
jTextField2.setText(Double.toString(FinalAmount));
}
● If the second value in the combo box is selected then the FinalAmount
is calculated by multiplying the BillAmount by 0.90 (to give a discount
of 10%)
break;
● Stop the execution of the switch statement and transfer the control to
the statement immediately following the closing brace of the switch
statement. It has to be included as the last statement of each case.
default:FinalAmount= BillAmount
● When getSelectedIndex() is not equal to either 1,2 or 3 then the code moves
to default statement and no discount is given to the customer.
Comparing Switch and If..else Statements - Switch is used to select sections of code
depending on specific integer or character values. If we are handling specific coded
values (eg, the number of the button that was clicked in a JOptionPane), or processing
characters(whose codes are treated like numbers), then switch is useful. The limitations
of switch are as follows:
experience."; break;
default: comment =
"Oops -- something is wrong with this code.";
Equivalent if statement
1,or 2. if (choice == 0)
experience"; else
A switch statement can often be rewritten as an if statement. Let us look at the example given
above, when a selection is to be made based on a single value, the switch statement is generally
easier to read. The switch is useful when you need to manage a lot of if /else if / else . It has a
shorter syntax and is more appropriate in this case.
Points to Remember:
• NetBeans is an IDE using which we can develop GUI applications in Java.
• NetBeans provides various components used to create a GUI front-end
interface.
• GUI components' appearance and behaviour is controlled by their
properties and methods.
• We should use meaningful names for controls on the form and variables
in the code. It makes programming convenient.
• Some useful Data Types supported in Java are: int, double, char and boolean.
• String is an Object (reference) type supported in Java.
• A variable must be declared before it can be used.
• Different types of operators are available in Java. Operators are used to
perform various operations on data.
• The if statement selects among a set of statements depending on the
value of a controlling expression.
EXERCISES
1. What will be the final value of sum1 after the execution of the
program given below?
int sum1 = 3; sum1=sum1+1;
jTextField1.setText(""+sum1);
sum1=sum1+1; jTextField2.setText(""+sum1);
sum1=sum1+1;
jTextField3.setText(""+(sum1));
sum1=sum1+1;
jTextField4.setText(""+sum1);
jTextField5.setText(""+sum1);
a. 5 b. 6
c. 4 d. 7
if (anumber >=10)
jLabel1.setText("first string");
else
jLabel1.setText("second string");
jLabel2.setText("third string");
test condition.
4. If there is more than one statement in the block of a if statement, which of the
following must be placed at the beginning and the ending of the loop block?
int a = 11;
int b = 22; int c = 33; int d = 11;
vii) a >= c
a) IDE
b) Inspector Window
c) Form
2. Differentiate between :
8. Write and explain two methods each of check box and radio button.
AMMING - A REVIEW
LAB EXERCISES
1. Design a GUI application in which the user enters a three digit number in the text
field and on clicking the button the sum of the digits of the number should be
displayed in a label.
2. Design a GUI application to accept a number from the user in a text field and print
using option pane whether it is a positive even number or not.
3. Design a GUI application to accept the cost price and selling price form the user in
two text fields then calculate the profit or loss incurred.
4. Design a GUI application to accept a character in a text field and pr int in a label if
that character is a vowel: a, e, i, o, or u. The application should be case sensitive.
6. Design a GUI application in java to convert kilograms into grams, litres into
milliliters, rupees into paisa using combobox and text fields.
Customer - 5%
PROGRAMMING - A REVIEW
8. A networking company decided to computerize its employee salary . Develop an
application to store employee's personal data which will be saved in the back end.
The front end should accept Name, Father's Name, Mother's Name, Address,
Gender, Basic Salary, Medical and Conveyance. Calculate gross and net salary.
Basic DA HRA