You are on page 1of 57

Example Program : WAP in Java to accept the number of days and display it after converting into

number of years, number of months and number of days.

Code window for the above prgram

Execute the Jframe, On click of JButton1

Application
to Create a

1. Program
Calculator.

Add 4 labels, 3 text fields, 4 buttons to your application by dragging them from the palette. Drag
them one by one, See the below screenshot and rename them and place them in the similar way
as Ive placed.

After
Addition
below

placing them click on


button and write the
code:

double
fnum,
snum,
tot;
fnum
=

Double.parseDouble(jTextField1.getText());
Double.parseDouble(jTextField2.getText());
fnum+snum;
jTextField3.setText(Double.toString(tot));

snum =
tot =

Now go to the Subtraction button and the above code but just replace the addition
operator by subtracting operator, the code will look like this after you replace
double fnum, snum, tot;
fnum = Double.parseDouble(jTextField1.getText());
snum
= Double.parseDouble(jTextField2.getText());
tot = fnum-snum;
jTextField3.setText(Double.toString(tot));

Now go to the Multiplication button and replace the operator by a astrict, it refers to
multiplication operator which will allow you to multiply the numbers
double fnum, snum,
tot;
fnum = Double.parseDouble(jTextField1.getText());
snum =
Double.parseDouble(jTextField2.getText());
tot = fnum*snum;
jTextField3.setText(Double.toString(tot));

Now go to the Division button and replace the operator by a slash, that operator is used
for dividing in computers, after replacing the code will be looking like this
double fnum,
snum, tot;
fnum = Double.parseDouble(jTextField1.getText());
snum = Double.parseDouble(jTextField2.getText());
tot
= fnum/snum;
jTextField3.setText(Double.toString(tot));

After adding the code in all the buttons your code will look similar to the code which Ive shown in
the below Figure.

Application 2.
Program to do long division and display quotient and remainder.
1. Design a Jframe with following controls and set the necessary properties.

2. Write
code

the following
in the code
window.

int
divisor,dividend;
int quotient,remainder;
divisor=Integer.parseInt(jTextField1.getText());
dividend=Integer.parseInt(jTextField2.getText());
4

quotient=(int)(dividend/divisor);
remainder=dividend-(int)(dividend/divisor)*divisor;
jTextField3.setText("The quotient is" + Integer.toString(quotient)); jTextField4.setText("The
remainder is" + Integer.toString(remainder));

Radio buttons are usually used to select just one item from a list, rather than the multiple items
available with check boxes. Let's see how they work.
Drag and drop a panel onto your form. Then locate the Radio Button control in the NetBeans
palette. Drag a Radio button onto your new palette. It should look like this:

The default text for the first radio button is jRadioButton1. We'll use our radio buttons to allow a
user to select a payment method. So change the text of your radio button to Credit Card. (The
text can be changed in the same way as you did for check boxes. Again, we'll leave the variable
name on the default of jRadioButton1.)

Add two more radio buttons to the panel. Change the text to Debit Card, and PayPal:

There is, however, a problem with the radio buttons you've just added. To see what the problem is,
run your program again. Now select one of the radio buttons. Try selecting another radio button
and you'll find that you can indeed select more than one at the same time:

With our radio buttons, though, we only want the user to select one payment option. To solve the
problem, Java lets you to create something called a ButtonGroup. As its name suggest, this
allows you to group buttons under one name. You can then add radio buttons to the group. Once
you've added buttons to the group, only one option is available for selection.
Add a Button Group to the panel (Fig:1) and set the button group property of each button to the
Button Group1 (Fig:2).

Fig:1

Fig:2

following:

Check Box
Check boxes are similar to radio buttons but their selection model is different. Each Check box
component works independently of each other and so the user can select any number of check
boxes from an interface. A group of radio buttons, on the other hand, can have only one button
selected. A Check box can be added from the Swing Control menu as shown in the below Figure.

Code for the Sports charges application:


private
void
jButton1ActionPerformed(java.awt.event.ActionEvent
// TODO add your handling code here:
double amount=0;
if (jCheckBox1.isSelected())
{
amount=amount+2500; //cricket
jTextField1.setText("2500");
}
if (jCheckBox2.isSelected())
{
amount=amount+1500;
jTextField2.setText("1500");
}
if (jCheckBox3.isSelected())
{
amount=amount+2000;
jTextField3.setText("2000");
}
if (jCheckBox4.isSelected())
{
amount=amount+3500;
9

evt)

jTextField4.setText("1000");
}
jTextField5.setText(Double.toString(amount));
}
Q1: Design an application for Theatre Booking system. And answers the following questions:

