Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Program 1: Design an application for a Football match’s Scoreboard.

Each
team’s score should be maintained. Whenever a team scores a goal, it should be
reflected on the Scoreboard. When the result is declared, depending upon the
scorecard, the winning team should be declared.

 Design the following interface in NetBeans IDE.

declRes

tAGoals

tBGoals

GoalOfA GoalOfB

result

 Set the name of controls as mentioned above.


Add following code in the action event handlers of respective push buttons.
GoalOfA: ActionPerofrmed method-
String v1=tAGoals.getText();
int ga= Integer.parseInt(v1);
ga=ga+1;
tAGoals.setText(“”+ga
GoalofB: ActionPerformed method.
String v1=tBGoals.getText();
int gb=Integer.parseInt(v1);
tbGoals.setText(“”+gb);
declRes:ActionPerformed method.
String v1=tAGoals.getText();
int ga= Integer.parseInt(v1);
String v2=tbGoals.getText();
int gb=Integer.parseInt(v2)

1|Page
String res= (ga>gb) ? “Team A wins” : (ga<gb) ? “Team B wins” : “Draw”);
result.setText(res);
 Save and run an application. A sample run would be:

2|Page
Progrma2: Design a GUI application that has a list and a few controls such
as Label, a button and a text field. The list displays some colours. When a
user select a colour from the list, the background of the appropriate
control(depending upon user’s choice) should be changed.

 Design the following interface in NetBeans IDE.

Lbl

colorsLst Btn

TF

lblChk tfChk

btnChk
 Set the name of controls as mentioned above.
 Make sure to set opaque property of the label to true(i.e., check its box) so that the
background color of the label is reflected.
 Since we need to work with colors, thus we need to import Color class of java.awt. Thus,
in the source editor, at the top of all the code, type:
import java.awt.Color;
Now we can use colors using Color<colorname>syntax.
 Now add code to valueChanged() event handler of ListSelection event of list colorLst i.e.
right click on the list, select Events ListSelection valueChanged and then type
code into it as given below:
int i;
Color x= Color.WHITE;
i= colorsLst.getSelectedIndex();
switch(i){
case 0: x=Color.RED;
break;
case 1: x=Color.BLUE;
break;
case 2: x=Color.GREEN;

3|Page
break;
case 3: x=Color.MAGENTA;
break;
case 4: x=Color.CYAN;
break;
case 5: x=Color.YELLOW;
break;
case 6: x=Color.GRAY;
break;
}
if (lblChk.isSelected( ))
Lbl.setBackground(x);
else
Lbl.setBackground(Color.WHITE);
if (btnChk.isSelected( ))
Btn.setBackground(x);
else
Btn.setBackground(Color.WHITE);
if (tfChk.isSelected( ))
TF.setBackground(x);
else
TF.setBackground(Color.WHITE);
 Add the same code to actionPerformed( ) event handlers of check boxes: lblChk, btnChk
and tfChk.
 Save and run your project. It will run in the desired manner.

4|Page
Program3: Design a GUI application that display food types in a combobox and
foods pertaining to selected type in a list box.
 Design the following interface in NetBeans IDE.

OkBtn
Foodlst
ExitBtn

ftypCB

 Set the name of controls as mentioned above.


 Add following code in the action event handlers of respective push buttons and List.
