Java Advanced Programs
Java Advanced Programs
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
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.
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
625/750/-
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)
(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);
12
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
{
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
Ans:
(a) int w=0;
if(jCheckBox1.isSelected())
w=w+100;
if(jRadioButton3.isSelected())
(w*10)/100;
w=w-
int cw=d*w;
jLabel6.setText(+cw);
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:
Ans:
(a) float
q=Float.parseFloat(jTextField2.getText());
float
p=Float.parseFloat(jTextField3.getText());
(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
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.
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(
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
26
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:
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
Allows
the
Answer:
Perform the following steps to create the required GUI application:
1.
2.
3.
4.
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
41
42
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:
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.
Application 5:
47
Create a Quiz application similar to the one shown in the below figure:
48
3. Add a new frame HardwareInputJPanel.java and design it as shown in the below figure:
HardwareOutputJPanel.java
50
HardwareMemoryJPanel.java
SoftwareApplicationJPanel.java
SoftwareSystemJPanel.java
51
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);
}
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");
}
53
54
55
56
57