A. When the user select different seat type, then its price should be displayed in the Label.
B. If the user enters an invalid no of seats i.e. less than I, then an error message should be

displayed in the dialog box.


C. When the user click at the Book Seats button , then total amount (calculated as no. of
seats x price per seat) should be displayed along with payment method, next to the push
button.
Price per seat depend upon the seat type :
Stall
Circle

625/750/-

Upper Circle 850/Box

1000/-

Ans:
(a)

if(jRadioButton1.isSelected()==true)jLabel2.setText(
625);
if(jRadioButton2.isSelected()==true)
jLabel2.setText(750);
if(jRadioButton3.isSelected()==true)
jLabel2.setText(850);
10

if(jRadioButton4.isSelected()==true)
jLabel2.setText(1000);
(b)

int s=Integer.parseInt(jTextField1.getText()); if(s<1)


JOptionPAne.showMessageDialog(null,Error);

(c)

int

s=Integer.parseInt(jTextField1.getText());

p=Integer.parseInt(jLabel2.getText());

int

int tp=s*p;

if(jRadioButton5.isSelected()==true)
jLabel5.setText(Cash

Payment

of

+tp);

of

+tp);

if(jRadioButton6.isSelected()==true)
jLabel5.setText(Visa

Payment

if(jRadioButton7.isSelected()==true)
jLabel5.setText(American Exress Payment of +tp);
if(jRadioButton8.isSelected()==true)
jLabel5.setText(Master Card Payment of +tp);
Q2 : Design the following application and answer the questions that follow :

(a)

Write the code for the Clear button to clear all the textfields and checkbox. Set the default
choice in the radio button as Fixed Deposit.

(b)

Write the code for the calculate button to calculate compound interest and amount and
display the values in the txtInterest and txtAmount depending on principal, rate and time.
Rate is calculated based on the time according to the following table:
Account
Fixed Deposit

Recurring Deposit

Time
<= 1
>1 and <=5
>5
<= 2
>2 and <=7
>7
11

Rate
10%
12%
15%
11%
12%
15%

An additional rate of 2% is given to the senior citizens i.e. if the chkSR checkbox is checked .
Ans:
(a)

jTextField1.setText(); jTextField2.setText();
jTextField3.setText();
jRadioButton1.setSelected(true); jCheckBox1.setSelected(false);

(b)

int p= Integer.parseInt(jTextField1.getText());
int t= Integer.parseInt(jTextField2.getText());
if(jRadioButton1.isSelected() )
{
if(t<=2) r=11; else if(t>2
&& t<=7) r=12;
else
r=15;
} else
{
if(t<=1) r=10; else if(t>1
&& t<=5) r=12;
else
r=15;
}
float ci= p*Math.pow((1+(r/100)),t); float
amt= p+ci; txtInterest.setText(+ci);
txtAmount.setText(+amt);

Q 3: Consider the following application and answers the following questions:

12

The grading criteria for the two streams is given below :


Stream
Percentage

Grade

Medical

>=80
A
60-80
B
<60
Non-Medical
>=75
A
50-75
B
<50
A. Write code for Calculate Percentage button to calculate the Percentage after
finding the total marks of I term and II term . Also ensure that NCC cadet
gets an increment of 3% in their percentages.
B. Write code for Calculate grade button to calculate the grade depending

upon on the stream selected according to the given criteria. Ans:


(a) float f= Integer.parseInt(jTextField1.getText());
float s= Integer.parseInt(jTextField2.getText());
float tot = f+s; float p= tot/2;
if(jCheckBox1.isSelected()) p=p+3;
jLabelp.setText(+p);
( b) String g;
if(jRadioButton1.isSelected())
{
if(p>=80)
g=A;
else if(p>=60 &p<80)
g=B;
else
g=C;
}
else
13

{
if(p>=75)
g=A;
else if(p>=50 &p<75)
g=B;
else
g=C;
}
jLabelp.setText(+p);
jLabelg.setText(+g);
Q 4: Mr. Kumar works in a construction company. To calculate total wages he has developed the
following GUI in NetBeans.

Male and female workers are respectively paid Rs. 150/- per day and Rs. 170/- per day. Skilled
workers are paid extra at the rate of Rs. 100/- day. Male and female workers from rural areas
are paid 10% less per day.
a. When Calculate Wage button is clicked, the total wages is calculated as per the given criteria

and displayed in total wage text box.


b. When Clear button is clicked, all the text boxes should be cleared and radio button, check
box should be deselected.
c. Close the application when Quit button is pressed.

Ans:
(a) int w=0;

int d =Integer.parseInt(jTextField2.setText()); if(jRadioButton1.isSelected())


w=150;
else
w=170;
14

if(jCheckBox1.isSelected())
w=w+100;
if(jRadioButton3.isSelected())
(w*10)/100;

w=w-

int cw=d*w;
jLabel6.setText(+cw);

(b) jTextField1.setText(); jTextField2.setText();

jRadioButton1.setSelected(false);
jRadioButton2.setSelected(false); jRadioButton3.setSelected(false);
jRadioButton4.setSelected(false); jCheckBox.setSelected(flase);
(c) System.exit(0);

Q 5: Mr. JigneshDesai an owner of Alpha Chemicals PVT ltd has asked his programmer Sweta to
develop the following GUI application in Netbeans:

Service Charges Rates are as follows :


Class of
Rate of Service
City
Charges
i
10% of sales price
ii
15% of sales price
iii
20% of sales price
Write java code for the following:
a. To calculate service charges depending on the selection of radio button. This code will

execute after click on the calculate service charges?


b. To calculate net price when Calculate Net price button will be clicked.
15

c. When exit button will be clicked application should be automatically closed.

Ans:
(a) float

q=Float.parseFloat(jTextField2.getText());

float

p=Float.parseFloat(jTextField3.getText());

float sp=q*p; jLabelsp.setText(+sp);


float sc;
if(jRadioButton1.isSelected()) sc=(10*sp)/100;
else if(jRadioButton2.isSelected())
sc=(15*sp)/100;
else sc=(20*sp)/100; jLabelsc.setText(+sc);

(b) float

float

sp=Float.parseFloat(jLabelsp.getText());
sc=Float.parseFloat(jLabelsc.getText()); float

np=sp+sc;

jLabelnp.setText(+np);

(c) System.exit(0);

Q6. Assume the following interface built using Netbeans used for bill calculation of a icecream
parlor. The parlor offers three verities of ice-cream - vanilla, strawberry, chocolate. Vanilla
ice- cream costs Rs. 30, Strawberry Rs. 35 and Chocolate Rs. 50. A customer can chose
one or more ice-creams, with quantities more than one for each of the variety chosen. To
calculate the bill parlor manager selects the appropriate check boxes according to the
verities of ice-cream chosen by the customer and enter their respective quantities. Write
Java code for the following:

(a) On the click event of the button 'Bill', the application finds and displays the total bill of
the customer. It first displays the rate of various ice-creams in the respective text fields.
If a user doesn't select a check box, the respective ice-cream rate must become zero.
The bill is calculated by multiplying the various quantities with their respective rate and
later adding them all.
(b) On the Click event of the clear button all the text fields and the check boxes get cleared.
(c) On the click event of the close button the application gets closed.

16

Ans: (a) private void jBtnCalculateMouseClicked(java.awt.event.MouseEvent evt)


{
if(jchkStrawberry.isSelected()==true) jTxtPriceStrawberry.setText("35");
else
{
jTxtPriceStrawberry.setText("0"); jTxtQtyStrawberry.setText("0");
}
if(jChkChocolate.isSelected()==true) jTxtPriceChocolate.setText("50");
else
{
jTxtPriceChocolate.setText("0"); jTxtQtyChocolate.setText("0");
}
if(jChkVinella.isSelected()==true) jtxtPriceVinella.setText("30");
else
{
jtxtPriceVinella.setText("0"); jTxtQtyVinella.setText("0"); }
int r1,r2,r3,q1,q2,q3,a1,a2,a3,gt;
r1=Integer.parseInt(jTxtPriceStrawberry.getText());
r2=Integer.parseInt(jTxtPriceChocolate.getText());
r3=Integer.parseInt(jtxtPriceVinella.getText());
q1=Integer.parseInt(jTxtQtyStrawberry.getText());
q2=Integer.parseInt(jTxtQtyChocolate.getText());
q3=Integer.parseInt(jTxtQtyVinella.get
Text()); a1=r1*q1;
jTxtAmtStrawberry.setText(""+a1); a2=r2*q2;
jTxtAmtChocolate.setText(""+a2); a3=r3*q3;
jTxtAmtVinella.setText(""+a3); gt=a1+a2+a3;
jTxtTotalAmt.setText(""+gt);
}

(a) private void jBtnClearActionPerformed(java.awt.event.ActionEvent evt)


{
jTxtPriceStrawberry.setText("");
17

jTxtPriceChocolate.setText("");
jtxtPriceVinella.setText("");
jTxtQtyStrawberry.setText("");
jTxtQtyChocolate.setText(""); jTxtQtyVinella.setText("");
jTxtAmtStrawberry.setText("");
jTxtAmtChocolate.setText("");
jTxtAmtVinella.setText("");
jchkStrawberry.setSelected(false);
jChkChocolate.setSelected(false);
jChkVinella.setSelected(false);
}
(c ) private void jBtncloseActionPerformed(java.awt.event.ActionEvent evt)
{
System.exit(0);
}

Exercises
1. What is the difference between Radio button and Check Box control? Explain with the help
of an example.
2. Explain the following methods of a Check box control?
(a) getText( )
(b) setText(String S)
(c) isSelected( )
18

(d) setSelected( )
3. Write a Java code for the following window to convert the temperature from Fahrenheit to
Celsius and Celsius to Fahrenheit.

4. Write a code for following window, the addition will be performed if the user clicks the
Addition check box and so that the product will be performed if the user clicks the Product
check box. Both or only one might be checked at any one time. The result will be displayed
on click of CALCULATE button.

19

5. Write a code for following Windows, on click of EXECUTE button the currency and the
conversion into paise will be displayed if the user select the India Option button and so that
currency and the conversion of Dollar to cents will be displayed if the user select the United
States Option button. Only one will be selected at one time.

20

9.

List Box and Combo Box

A List(also called list box) component displays a list of values/options from which single or multiple
values/items can be selected. When we place a list on JFrame form the default model property of
the list (default values in the list) has values as Item1, Item2and so on as shown in below Fig1.
The selectionMode property is set to MULTIPLE_INTERVAL by default ensuring that a user can
select multiple items from the list. These properties can be changed using the properties window
as shown in Fig:2.

Fig:1(

default values in the) list

Fig:2 Common Property of List


The selectionMode property has three possible values. The usage of each of these values is
explained below:
SINGLE implies that List box will allow only a single value to be selected.
SINGLE_INTERVAL implies that List box allows single continuous selection of options
using shift key of keyboard (i.e. values which occur in succession).
MULTIPLE_INTERVAL implies that List box allows multiple selections of options using
ctrl key of keyboard.
The model property is used to change the choices displayed in the list. The values can be updated
by clicking on the ellipsis(..) next to the property in the properties window as displayed in the
below Figure:

21

Modifying the model property of the jList component results in a change in the values displayed in
the list as shown in the below Figure.

Let us now design an application Restra Order using the food list created to help us understand
how to use a list component in an application. Design the form as shown in the above Figure. The
form consists of a list, a button, a text field and two labels - one for explaining the selection
process and one for indicating that the payable amount is in rupees. The aim of the application is
to allow the user to place an order for multiple items displayed in the list and display the bill
amount in the text field which will be calculated on the basis of the items selected. The menu
options are shown in the below Figure:

22

Let us now write the code for the above application as shown below:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
int
Total=0;
//Bhel Puri, Pasta, Pizza, Burger; if
(jList1.isSelectedIndex(0)==true)
{
Total=Total+150;
JOptionPane.showMessageDialog(this,"Bhel Puri Ordered Rs.150");
} if (jList1.isSelectedIndex(1)==true)
{
Total=Total+300;
JOptionPane.showMessageDialog(this,"Pasta Ordered Rs.300");
} if (jList1.isSelectedIndex(2)==true)
{
Total=Total+200;
JOptionPane.showMessageDialog(this,"Pizza Ordered Rs.200");
} if (jList1.isSelectedIndex(3)==true)
{
Total=Total+180;
JOptionPane.showMessageDialog(this,"Burger Ordered Rs.180");
}

if (jList1.isSelectedIndex(4)==true)

{
Total=Total+220;
JOptionPane.showMessageDialog(this,"Pav Bhaji Ordered Rs.220");
23

jTextField1.setText(Integer.toString(Total));

The above code introduces us to a new method - isSelectedIndex() method. This method is used
to check whether the index specified in the parenthesis has been selected or not.
The syntax of this method is given below:
Syntax:
jList.isSelectedIndex(int num)
The num is an integer value and represents the index value to be checked. The index numbering
starts at 0. This method returns a boolean value i.e. true or false. The true indicates that the value
at the specified index is selected and false indicates that the value is not selected.

Combo Box
This control is used to display a list of choices from which the user can choose a single option.
The difference between combo box and list box control is that a list box control allows user to
make one or more selections whereas a combo box control allows the user to make single
selection.
24

A Simple Combo Box


When we place a combo box on the JFrame form by default it shows Item1 as the first value as
shown in the above Figure. A Combo box appears like a text field with a drop down list arrow.
The common properties of the Combo Box can be edited using the properties window as shown
in below Figure.

Common Properties of the Combo Box Component


The default values displayed in a combo box are Item1, Item 2 and so on. These can be edited by
clicking on the ellipse() next to the values. Let us create a combo box having the name of cities.
Drag the Combo Box component from the Swing Controls tab and then type the items that we
want to be displayed in the combo box by clicking on the model property ellipse button. The new
values we typed in are shown in the below Figure.
25

Modifying the model Property of a Combo Box


Now Bangalore is the first value in the model property therefore on the form Bangalore will be
displayed with a drop down list arrow as shown in the above Figure.
Let us design an application called City Highlights to learn the usage of combo box. Design a
simple form with a combo box (containing names of 5 cities) and a button with display text as
"Know More". The required functionality is that on executing the application City Highlights, the
user should select a particular city and click on the button to view some additional information
about the city. Sample run of the application is shown in the below Figure.

26

Sample Run of the City Highlights Application

The code for the City Highlights application is as shown below:


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
if (jComboBox1.getSelectedIndex()==0)
JOptionPane.showMessageDialog(this,jComboBox1.getSelectedIte m()+
" - Known as Silicon Valley of India");
(jComboBox1.getSelectedIndex()==1)

else if

JOptionPane.showMessageDialog(this,jComboBox1.getSelectedI tem()+
" - Capital City of India");
else if (jComboBox1.getSelectedIndex()==2)
JOptionPane.showMessageDialog(this,jComboBox1.getSelectedI tem()+
" - Known for broad Industrial Base");
(jComboBox1.getSelectedIndex()==3)

else if

JOptionPane.showMessageDialog(this, jComboBox1.getSelectedItem()+
" - Known for literary, artistic and revolutionary heritage");
else if
(jComboBox1.getSelectedIndex()==4)
JOptionPane.showMessageDialog(this,jComboBox1.getSelectedI tem()+
" - Known for hub of Bollywood");
}
27

This code introduces us to two new methods, the getSelectedIndex() method and
thegetSelectedItem() method. The syntax and usage of each of these methods is explained below:
1. getSelectedIndex() - This method is used to return the index of the selected item. If an item is
selected only then will the getSelectedIndex method return a value else it returns -1. The syntax of
this method is given below: Syntax:
jComboBox.getSelectedIndex()
2. getSelectedItem() - This method is used to return the selected item. The syntax of this method is
given below: Syntax:
jComboBox.getSelectedItem()

1. Glamour Garments has developed a GUI application for their company as shown below :

The company accepts payments in 3 modes- Cheque, cash and credit cards. The discount given
as per mode of payment is as follows.

28

If the Bill Amount is more than 15000 then the customer gets an additional discount of 10% on Bill
Amount.
(i) Write the code to make the textfields for Discount (named txtDisc) and Net Amount
(named txtNetAmt) uneditable.
(ii) Write code to do the following:
(a) . When "Calculate Discount" button is clicked the discount should be calculated as per the
given criteria and it should be displayed in the discount textfield. "Calculate Net Amount"
button (named btnCalcNetAmt) should also be enabled.
(b) When "Calculate Net Amount" button is clicked the net amount should be calculated and it
should be displayed in the net amount textfield.
6. Write a code for the following window that builds a list as the user enters new values. As the
user enters more and more name of books the list should grow. Add four command
buttons :
(a) Add a command button to the form with the caption ADD when the user clicks the
command button, the name of book just entered in the textbox goes to the list.
(b) REMOVE command button to remove a particular item from the list.
(c) >> command button to move an item from left list box to right list box.
books which you like to list box2)
(d) END command button to end the application.