Foodlst: ActionPerofrmed method-
String food=(String)Foodlst.getSelectedValue( );
if(food.equals(“Cheddar Cheese”)){
ftypCB.setSelectedItem(“Dairy”);
}
else if(food.equals(“Processed Cheese”)){
ftypCB.setSelectedItem(“Dairy”);
}
else if(food.equals(“Milk”)){
ftypCB.setSelectedItem(“Dairy”);
}
else if(food.equals(“Curd”)){
ftypCB.setSelectedItem(“Dairy”);
}
else if(food.equals(“Ghee”)){
ftypCB.setSelectedItem(“Dairy”);
}
else if(food.equals(“Orange”)){

5|Page
ftypCB.setSelectedItem(“Fruits and Vegetables”);
}
else if(food.equals(“Apple”)){
ftypCB.setSelectedItem(“Fruits and Vegetables”);
}
else if(food.equals(“Banana”)){
ftypCB.setSelectedItem(“Fruits and Vegetables”);
}
else if(food.equals(“Muffins cake”)){
ftypCB.setSelectedItem(“Bread and Cereals”);
}
else if(food.equals(“Brown Bread”)){
ftypCB.setSelectedItem(“Bread and Cereals”);
}
ExitBtn: ActionPerofrmed method-
System.exit(0);
OkBtn: ActionPerofrmed method-
JOptionPane.showMessageDialog(null,“You have selected”+Foodlst.getSelectedValue( ));
 Save and run an application. A sample run would be:

6|Page
Program4: Design a GUI application that gives all the information of places.
 Design the following interface in NetBeans IDE.

JamBtn
GoaBtn HaridwBtn
SriBtn

infoTA

imgLbl

 Set the name of controls as mentioned above.


 We need to import ImageIcon class of java.awt. Thus, in the source editor, at the top of all
the code, type:
import javax.swing.ImageIcon;
 Add following code in the action event handlers of respective push buttons.
GoaBtn: ActionPerofrmed method-
imgLbl.setIcon(new ImageIcon(“C:\\Users\\ Documents\\Goa.jpg”));
infoTA.append(“Place: Goa \n Means of transport: Aeroplane \n Stay: 5nights & 6days in
a 3star hotel near\n Calangute Beach \n Package comprises: Breakfast, lunch, Dinner &
\n whole tour around North and South Goa. \n Amount of ticket: Rs 24500/- per
person”);
SrinBtn: ActionPerofrmed method-
imgLbl.setIcon(new ImageIcon(“C:\\Users\\ Documents\\Srinagar.jpg”));
infoTA.append(“Place: Srinagar\n Means of transport: Aeroplane \n Stay: 3nights
4days in a 3star hotel near\n Dal Lake\n Package comprises: Breakfast, lunch,
Dinner & \n Amount of ticket: Rs 24500/- per person”);
JamBtn: ActionPerofrmed method-
imgLbl.setIcon(new ImageIcon(“C:\\Users\\ Documents\\Jammu.jpg”));
infoTA.append(“Place: Jammu \n Means of transport: Aeroplane \n Stay: 3nights
4days in a 3star hotel near\n Katra \n Package comprises: Breakfast, lunch,
Dinner & \n whole tour around Jammu \n Amount of ticket: Rs 15000/- per person”);
HaridwBtn: ActionPerofrmed method-
imgLbl.setIcon(new ImageIcon(“C:\\Users\\ Documents\\Haridwar.jpg”));
infoTA.append(“Place: Haridwar\n Means of transport: Volvo\n Stay: 2nights

7|Page
3days in a 3star hotel near\n River Ganga\n Package comprises: Breakfast, lunch,
Dinner & \n whole tour around Haridwar n\ Amount of ticket: Rs 10000/- per person”);
 Save and run an application. A sample run would be:

8|Page
Program5 : Write a method that takes a number as argument and displays the
sum of all the digits in the number. For example if the argument passed in 354,
the procedure should display 12 (i.e. 3+5+4).
Implement the method through a GUI application that obtains a number in a
text field, computes the sum of its digits and displays in a label.
 Design the following interface in NetBeans IDE.

numTF

SumBtn

resLbl

 Set the name of controls as mentioned above.


 Write method to compute sum of digits
Add following method above the main( ) method of your application in source editor:
int addDigits (int n) {
int s = 0;
int dig;
while(n > 0) {
dig = n%10;
s = s+dig;
n = n/10;
}
return s;
}
Add following code in the action event handlers of respective push buttons.
SumBtn: ActionPerofrmed method-
int num = Integer.parseInt(numTF.getText( ));
int sum = Integer.parseInt(num);
resLbl.setText(“Sum of its digits is: “+sum);