29

(Move the

10. Menus
You can add menus to your Java forms, things like File, Edit, View, etc. Each menu has menu
items, and these in turn can have sub menus.
Return to Design view. In the NetBeans palette, locate the Menu Bar item:

Drag one to the top of your form. When you let the mouse button go, you'll have a default File and
Edit menu bar:
30

There's no menu items added by default, though. To add your own, click on the File menu item to
select it. With the File menu item selected, right-click. A new menu will appear. Select Add From
Palette > Menu Item:

A Menu Item will be added to your File menu:

What we'll do is to add menu items to open and save a file.


Double click on the default text jMenuItem1. It will then be highlighted, so that you can type over
it:

Type Open, then press the enter key on your keyboard:

Add another menu item in the same way. This time, type Save as the menu item:

31

As you can see above, you can add shortcuts for your menu items. Click on to the Open menu
item, then onto the shortcut for it:

With the shortcut item selected, have a look at the properties window:

Locate the Accelerator item, and click the small button to the right of the row. A dialogue box
appears. You can set which shortcut keys you want for a menu item from this dialogue box. An
open shortcut is usually CTRL + O.
Type an O in the box, and Shift + O will appear. Uncheck the Shift item and check Ctrl instead:

32

Click OK, and the shortcut will be added to your Java menu item:

To see if all this works, click back on the Open menu item to highlight it. Now right click. From the
menu that appears, select Events > Action > Action Performed. This will create a code stub for
the menu item. Enter the following for the code:
JOptionPane.showMessageDialog(null,"Open");
This will display just a message box.
Run your programme and try it out. Click File > Open and you should see the message box
appear. Click OK to get rid of it. Now try your shortcut. Hold down the Ctrl key on your keyboard.
Keep it held down and press the letter O. Again, the menu should appear. Sample run of the
application is shown in the below Figure.

33

Exercise
1. Create a Menu containing Project, Format, Run as menu items.
2. Create a drop down menu with the following menu bar items:
Project, Format and Run. The menu structure is as follows:
A. File
1. New Project
2. New File
B. Edit
1. Undo
2. Redo
C. View
1. Editors
2. Split
3. Create a drop down Menu as shown in following figure:

34

11. Sample Applications and Case Studies


Application 1: Create an application that works similar to a text editor and provides the
following features:

Allows a user to type text in this text editor


Allows the user to copy, cut and paste the text
user to exit from the text editor

Allows

the

Answer:
Perform the following steps to create the required GUI application:
1.
2.
3.
4.

Start the NetBeans IDE and create a new project.


Add a frame to the project.
Set the title of frame as Text Editor Form.
Now add the four Button controls and a Text Area control from a swing controls
section of the Palette pane. Arrange these controls in the TextEditor frame, as
shown in the following figure.

5. Type the following code in the action event handler of the copy button:
jTextArea1.copy();
6. Type the following code in the action event handler of the cut button:
jTextArea1.cut();
35

7. Type the following code in the action event handler of the paste button:
jTextArea1.paste();
8. Type the following code in the action event handler of the exit button:
System.exit(0);
9. Save and run your application. The output appears, as shown in the following
figure:

10. To perform the copy operation, type some text in the text area, as shown in the
following figure:

36

11. Select the text that you want to copy and click the copy button, as shown below
figure:

12. Now, select the desired location where you want to copy the selected text and
click the Paste button, as shown in the following figure:

Application 2: Create a Java Swing toolbar using the Tool Bar control.
37

Answer:
Perform the following steps to create the required GUI application:
1. Create a new Java application in the Netbeans IDE and add a frame to it. After that, go to
the design view of the GUI builder and drag a Tool Bar from the Swing Container section of
the Palette pane onto the frame, as shown in the figure below:

An empty toolbar (or a place holder for buttons) will be added to the frame. By default, a
horizontal toolbar is added. However, you change its orientation to vertical using the
Properties window.
2. Now, on the empty place holder (that is, toolbar), you are required to add buttons. To do
this, drag and drop the Button control from the Swing Controls section to the toolbar
container, as shown in the below figure:

38

3. Select the added button and set its icon property to display an image on it.
4. Set the text property if you want display a text label along with icon on the button. After
adding few button and after setting these properties, the toolbar will look like, as shown in
the below figure

5. In the action event handler of these buttons, we are simply displaying the names of buttons
through the JoptionPanes dialog box. Following are the lines of code for each button
defined on the toolbar container:
JOptionPane.showMessageDialog(null,"You are selected Home option");
JOptionPane.showMessageDialog(null,"You are selected Mail option");
JOptionPane.showMessageDialog(null,"You are selected Department option");
JOptionPane.showMessageDialog(null,"You are selected Faculty option");
JOptionPane.showMessageDialog(null,"You are selected Job option");
JOptionPane.showMessageDialog(null,"You are selected About us option");
6. Save and press F6 key on the keyboard to run your application.
7. Click the Home button or any other button. A message dialog box appears as shown in
below figure
39

The new toolbar with Mail Buttons message dialog box.

The newtoolbar with Faculty buttons message dialog box.


Application 3:
40

Create a GUI application to obtain the details of a student, such as roll


number, name, class, subject, and marks through text fields and add them in a table. The
application should also provide the option to display total count of records in the table along
with the option to exit from the application. The GUI of the application should appear as
shown the below figure:

Answer: Perform the following steps to create such an application:


1. Create a new application in NetBeans IDE and add a frame to it.
2. Add a Table control by dragging and dropping it onto the frame from the Swing controls
section of Palette pane, as shown in the below figure:

3. Right-click on the table and change the variable name as StdntTbl.


4. While keeping the table selected, click the ellipsis button of the model property in the
Properties dialog box. A dialog box appears.
5. Set the number of rows (initially) as well as the heading of columns in this dialog box. Now,
specify the column headings as RollNO, Name, Class, Subject, MaxMarks, MarksObt. Set
the rows field in the button left corner as 0 (zero), because we do not want any initial rows
(rows will be added during the runtime). After that, click the OK button, as shown in the
below figure:

41

Adding Column Names to Tables Model


After adding the columns heading to the StdntTbl table, your application will appear shown
in the below figure:

42

The Application GUI after Adding Column Headings


6. Now, add the text fields and button controls to your application and arrange them as shown
in the below figure:

7. To append the values that are entered in the text fields to the StdntTbl table as rows, you
need to double click the Add Row button and type the following code:
Object [] addRows={jTextField1.getText(),jTextField2.getText(),jTextField3.getText(),
jTextField4.getText(), jTextFiled5.getText(), jTextField6.getText()}; DefaultTableModel
dtm=(DefaultTableModel) jTable1.getModel(); dtm.addRow(addRows);
jTextField1.setText(" "); jTextField2.setText("
"); jTextField3.setText(" ");
jTextField4.setText(" "); jTextField5.setText("
"); jTextField6.setText(" ");
To display total number of records in table, double click the Count Total Record button and
add the following lines of code:
JOptionPane.showMessageDialog(null,"Total
are :"+jTable1.getRowCount());

Number

of

records

8. Finally double click the Exit button and type the following code to the action event handler
of this button:
System.exit(0);
43

9. Save the application and run it. The output will be as shown in the below figure:

The Output of the New Application

Getting Total Records in the Table

Application 4:
Create an application consisting of a color chooser, buttons and a label as
shown in the below figure:
44

Answer: Perform the following steps to design an application similar to the one as shown
in the above figure:
1. Create a new application using NetBeans IDE and add a frame to the application.
2. Now drag a color chooser control from the swing windows section of the Palette pane
and drop it on the frame as shown in the below figure.

3. Add three button controls and one label control to the frame and name them
accordingly. Moreover, ensure that the Opaque property of the label is set to true by
selecting its check box. If you do not set this property, you will not able to view the filled
45

color. After adding all the components to the frame, your application will look similar to
the one shown in the below figure.

4. First you need to include import statement import java.awt.Color; at the top of your
application. Now double click the apply foreground button (forBtn) button and add the
following code in the action event handler of this button:
Color forgrndColor=jColorChooser1.getColor();
disLabel.setForeground(forgrndColor);
5. Double click the apply Background (backBn) button and add the following code in the
action event handler of this button:
Color backgrndColor= jColorChooser1.getColor();
disLabel.setBackground(backgrndColor);
6. Double click the exit (exitBtn) button and add the following code in the action event
handler of this button:
System.exit(0);

7. Finally save and run your application. The output is shown in the below figure:
46

Using the application shown in the above figure, you can choose a desired color from the color
chooser control by selecting any of the three tabs: Swatches, HSB and RGB.

The Output of the Application

Application 5:
47

Create a Quiz application similar to the one shown in the below figure:

The main frame QuizForm.java provide the following functionality:


The main frame QuizForm.java consists of a menu bar containing three menus: Hardware,
Software and Exit. The Hardware menu contains three menu items (namely- Input Devices,
Memory Devices and Output Devices), the Software menu contains two menu items
(namely- System Software and Application Software) and Exit menu to exit the application.
Answer: Perform the following steps to design an application similar to the one as shown
in the above figure:
1. Create a new application using NetBeans IDE and add a frame (QuizForm.java.) to the
application. Change the title of the frame TEST YOUR KNOWLEDGE.
2. Add menus and menu items to the main frame QuizForm.java. Add two label controls by
dragging and dropping it onto the frame from the Swing controls section of Palette pane.
Change the text of jLabel1 TEST YOUR KNOWLEDGE and change the icon of
jLabel2 that display an image for Quiz as shown in the below figure:

48

3. Add a new frame HardwareInputJPanel.java and design it as shown in the below figure:

4. Similarly design add new frames


HardwareOutputJPanel.java, HardwareMemoryJPanel.java,SoftwareApplicationJPanel.java
and SoftwareSystemJPanel.java as shown in the below figures:
49

HardwareOutputJPanel.java

50

HardwareMemoryJPanel.java

SoftwareApplicationJPanel.java

SoftwareSystemJPanel.java

51

5. The code for main frame (QuizForm.java) is as below:


private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt)
{
HardwareInputJPanel();

HardwareInputJPanel s=new
s.setVisible(true);:

}
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt)
{
HardwareOutputJPanel s=new HardwareOutputJPanel();
s.setVisible(true);
}
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt)
{
HardwareMemoryJPanel s=new HardwareMemoryJPanel();
s.setVisible(true);
}

private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt)