9|Page
 Save and run an application. A sample run would be:

10 | P a g e
Program6: Design a GUI application to calculate the GCD(HCF) of two numbers.
Write code for the command button (cmdGcd) to print the GCD in the label
(lblGcd).
 Design the following interface in NetBeans IDE.

Num1TF

GCDTF

Num2TF

GCDBtn

 Set the name of controls as mentioned above.


 Add following code in the action event handlers of respective push buttons.
GCDBtn : ActionPerofrmed method-
int n1 =Integer.parseInt(Num1TF.getText( ) . toString( ));
int n2 =Integer.parseInt(Num2TF.getText( ) . toString( ));
int t;
while(n2!=0)
{
t = n2;
n2 = n1%t;
n1 = t;
}
GCDTF.setText(“”+n1);
}
 Save and run an application.

11 | P a g e
Program7: Design an application for theatre booking system. Write a code for
Book Seat button(bookBtn) to print the total amount in (amtTF).
 Design the following interface in NetBeans IDE.

StallsRb

CircleRb
UCircleRb

BoxRb

pricelbl

SeatTF

CashRb

VisaRb
Aexpress

Mcard

Bookbtn payableAmt

 Set the name of controls as mentioned above.


 We need to import showMessage class of java.awt. Thus, in the source editor, at the top of
all the code, type:
import javax.swing.JOptionPane;
 Add following code in the action event handlers of respective push buttons and radio
buttons.
StallsRb: ActionPerofrmed method-
boolean stall = StallsRb.isSelected( );
pricelbl.setText(“625”);
CircleRb: ActionPerofrmed method-
boolean circle = CircleRb.isSelected( );
pricelbl.setText(“750”);

12 | P a g e
UCircleRb: ActionPerofrmed method-
boolean circle = UCircleRb.isSelected( );
pricelbl.setText(“850”);
BoxRb: ActionPerofrmed method-
boolean circle = BoxRb.isSelected( );
pricelbl.setText(“1000”);
SeatTF: ActionPerofrmed method-
int seat = Integer.parseInt(SeatTF.getText( ));
if(seat < 1)
JOptionPane.showMessageDialog(null, “ERROR! Please enter the no. of seats you
required”);
BookBtn: ActionPerofrmed method-
int price = Integer.parseInt(pricelbl.setText( ));
int seat = Integer.parseInt(SeatTF.getText( ));
int amount = price * seat;
boolean cash = CashRb.isSelected( );
boolean visa = VisaRb.isSelected( );
boolean aexp = Aexpress.isSelected( );
boolean masterca = Mcard.isSelected( );
if(cash == true){
payableAmt.setText(“Cash payment of Rs” + result + “/-“);
}
else if(visa == true){
payableAmt.setText(“Visa payment of Rs” + result + “/-“);
}
else if(aexp == true){
payableAmt.setText(“American Express payment of Rs” + result + “/-“);
}
else if(masterca == true){
payableAmt.setText(“Master Card payment of Rs” + result + “/-“);
}

13 | P a g e
 Save and run an application. A sample run would be:

14 | P a g e
Program8 : Program to check wheather a string is a palindrome or not.
 Design the following interface in NetBeans IDE.

StrTf

submitBtn

outLbl

 Set the name of controls as mentioned above.


 Now add the following code in the action event handler of Submit button :
String str = strTF.getText( );
showPalindrome(str);
 As the action event handler invokes a method namely showPalindrome( ). Write the code as
given below, above the method main( )in source editor window.
public void showPalindrome(String s) {
StringBuffer out = new StringBuffer(s);
if(isPalindrome(s))
s = s+” : Is a palindrome!” ;
else if(isPalindrome2(s))
s = s+” : IS a palindrome if you ignore case!”;
else
s = s+” : IS NOT a palindrome!”;
outLbl.setText(s);
} //end showPalindrome
o /* Returns true if string of characters is a palindrome. */
public boolean isPalindrome(String s) {
StringBuffer reversed = (new StringBuffer(s)).reverse( );
return s.equals(reversed.toString( ));
} //end isPalindrome
15 | P a g e
o /* Returns true if string of characters is a palindrome when case is Ignored. */
public boolean isPalindrome2(String s) {
StringBuffer reversed = (new StringBuffer(s)).reverse( );
return s.equals(reversed.toString( ));
} //end isPalindrome
 Save and run an program. A sample run would be:

16 | P a g e
Program 9: Program to illustrate the usage and functionality of following String
methods :
(i) Length( ) (ii) charAt( ) (iii) compareTo( )
(iv) equals( ) (v) concat( ) (vi) indexOf( )
(vii) lastIndexOf( ) (viii) substring( ) (ix) replace( )
(x) toLowerCase( ) (xi) toUpperCase( )

 Design the following interface in NetBeans IDE.

name1TF
name3TF

submitBtn
name2TF

outTA

 Set the name of controls as mentioned above.


 Now add the following code in the actionPerformed( ) event handler of Submit button :
String name1 = new String( );
name1 = name1TF.getText( );
String name2 = new String( );
name2 = name2TF.getText( );
String name3 = new String( );
name3 = name3TF.getText( );
// Sequence of method calls illustrating string manipulation
lengthOfString(name1); //#1
characterAtIndexN(name1); //#2
compareStrings(name1,name2); //#3
concatination1(name1,name2); //#4
concatination2(name1,name2); //#5
occurrencesOfN(name3); //#6
subString(name3); //#7
replaceCharacter(name3); //#8
caseConversion(name1); //#9

17 | P a g e
 Above the method main( ), write codes for the methods being invoked by
SubmitBtnActionPerformed( ) as we have given below:
// #1 LENGTH OF STRING :
// Example method to illustrate use of length method
public void lengthOfString(String name)
{
outTA.append(“LENGTH OF STRING”);
outTA.append(“\n------------------------------------\n);
outTA.append(“Length of string”+ name +”is”+ name.length( ));
}