{
SoftwareSystemJPanel s=new SoftwareSystemJPanel();
s.setVisible(true);
}
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt)
{
SoftwareApplicationJPanel s=new SoftwareApplicationJPanel();
s.setVisible(true);
}

6. The code for Submit Button of HardwareInputJPanel.java is as follows:


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jRadioButton3.isSelected())
jLabel6.setText("Correct");
else
52

jLabel6.setText("Incorrect"); if
(jRadioButton8.isSelected())
jLabel7.setText("Correct"); else
jLabel7.setText("Incorrect");
}
7. The code for Submit Button of HardwareOutputJPanel.java is as follows:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{

if
(jRadioButton4.isSelected())
jLabel3.setText("Correct"); else
jLabel3.setText("Incorrect"); if
(jRadioButton7.isSelected())
jLabel5.setText("Correct"); else
jLabel5.setText("Incorrect");
}

8. The code for Submit Button of HardwareMemoryJPanel.java is as follows:


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
if (jRadioButton3.isSelected())
jLabel3.setText("Correct"); else
jLabel3.setText("Incorrect");
if (jRadioButton8.isSelected())
jLabel5.setText("Correct"); else
jLabel5.setText("Incorrect");
}

9. The code for Submit Button of SystemSoftwareJPanel.java is as follows:


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jRadioButton2.isSelected())
jLabel4.setText("Correct"); else
jLabel4.setText("Incorrect"); if
(jRadioButton5.isSelected())
jLabel7.setText("Correct"); else
jLabel7.setText("Incorrect");
}

53

10. The code for Submit Button of ApplicationSoftwareJPanel.java is as follows:


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jRadioButton4.isSelected())
jLabel3.setText("Correct"); else
jLabel3.setText("Incorrect"); if
(jRadioButton5.isSelected())
jLabel5.setText("Correct"); else
jLabel5.setText("Incorrect");
}
11. The code for Close sub menu of Exit menu is as follows: System.exit(0) ;
12. Finally save and run your application. The output is shown in the below figures:

54

55

56

57

You might also like