// #2 CHARACTER AT INDEX N :
// Example method illustrating use of charAt method.
public void characterAtIndex(String name)
{
outTA.append(“\n\nCHARACTER AT INDEX \n”);
outTA.append(“---------------------------------------\n”);
outTA.append(“ At 0 the character is “+ name.charAt(0);
outTA.append(“\n At 3 the character is + name.charAt(3);
}

// #3 COMPARE STRINGS :
// Example method illustrating use of campareTo and equals methods
public void compareStrings(String name1, String name2)
{
outTA.append(“\n\n COMPARE STRINGS \n”);
outTA.append(“----------------------------------------\n”);
//Using the compareTo method
outTA.append(“Compare”+name1+”and”+name2+”=”+ name1.compareTo(name2));
outTA.append(“Compare”+name2+”and”+name1+”=”+ name2.compareTo(name2));
outTA.append(“Compare”+name2+”and”+name2+”=”+ name3.compareTo(name2));
outTA.append(“\n” +name1+ “and” +name2+ “are”);
//Using the compareTo method within an if-else statement
if(name1.compareTo(name2) == 0)
outTA.append(“the same”);
else
outTA.append(“not the same”);
// The equals method

18 | P a g e
outTA.append(“\n Equals”+name2+”and”+name1+”=”+ name2.equals(name1));
outTA.append(“\n Equals”+name2+”and”+name2+”=”+ name2.equals(name1));
}

// #4 CONCATENATION 1 :
// Example method illustrating use of concat method
public void concatination1(String name1, String name2)
{
outTA.append(“\n\n CONCATENATION \n”);
outTA.append(“--------------------------------------\n”);
name1 = name1.concat(“ “);
name2 = name1.concat(name2);
outTA.append(“name1= “ +name1);
}

// #5 CONCATENATION 2 :
// Example method illustrating use of +(concatenation) operator. Some effect as above.
public void concatination2(String name1, String name2)
{
outTA.append(“\n\n CONCATENATION 2 \n”);
outTA.append(“--------------------------------------\n”);
name1= name1 + “ “+ name2;
outTA.append(“name1= “ + name1);
}

// #6 OCCURRENCES OF N:
// Exmaple method illustrating use of indexOf and LastIndexOf method /
public void occurrencesOfN(String name)
{
outTA.append(“\n\n OCCURRENCES OF n”);
outTA.append(“\n----------------------------------\n”);
// Find first and last occurances of ‘n’ in argument
outTA.append(“\n First occurance of ‘n’ in” +name+ “is at index” +name.indexOf(‘n’));
outTA.append(“\n Last occurance of ‘n’ in” +name+ “is at index” +name.lasstindexOf(‘n’));
// What happens if we are looking for the index of something
// that does not exist in the given string?
outTA.append(“\n First occurrence of ‘Z’ in” +name+ “is at index” + name.indexOf(‘Z’));
}

19 | P a g e
// #7 SUBSTRINGS :
// Example method illustrating use of substring method
public void substring(String name1)
{
outTA.append(“\n\n SUBSTRINGS”);
outTA.append(“\n----------------------------“);
// Substring from index 4 onwards
outTA.append(“\n Substrings form index 4 onwards = “+name1.subString(4));
// Substring comprising all of input
String name2 = name1.substring(0, name1.length( ));
outTA.append(“\n Entire copy of” +name1+ “=” +name2);
// Substring from N to M
name2 = name1.substring(0,2);
outTA.append(“\n \n Substring from index 0 to 2 =”+ name2);
// Substring made up of name2 from above (first three charcters
// of name1) plus substring from the first occurrence of a space
//(‘ ‘) in name 1 to three characters beyond it.
name2 = name2.concat(name1.substring(name1.indexOf(‘ ‘), name1.indexOf(‘ ‘)+3));
outTA.append(“\n name2 = “ + name2);
}

// #8 REPLACE CHARACTER :
// Example method illustrating use of replace method
public void replaceCharacter(String name)
{
outTA.append(“\n\n REPLACE CHARACTER”);
outTA.append(“\n--------------------------------------“);
// Replace R and O with.
name = name.replace(‘R’,’.’);
name = name.replace(‘O’,’.’);
outTA.append(“\n name = “ +name);
}

// #9 CASE CONVERSION :
// Example method illustrating use of toLowercase and toUppercase methods.
public void caseConversion(String name1)
{
outTA.append(“\n\n CASE CONVERSION”);

20 | P a g e
outTA.append(“\n------------------------------------------“);
// Upper to lower case conversion
name1 = name1.toLowerCase( ));
outTA.append(“\n name1 = “ + name1);
// Lower to upper case conversion
name1 = name1.toUpperCase( ));
outTA.append(“\n name1 = “ + name1);
// Substrings and case conversion
String name2 = name1.substring(0,1);
String name3 = name1.substring(1,5);
name2= name2.concat(name3.toLowerCase( ));
outTA.append(“\n name2 =” + name2);
}
 Save and run an program. A sample run would be:

21 | P a g e
Program10: Design a data connectivity application tha fetches data from EMPL
table.
 Design the following interface in NetBeans IDE.

 Set the name of controls as mentioned below.


(i) List(fieldList) (ii) Radio buttons(SalRB, DepNoRB, HiredateRB, ascRB, descRB)
(iii) Combo box(jobCB, depnoCBx) (iv) Button(fetchBtn) (v) Table(outTbl)
 The application work as per following specifications:
1. The user should be able to choose any field(s) in the select list.
2. The sort criteria should be decided by user for Order By clause.
3. The filtering conditions for where clause should be specified by user for job and/or dept
no fields. Go only for equality comparisions.
4. As per the specified details the data should be fetched from EMPL table and shown in
tabular format.
 Emport Commands
import javax.swing.JOptionPane;
import java.sql.*;
import javax.swing.table.DefautlTableModel;
 Add following code in the action event handlers of respective push buttons.
fetchBtn: ActionPerofrmed method-
Object fld[ ] = fieldList.getSelectedValues( );
int len = fld.length;
String qry = “SELECT”;
int I;
22 | P a g e
String field = (String) fld[0];
qry = qry + field;
for(i = 1 ; i < len; i++) {
String field1 = (String) fid[i];
qry = qry + “ , “ + field1;
}
qry = qry + “ FROM EMPL”;
String filter1, filter2;
filter1 = (String) jobCBx.getSelectedItem( );
filter2 = (String) depnoCBx.getSelectedItem( );
if ( filter1.compareTo(“ANY”)!=0 && filter2.compareTo(“ANY”)!=0) {
qry = qry + “WHERE Job = ‘ “+filter1+” ‘ “;
qry = qry + “AND deptno = “ +filter2;
}
else if (filter1.compareTo(“ANY”)!=0)
qry = qry + “WHERE Job = ‘”+filter1+” ‘ “;
else if (filter2.compareTo(“ANY”)!=0)
qry = qry + “WHERE deptno = “ + filter2;
if (SalRB.isSelected( ))
qry = qry + “ORDER BY Salary” ;
else if (DepNoRB.isSelected( ))
qry = qry + “ORDER BY deptno” ;
else if (HiredateRB.isSelected( ))
qry = qry + “ORDER BY hiredate” ;
if (ascRB.isSelected( ))
qry = qry + “asc”;
else if(descRB.isSelected( ))
qry = qry + “desc”;
qry = qry + “;” ; // final query string ready
// Data Connectivity code begins.
DefaultTabeModel dm = (DefaultTableModel) outTbl.getModel( );
try {
Class.forName(“java.sql.Driver);
Connection con = DriverManager.getConnection(“jdbc:mysql://localhost/test”
,”root”,”xyz”);
Statement stmt = con.createStatement( );
ResultSet rs = stmt.executeQuery(qry);
int empnoStr = 0;

23 | P a g e
String enameStr = ””;
String jobStr = “ “;
int mgrStr = 0;
Date hiredateStr = null;
float salStr = 0;
float commStr = 0;
float deptnoStr = 0;
//Remove existing rows from table if any
while (dm.getRowCount( ) > 0)
dm.removeRow(0);
while (rs.next( )) {
for( i = 0; i< len ; ++i) {
String field1 = (String) fld[i] ;
if( field1.compareToIgnoreCase(“Empno”)== 0)
empnoStr = rs.getInt(“empno”);
else if( field1.compareToIgnoreCase(“Ename”)==0)
enameStr = rs.getString(“ename”);
else if(field1.compareToIgnoreCase(“Job”)==0)
jobStr = rs.getString(“job”);
else if(field1.compareToIgnoreCase(“mgr”)==0)
mgrStr = rs.getInt(“mgr”);
else if(field1.compareToIgnoreCase(“Hiredate”)==0)
hiredateStr = rs.getDate(“hiredate”);
else if(field1.compareToIgnoredCase(“Sal”)==0)
salStr = rs.getFloat(“sal”);
else if(field1.compareToIgnoredCase(“Comm”)==0)
commStr = rs.getFlod(“Comm”);
else if(field1.compareToIgnoredCase(“deptno”)==0)
deptnoStr = rs.getInt(“deptno”);
}
dm.addRow(new Object[ ] {empnoStr, enameStr, jobStr, mgrStr, hiredateStr, salStr,
commStr, deptnoStr});
}
rs.close( );
stmt.close( );
con.close( );
}
catch(Exception e) {

24 | P a g e
JoptionPane.showMessageDialog(null, “Erroe in connectivity);
}
 Save and run an application. A sample run would be:

25 | P a g e

You might also like