0% found this document useful (0 votes)
12 views47 pages

SBL Oopm - Java Lab

Uploaded by

thebabadrive
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views47 pages

SBL Oopm - Java Lab

Uploaded by

thebabadrive
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INDEX

Sr. No Name of Experiment


01 a) Program to check whether given integer is Perfect number or not using Selection
statements.
b) Program to find sum of digits in a given integer.
02 Write a program to calculate area of Circle and area of Rectangle using method
overloading.
03 Study of classes, members of classes and working with object.
04 Study of String class functions.
05 Study of Single Inheritance.
06 Write a program to input two numbers from user and display the answer of
dividing first number by second number on Exception handling in Java.
07 Write a menu driven program to work with list of names, with following
options like 1. Add name, 2. Remove name, 3. Display list Using Vector class.
08 Demonstration of Multithreading
09 Using Applet and Graphics class draw a simple face on applet window.
10 Write a GUI based application using AWT, which inputs two numbers and
displays the sum. Use Frame, Buttons, Text boxes and Lables. Use event
handling to get the answer.
11 Design GUI with Radio Button to Select engineering branch.
12 Drawing different geometric Shapes using JavaFX
13 Creating Login windo using JavaFX
14 Mini Project
Practical 1:
Aim: Program to check whether given integer is Perfect number or not using Selection
statements.

Theory:
Selection Statements:
if: The statement is used to select what part of the program should execute according to
different conditions arising in a program.
It has following three general syntaxes
1. if ( condition )
statement
2. if( condition )
Statement1
else
Statment2

3. if ( condition1)
Statement1
else if ( condition2)
Statement2
else if ( condition3)
Statement3

else
Statement..n

The if, if-else and if-else if statements should not have semicolons. If multiple statements are to be
written for one condition, then those statements must be enclosed inside the curly braces.
Description:
Perfect no is four digit (e.g. 1681) which is a perfect square. Also, the numbers formed by its left two
digits (e.g.16) and right two digits (e.g. 81) are also perfect squares.
Program:
import [Link].*;
class Pract01A
{
public static void main (String[] args)
{
Scanner sc = new Scanner([Link]);
int no, lf, rt;
double r1, r2, r3;
[Link]("Enter a number :");
no = [Link]();
if( no>=1000 && no<= 9999 )
{
r1 = [Link](no);
if( r1 == [Link](r1))
{
lf = no / 100;
rt = no % 100;
r2 = [Link]( lf);
r3 = [Link](rt);
if( r2 == [Link](r2) && r3 == [Link](r3))
[Link]("The number is Perfect number");
else
[Link]("The number is Not a perfect number");
}
else
[Link]("Given number is Not a perfect number");
}
else
[Link]("Given number is Not 4-digit number");
}
}

Output:
Enter a number: 1681
Given number is Perfect number
Enter a number :2536
Given number is Not a perfect number
b) Program to find sum of digits in a given integer.
e.g. input number=3482, then sum of digits =17

Theory:
Iteration statements: (Looping statements):
These statements make some part of program repeat for multiple time till some condition is
true. The statements are while, for, do-while. (same as those in C++).
while: The looping statement is used to repeat a block of statements till some condition is
true. The condition should be a Boolean expression.
while ( condition)
statements

Program :
import [Link].*;
class Pract01B
{
public static void main (String[] args)
{
Scanner sc = new Scanner([Link]);
int no, d, sum=0;
[Link]("Enter a number :");
no = [Link]();
while( no != 0 )
{
d = no % 10;
sum = sum + d;
no = no / 10;
}
[Link]("Sum of digits=" + sum);
}
}

Output :
Enter a number :6253
Sum of digits=16
Practical 2:
Aim: Write a program to calculate area of Circle and area of Rectangle using method
overloading

Theory:
Java class can consist of multiple methods with the same name but different type of
parameters or different number of parameters. Such methods are called Overloaded methods.
This feature of Java is called as Method overloading.
This is a feature of OOP called Polymorphism. This, allows defining multiple methods with
same name in the same scope (here, same class). But the methods are differentiated by their
parameters.
Overloaded Methods can have any combination of data-types, but each combination should
be unique. This unique definition of each method is also called Signature of a method.
e.g. int add (int a, int b), float add (float a, float b), long add (long a, int b), and int add (int a,
int b, int c) are all treated as different methods. These definitions are called Signatures.
Program:
import [Link].*;
class Pract02
{
static void area( int len, int br)
{
int a = len * br;
[Link]("Area of Rectangle=" + a );
}

static void area( double r )


{
double a = 3.14 * r * r;
[Link]("Area of Circle=" + a );
}

public static void main (String[] args)


{
Scanner sc = new Scanner([Link]);
int l, b;
double r;
[Link]("Enter Length and breadth :");
l = [Link]();
b = [Link]();
area( l, b );

[Link]("Enter radius :");


r = [Link]();
area( r );

}
}

Output :
Enter Length and breadth :
12
4
Area of Rectangle=48

Enter radius :10


Area of Circle=314.0
Practical:3
Aim: Study of classes, members of classes and working with object.

Program Statement: Define a class Account with following:


data members: Account number, Name, Balance amount.
methods: to input data, output data, deposit amount and withdraw amount
Assume Rs. 2000/- is minimum balance for account.

Program:
import [Link].*;
class Account
{
int actno;
String name;
double balance;
void input()
{
Scanner sc = new Scanner([Link]);
[Link]("Enter Name :");
name = [Link]();
[Link]("Enter Act. No :");
actno = [Link]();
[Link]("Enter Amount in account :");
balance = [Link]();
}
void output()
{
[Link]("-- Account info. --");
[Link]("Account no :" + actno);
[Link]("Name :" + name);
[Link]("Balance Amount :" + balance);
}
void deposit(double a)
{
balance += a;
}
void withdraw(double a)
{
if( balance-a >=2000)
balance -= a;
else
[Link]("* Insufficient Balance");
}
}
class Pract03
{
public static void main (String[] args)
{
Scanner sc = new Scanner([Link]);
double amt;
Account act = new Account();
[Link]();
[Link]();
[Link]("- Enter amount to deposit :");
amt = [Link]();
[Link](amt);
[Link]();

[Link]("- Enter amount to withdraw :");


amt = [Link]();
[Link](amt);
[Link]();
}
}
Output :
Enter Name :Ajay
Enter Act. No : 2345
Enter Amount in account : 10000
-- Account info. --
Account no :2345
Name :Ajay
Balance Amount :10000.0
- Enter amount to deposit :4500
-- Account info. --
Account no :2345
Name :Ajay
Balance Amount :14500.0
- Enter amount to withdraw :5000
-- Account info. --
Account no :2345
Name :Ajay
Balance Amount :9500.0
Practical:4

Aim: Study of String class functions.

Theory:

Strings in Java:
Any data enclosed in a double quotation symbols (“ ”) is a string in Java.
Also, strings are represented by Java class String.
e.g.
String s = “Hello Java”;
Here, an object is created that holds string ‘Hello Java’ and the reference variable s refers to it.
Every string value in Java is an object of predefined Java class String.
The class is included in Java’s default package [Link].
The String class has a lot of methods to work with string data e.g. Comparing two strings, reading
character at a required index in the string, Converting all letters in a string to upper/lower case etc.
The String class methods that are used to alter string do not alter the original string contents but they
return a new string object, which consist of an altered character.
Almost all the string methods are case sensitive.
The method that deal with the index of characters, generate
IndexOutOfBoundsException if an index outside the string length is accessed.
e.g. [Link]( 10) ; will generate above exception.

Program:

import [Link].*;

class Pract04

public static void main (String[] args)

String a = "Abcd abc pqr", b ="XYZ PQ", c ="Xyz Pq";

int j;

String r;

char ch;

[Link]("- String class methods -");

j = [Link]();
[Link]("Length =" + j);

ch = [Link]( 2 );

[Link]("char. at index 2=" + ch);

[Link]("Index of c =" + [Link]('c') );

r = [Link]( 1, 6);

[Link]("Substring 1 to 5 =" + r );

[Link]("Substring from 2=" + [Link](2) );

j = [Link]( 'b');

[Link]("last index of b=" + j );

j = [Link]( 'R');

[Link]("index of R=" + j );

j = [Link]( "bc");

[Link]("index of bc=" + j );

if( [Link](c))

[Link]("Strings are equal" );

else

[Link]("Strings are not equal" );

String ar[] = [Link](" ");

[Link]("Words in string" );

for( j=0; j<[Link]; j++)

[Link]( ar[j] );

r = [Link]();

[Link]("Upper case of c=" + r );

[Link]("Lower case of c=" + [Link]() );

char chrs[] = [Link]();

[Link]("Chars. in the string :");

for( j=0; j<[Link]; j++ )


[Link](chrs[j] + " ");

Output :

- String class methods -


Length =6
char. at index 2=c
Index of c =2
Substring 1 to 5 =bcd a
Substring from 2=Z PQ
last index of b=6
index of R=-1
index of bc=1
Strings are not equal
Words in string
Abcd
abc
pqr
Upper case of c=XYZ PQ
Lower case of c=xyz pq
Chars. in the string :X Y Z P Q
Practical: 5
Aim: Study of Single Inheritance.

Theory:
It’s a feature of OOP by virtue of which an object can acquire (inherit) some or all the
members of another object (or a class).
Inheritance is one of the important features of OOP, by which we can define a new class
using pre-existing class, and the new class works like extension of old (i.e. pre-existing)
class.
Thus, it provides re-usability of a code.
The new class has its own features plus the features inherited form the preexisting class. This
process is called inheritance or extending class.

Single inheritance:
When a class is derived from single super class, it is called as single inheritance.
e.g.
class A
{
private in b;
void x() A
{ // some statements
}
public void y() B
{ // some statements
}
}

class B extends A
{
int m;
void pq()
{ // some statements
}
}

Program statement : Define a class Person with following:


Data members: name, age
Methods : input,output
Define a sub-class Employee
data members : salary, dept
methods : getData, outData.
Program:
import [Link].*;
class Person
{
int age;
String name;
void input()
{
Scanner sc = new Scanner([Link]);
[Link]("Enter Name:");
name = [Link]();
[Link]("Enter age:");
age = [Link]();
}
void output()
{
[Link]("Name : " + name);
[Link]("Age : " + age );
}
}

class Employee extends Person


{
double salary;
String dept;
void getData()
{
input();
Scanner sc = new Scanner([Link]);
[Link]("Enter Dept:");
dept = [Link]();
[Link]("Enter salary:");
salary = [Link]();
}
void outData()
{
output();
[Link]("Department: " + dept);
[Link]("Salary : " + salary );
}
}
class Pract05
{
public static void main (String[] args)
{
[Link]("- Single inheritance -");
Employee emp = new Employee();
[Link]("Enter employee data ..");
[Link]();
[Link]("- Employee data -");
[Link]();
}
}

Output:
- Single inheritance -
Enter employee data ..
Enter Name:Ajay
Enter age:34
Enter Dept:Computer
Enter salary:45000
- Employee data -
Name : Ajay
Age : 34
Department: Computer
Salary : 45000.0
Practical :6

Aim: Write a program to input two numbers from user and display the answer of
dividing first number by second number on Exception handling in Java.

Theory:
Exception is a run-time error. Such types of errors occur when some abnormal conditions
arise in some part of a program while it is running.
These errors can occur because of: (Causes of exceptions)
Sudden failures in hardware, used by the program or use of invalid or restricted resources by
the program.
Errors can also occur while program execution because of in-correct (or invalid) data input
done by user. The other reason of run-time error is because of mismatched data types.
Run-time error can occur because some error prone statements e.g. statement accessing array
element outside the array limit.
Java uses Object-oriented approach for Exception handling. Exception in Java is an object of
some class that describes the error-condition that has occurred in some part of a program.
For handling the exceptions occurring in a program, Java provides a special block of
statements, called try-catch-finally block. try, catch and finally are the keywords in Java.
The syntax for exception handling block is as follows.
try
{
// program segment that can generate (i.e. throw) exceptions
}
catch ( exception_type1 obj1 )
{
// Statements to handle (or describe) the exception
}
catch ( exception_type2 obj2 )
{
// Statements to handle (or describe) the exception
}
catch ( exception_type3 obj3 )
{
// Statements to handle (or describe) the exception
}
… some catch blocks
finally
{
// Statements which must work (whatever way try-catch works)
}

Program statement:
Handle different exceptions.

Program :
import [Link].*;
class Pract06
{
public static void main( String[ ] args )
{
Scanner sc = new Scanner([Link]);
int a,b,c;
try
{
[Link]("Enter first integer:");
a = [Link]();
[Link]("Enter second integer:");
b = [Link]();
c = a / b;
[Link]("Ans = " + c );
}
catch( InputMismatchException ex2 )
{
[Link]("Input integer values only");
}
catch( ArithmeticException ex3 )
{
[Link]("Divide by zero Error occured");
}
catch( Exception ex )
{
[Link]("Exception occured : " + ex);
}
finally
{
[Link]("== This is finally block ==");
}
}
}
Outputs:
1)
Enter first integer:20
Enter second integer:4
Ans = 5
== This is finally block ==

2)
Enter first integer:5
Enter second integer:0
Divide by zero Error occurred
== This is finally block ==

3)
Enter first integer:15
Enter second integer:ab
Input integer values only
== This is finally block ==
Practical 7:
Aim: Write a menu driven program to work with list of names, with following options
like 1. Add name, 2. Remove name, 3. Display list Using Vector class.

Program:
import [Link].*;
class namelist
{
public static void main (String [ ] args)
{
Scanner sc = new Scanner([Link]);
Vector v = new Vector( );
String name;
int opt, i;
while( true )
{
[Link](".. Options ..");
[Link]("1.. Add Name");
[Link]("2.. Remove name");
[Link]("3.. Display names");
[Link]("4.. Quit");
[Link]("Enter option :");
opt = [Link]();
switch( opt )
{
case 1 : [Link]("-Enter a Name ");
name = [Link]();
if( [Link]( name ) )
[Link]("Name already exists in the list");
else
[Link]( name );
break;
case 2 : [Link]("-Enter a Name to remove");
name = [Link]();
if( [Link]( name ) )
[Link]( name );
else
[Link]("Name Not found in the list");
break;
case 3 :
int s = [Link]();
[Link]("Names...");
for( i=0; i<s; i++)
{
[Link]( [Link](i) );
}
break;
case 4 : [Link]( “End” );
return;
}
} // ... while ends
}
}
Output:
.. Options ..
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option :1
-Enter a Name Ajay
.. Options ..
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option :1
-Enter a Name Vijay
.. Options ..
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option :1
-Enter a Name Sanjay
.. Options ..
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option :3
Names...
Ajay
Vijay
Sanjay
.. Options ..
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option :2
-Enter a Name to remove
Vijay
.. Options ..
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option :3
Names...
Ajay
Sanjay
.. Options.
1.. Add Name
2.. Remove name
3.. Display names
4.. Quit
Enter option : 4
End
Practical:8
Aim: Demonstration of Multithreading

Theory:
Java provides support for writing Multithreaded programs. A multithreaded program consists
of
multiple parts of the same program running concurrently (i.e. simultaneously). Here each part
of
the program working simultaneously is called a thread, and each thread can work
independently. Also
each thread can be performing different task.
Two ways of achieving multithreading:
[Link] Thread class of Java: The class that has to start a new thread can extend a Thread
class of Java.
The class that extends Thread has to override a run() method. The code written in run() works
as a code for new thread.

2. Implementing Runnable interface :


The class that has to start a new thread can implement the Runnable interface. The class is
now treated as a thread class.
Obviously, the run() method must be implemented in the class. This run method works as a
new thread.
To start the thread the class has to call a start() method of the Thread class.

Program Statement: Define two thread classes. One prints 10 alphabets (A to J), and the other
prints 10 integers (1 to 10). Use these classes in main program to demonstrate Multithreading.

Program:
class Numbers extends Thread
{
public void run()
{
for( int i=1; i<=10; i++ )
{
[Link]( " " + i );
try
{ [Link](50);
}catch(Exception ex)
{ [Link]("Error");
}
}

}
class Chars extends Thread
{
public void run()
{
char ch='A';
for( int i=1; i<=10; i++ )
{
[Link]( " " + ch );
ch++;
try
{ [Link](50);
}catch(Exception ex)
{ [Link]("Error");
}
}

}
}
class Pract07
{
public static void main(String [] args )
{
Numbers nos = new Numbers();

Chars ch = new Chars();

// Start threads
[Link]();
[Link]();
}
}

Output : ( output not fix )


1 A B 2 C 3 4 D 5 E 6 F 7 G 8 H I 9 J 10
Practical: 9
Aim: Using Applet and Graphics class draw a simple face on applet window.

Theory:
Applets are Java programs which run on Web Browser.
Applets run on internet Browsers only with the help of JVM in browser. HTML tag <Applet>
is used to load and run applet on a Web page.
To write applet program we need to use Java’s built-in class Applet.
Java applets entry point is init() method. And the method is called by Brower.
Applets can use limited set of Java API and are particularly used to interact with web page
user.
For running an Applet we need to use some Web Browser or one can use an application
called ‘appletviewer’, which is used for testing and running applet programs only.

Program:

import [Link];
import [Link].*;
public class Pract09 extends Applet
{
public void paint(Graphics g)
{
// Ovals for eyes
[Link]( 50, 50, 60, 30 ); // x, y, w , h
[Link]( 140, 50, 60, 30 );
// Vertical line for nose
[Link](125, 60, 125, 110); // x1, y1, x2, y2
// lips (mouth)
[Link]( 80, 130, 100, 5 ); // x, y, w, h
// full face
[Link](25, 5 , 200, 200 );
}
}
// Following line loads the applet in browser window
/*
<Applet code="[Link]" width=500 height=500>
</applet>
*/
Output:
Practical 10 :
Aim : Write a GUI based application using AWT, which inputs two numbers and
displays the sum. Use Frame, Buttons, Text boxes and Lables. Use event handling to get
the answer.

Theory :
Java provides a package [Link] that has classes and interfaces using which one can develop
GUI based applications.
Some classes are component classes e.g. Button, Label, Textfield. These classes are used to
create visible GUI components.
There are some classes like Window, Frame which are used to create containers to define
main Window for GUI applications.
It also provides some interfaces which are used in Event handling. The methods from these
interfaces must be implemented to perform required action according user’s action and other
events.
In this program we are using Button, TextField, Frame and Label classes for GUI design.
Also, ActionListener interface is used for Event handling.
The code for event handling is written in method actionPerfomed().
The classes/interfaces For event handling are imported from [Link] package.

Program :
import [Link].*;
import [Link].*;
class AddNos extends Frame
{
// Defining objects of the required AWT components
Label lbl1 = new Label("Number 1");
TextField txtno1 = new TextField();
Label lbl2 = new Label("Number 2");
TextField txtno2 = new TextField();
Button btnadd = new Button("Add");
Label lbl3 = new Label("Sum");
Label lblsum = new Label("-");
Button btnclose = new Button("Close");
// Putting components on Window
AddNos()
{
super("Add Numbers");
// Remove default layout
setLayout(null);
// set position and size of components
[Link]( 50, 50, 80, 30 );
[Link](200, 50, 80, 30 );
[Link]( 50, 100, 80, 30 );
[Link](200, 100, 80, 30 );
[Link]( 50, 150, 80, 30 );
[Link](200, 150, 80, 30 );
[Link]( 100, 200, 70, 30 );
[Link]( 200, 200, 70, 30 );
// add the components on window
add(txtno1); add(txtno2); add(lbl1);
add(lbl2); add(lbl3); add(lblsum);
add(btnadd); add(btnclose);

// Register event listener class to the button


[Link]( new BtnListener());
[Link]( new BtnListener());

// Making current window visible


setSize( 350, 350 );
setVisible( true );
}
// Listener class to respond to button event
class BtnListener implements ActionListener
{
public void actionPerformed( ActionEvent ae )
{
String btn = [Link]();
if( [Link]("Add"))
{
int a = [Link]( [Link]());
int b = [Link]( [Link]());
int c = a+b;
[Link]( c + "" );
}
else
[Link](0);
}
}
// Load/Run above class
public static void main(String[ ] args )
{
AddNos f = new AddNos();
}
}
Output :
Practical: 11

Aim : Design GUI with Radio Button to Select engineering branch.

Theory :

Java Swing :

• Swing is a Set of API (API- Set of Classes and Interfaces)

• Swing is Provided to Design Graphical User Interfaces

• Swing is an Extension library to the AWT (Abstract Window Toolkit)

• Includes New and improved Components that have been enhancing the looks and
Functionality of GUIs’

• Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets and
Applets

• It Employs model/view design architecture.

• Swing is more portable and more flexible than AWT, the Swing is built on top of the AWT.

• Swing is Entirely written in Java.

• Java Swing Components are Platform-independent, and The Swing Components are
lightweight.

• Swing Supports a Pluggable look and feel and Swing provides more powerful components.

• such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.

Working with RadioButton:

RadioButton is defined using CheckBox class and added to aCheckBoxGroup.

Method getState() is used to get the status of Radio button i.e. checked or unchechked. The method
returns true if checked else false.

An interface ItemListener is used to listen to the click and change events of Radio buttons. The
method itemStateChanged() is used to handle and write code for the events.
Program:

import [Link].*;
import [Link].*;
import [Link].*;

// Current class displays window and handles events


class RadioButtonDemo extends Frame implements ItemListener
{
// Defining objects of the required AWT components
Label lbl1 = new Label("Select Your branch..");
CheckboxGroup grp = new CheckboxGroup();
Checkbox chkcomp = new Checkbox("Computer Sc",false, grp);
Checkbox chkit = new Checkbox("Info. Tech." ,false, grp);
Checkbox chkmech = new Checkbox("Mechanical",false, grp);
Checkbox chkextc = new Checkbox("Elect. & TC",false, grp);
Label lblmsg = new Label("-");
Button btnok = new Button("OK");
Button btnclose = new Button("Close");

// Putting components on Window


RadioButtonDemo()
{
super("Radio button Demo");
// Remove default layout
setLayout(null);
// set position and size of components
[Link]( 50, 50, 150, 30 );
[Link](50, 100, 100, 30 );
[Link](50, 150, 100, 30 );
[Link](50, 200, 100, 30 );
[Link](50, 250, 100, 30 );

[Link](50, 300, 250, 30 );


[Link]([Link]);
[Link]([Link]);
Font f = new Font("Arial", [Link], 14);
[Link]( f );

[Link]( 200, 200, 70, 30 );


[Link]( 200, 250, 70, 30 );
// add the components on window
add(lbl1);
add(chkcomp);
add(chkit);
add(chkmech);
add(chkextc);
add(lblmsg);
add(btnok);
add(btnclose);

// Rgister event listener class to the button


[Link]( new BtnListener());
[Link]( new BtnListener());

// Rgister event listener class to the Check Boxes


[Link](this);
[Link](this);
[Link](this);
[Link](this);

// Making current window visible


setSize( 350, 350 );
setVisible( true );
}

// Listener method to respond to Checkbox event


public void itemStateChanged( ItemEvent ie)
{
Checkbox cb = (Checkbox) [Link]();
String branch = [Link]();
if( [Link]() == true )
[Link]( branch + " .. Checked");
}

// Listener class to respond to button event


class BtnListener implements ActionListener
{
public void actionPerformed( ActionEvent ae )
{
String btn = [Link]();
String opt = "";
if( [Link]("OK"))
{
if( [Link]())
opt = [Link]() + " ";
if( [Link]())
opt = [Link]() + " ";
if( [Link]())
opt = [Link]() + " ";
if( [Link]())
opt = [Link]() + " ";

[Link]( opt + " .. Selected" );


}
else
[Link](0);
}
}

// Load above class


public static void main(String[ ] args )
{
RadioButtonDemo f = new RadioButtonDemo();
}
}

Output :
Practical: 12

Aim : Drawing different geometric Shapes using JavaFX

Theory :
• JavaFX is a media/graphics framework for creating GUI in Java Applications.
• It is more powerful than Java Swing.
• It is used to create both Windows as well a Web Applications.
• It draws its own components ( so less communication with OS). Hence, they are
lightweight components.

Installing JavaFX and Running JavaFx program :

Download Prper JavaFx SDK that matches your Java version ( and JavaFX Scene if required
)
Extract the file into some folder e.g. c:\javafx17
Go to Settings -> Env Varibales
Add following name :
Name : PATH_TO_FX
Value : c:\javafx17\lib (in out example)

From command prompt compile program as follows :


> javac --module-path C:\JavaFX17\lib --add-modules [Link] [Link]

Run :
java --module-path C:\JavaFX17\lib --add-modules [Link] JavaFx1

For drawing graphics shapes we use the methods in JavaFx classes.


Then we can apply them colour, fill colour, graphics type etc.
We use classes like Line, Text, Circle etc.

Program :
JavaFx_Shapes.java

// 1. Import required JavaFX packages


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*; // for Color
import [Link].*; // for Line
import [Link].*; // for Text
import [Link].*;
//2. define a public class that extends FX class 'Application'
public class JavaFx_Shapes extends Application
{
// user defined mthod to create Line object for given co-ordinates
Line createLine(double x1, double y1, double x2, double y2 )
{
Line line = new Line();
[Link](x1);
[Link](y1);
[Link](x2);
[Link](y2);
return line;
}

// user defined mthod to create Text object for given co-ordinates and
String data
Text createText(String data, double x, double y )
{
Text text = new Text(data);
[Link](x);
[Link](y);
return text;
}

// 3. Define a 'start' method


public void start(Stage stage ) throws Exception
{
Line line1 = createLine(100, 100 , 250 , 250);
[Link]([Link]);

Line line2 = createLine(50, 100, 50, 200);


[Link]([Link]);
[Link](10);
[Link]([Link]);

Text text = createText("Java Fx Shapes", 70, 70 );


[Link]( new Font(20));

Circle circle = new Circle(200, 200, 70);


[Link]([Link]);
[Link]([Link]);

// 4. create Group object


Group group = new Group();
// List of object to display on scene
ObservableList list = [Link]();
[Link](circle);
[Link](line1);
[Link](text);
[Link](line2);

// 5. create Scene object


Scene scene = new Scene( group,400, 300 );
[Link]([Link]);
// 6. Add the scene to stage
[Link]( scene);
[Link]("First FX window");
// 7. Display the stage
[Link]();

}
public static void main(String []args)
{
// Load the application by calling 'launch' method
launch(args);
}
}

Output :
Practical: 13

Aim : Creating Login windo using JavaFX

Theory :
• JavaFX is a media/graphics framework for creating GUI in Java Applications.
• It is more powerful than Java Swing.
• It is used to create both Windows as well a Web Applications.
• It draws its own components ( so less communication with OS). Hence, they are
lightweight components.

Steps for designing GUI using JavaFX :


1. Import required JavaFX packages
2. Define a public class that extends FX class (Application)
3. Define a 'start' method in the class
4. create Group object
5. create Scene object
6. Add the scene to stage
7. Display the stage
8. Define main() method and load the class using launch() method.

Program :

//import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JavaFX_LoginDemo extends Application implements
EventHandler<ActionEvent>
{
TextField txtuser = new TextField();
PasswordField txtpsw = new PasswordField();
Button btnLogin = new Button("Login");
Label lblmsg = new Label("...");

Stage window;
@Override
public void start(Stage primaryStage)
{
window = primaryStage;
GridPane grid = new GridPane();
[Link]([Link]);
[Link](10);
[Link](10);
[Link](new Insets(10));

/* Define column widths


ColumnConstraints col1 = new
ColumnConstraints(100);
ColumnConstraints col2 = new
ColumnConstraints(100, 150, 250);
[Link]().addAll(col1,col2);
*/

Label lblTop = new Label("login !");


[Link]([Link]("Aial",
[Link], 20));
[Link](lblTop, 0, 0);

Label lbluser = new Label("User name");


[Link](lbluser, 0, 1);

[Link]("user name...");
[Link](txtuser, 1, 1);

Label lblpsw = new Label("Password");


[Link](lblpsw, 0,2);
[Link]("password...");
[Link](txtpsw, 1, 2);

[Link](btnLogin, 1, 3 );

[Link](lblmsg, 1,4);

[Link](this);

Scene scene = new Scene(grid, 400, 250);


[Link](scene);
[Link]();

public void handle(ActionEvent event)


{
String name = [Link]();
String psw = [Link]();
if( [Link]("java") && [Link]("abcd"))
[Link]("Login successful !");
else
[Link]("Login failed...");
}

public static void main(String[] args)


{
launch(args);
}
}
Output :

-------------
Mini Project: Bank Account based on OOPM
Develop a small Java Application using Java, JDBC and Database.

Program:
Program for Bank account operations.
Form to create new Bank account. Other form for Transactions like Depositing money and
Withdrawal of amount from an account.
Create multiple bank account using database and demonstrate above operations.

Creating Database structure:


1. Creating a database for Bank program:
create database bankdemo;

2. Opening the database:


use bankdemo;

3. Creating customer table:


create table customer
(custid int primary key, custname varchar(40), amount float );

4. Creating Transaction table :


create table transaction
(tid int primary key, custid int , amount float, trdate date, trtype varchar(10));

Java Program :
1. Main form with menu.
import [Link].*;
import [Link].*;

class mainform extends Frame


{
MenuBar mb=new MenuBar();
Menu mnfile=new Menu("Bank Data");
MenuItem micust=new MenuItem("Customer");
MenuItem mitr=new MenuItem("Transaction");
MenuItem miex=new MenuItem("Exit");
mainform()
{
[Link](micust);
[Link](mitr);
[Link](miex);
[Link](mnfile);
setMenuBar(mb);
[Link](new menulistener());
[Link](new menulistener());
[Link](new menulistener());
setSize( 500, 500 );
setVisible(true);
}
class menulistener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String s=[Link]();// tells which button was selected
if([Link]("Customer"))
new Customer();
else if([Link]("Transaction"))
new Transaction();
else
[Link](0);
}
}
public static void main(String[] args)
{
mainform m=new mainform();
}
}

-------------------------------------------------

2. Customer Form:

import [Link].*;
import [Link].*;

import [Link].*;

class Customer extends Frame


{
Label l1 = new Label("ID");
TextField txtid = new TextField();
Label l2 = new Label("Name");
TextField txtname = new TextField();
Label l3 = new Label("Amount");
TextField txtamt = new TextField();
Button btnadd = new Button("ADD");
Button btnopn = new Button("OPEN");
Button btncls = new Button("CLOSE");
Button btndel=new Button("DELETE");
Label lblmsg = new Label("=");
Label lbltop = new Label("Customer Info..");
Customer()
{
setLayout( null );

[Link]( 50, 100, 80 , 30 );


[Link]( 150 , 100, 80, 30 );
[Link]( 50, 150, 80 , 30 );
[Link]( 150 , 150, 150, 30 );
[Link]( 50, 200, 80 , 30 );
[Link]( 150 , 200, 80, 30 );
[Link](50, 250, 350, 30);
[Link]([Link]);

[Link](50, 40, 110, 25 );


[Link]([Link]);
[Link]([Link]);

add(l1); add(l2); add( l3 );


add(txtid); add(txtname); add(txtamt);
add(lblmsg);
add(lbltop);
[Link](50,300, 70, 30 );
[Link](130, 300, 70, 30 );

[Link](210,300,70,30);
[Link](320,300, 70, 30 );

add(btnadd); add(btnopn); add(btncls); add(btndel);


[Link](new demo());
[Link](new demo());
[Link](new demo());
[Link](new demo());
setSize( 500, 500 );
setVisible(true);
}

void clearFields()
{
[Link]();
[Link]("");
[Link]("");
[Link]("- -");
}
class demo implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String s=[Link]();
if([Link]("ADD"))
{
Connection con=null;
Statement st=null;

try
{
// string mentions which jdbc driver to load
[Link]("[Link]");
//string to mention which db to connect
con=[Link]
("jdbc:mysql://localhost:3306/bankdemo","root","");
st=[Link]();

String str="insert into customer values(";


str=str + [Link]();
str=str+ ",'"+[Link]()+ "'";
str=str+ ","+[Link]()+ ")";

[Link](str); // for inserting,delete,update


[Link]("Customer record added.. !");
}
catch(Exception ea)
{
[Link]("Error .." +[Link]());
}
finally
{
try
{
[Link]();
}
catch(Exception ex)
{ }
}
}/* End of Add button code */

else if([Link]("DELETE"))
{
clearFields();
int b;
Connection con=null;
Statement st=null;
b=[Link]([Link]());
try
{
[Link]("[Link]");
con=[Link]
("jdbc:mysql://localhost:3306/bankdemo","root","");
st=[Link]();
String str="delete from customer where custid=" + b;
[Link](str);
lblmsg .setText("Customer record deleted");
}
catch(Exception ec)
{
[Link]("Error ..");
}
finally
{
try
{
[Link]();
}
catch(Exception ex) { }
}
}/* End of Delete button code */

else if([Link]("OPEN"))
{
clearFields();
int a;
Connection con=null;
Statement st=null;
a=[Link]([Link]());
try
{
[Link]("[Link]");
con=[Link]
("jdbc:mysql://localhost:3306/bankdemo","root","");
st=[Link]();
ResultSet rs=[Link](
"select * from customer where custid="+a);
if([Link]()==true)
{
[Link]([Link]("custname"));
[Link]([Link]("amount")+"");
}
else
[Link]("No such customer");
}
catch(Exception ez)
{
[Link]("Error : " + [Link]());
}
finally
{
try
{ [Link](); }
catch(Exception ex) { }
}
}/* End of Open button code */
else
dispose();
}
} /* End of Listener class */

public static void main(String[ ] args )


{
Customer c = new Customer();
}
}

-----------------------------------------------
3. Account Transactions form :

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
class Transaction extends Frame
{
Label lbldate = new Label();
Label l1 = new Label("CUST_ID");
TextField txtid = new TextField();
Label l3 = new Label("Amount");
TextField txtamt = new TextField();
CheckboxGroup cg=new CheckboxGroup();
Checkbox chk1=new Checkbox("WITHDRAW", cg, false);
Checkbox chk2=new Checkbox("DEPOSIT",cg, false);
Button btnnew = new Button("NEW");
Button btnadd = new Button("SUBMIT");
Button btncls = new Button("CLOSE");
Label lblmsg = new Label("TRANSACTION ID=");
Label lbltop = new Label("TRANSACTION Info..");

Transaction()
{
setLayout( null );
Calendar cal = [Link]();
String dt = [Link]([Link]) +
"/" + ([Link]([Link]) +1) + "/" +[Link]([Link]) ;
[Link]( 300, 50, 90, 30);
[Link]( 50, 50, 80 , 30 );
[Link]( 150 , 50, 80, 30 );
[Link]( 50, 150, 80 , 30 );
[Link]( 150 , 150, 80, 30 );
[Link](50, 200, 150, 30);
[Link]([Link]);
[Link](20, 30, 150, 30);

[Link]( dt );
add(lbldate);
add(l1);
add( l3 );
add(txtid);
add(txtamt);
add(lblmsg);
add(lbltop);
[Link](50,300, 70, 30 );
[Link](150, 300, 70, 30 );
[Link](250,300, 70, 30 );
add(btnnew); add(btnadd); add(btncls);
[Link](new demo());
[Link](new demo());
[Link](new demo());
add(chk1); add(chk2);
[Link](200,200,100,30);
[Link](200,250,100,30);
setSize( 500, 500 );
setVisible(true);
}
class demo implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String s=[Link]();
if([Link]("CLSOE"))
{
dispose() ;
}
if([Link]("NEW"))
{
Connection con=null;
Statement st=null;
try
{
[Link]("[Link]");
con=[Link](
"jdbc:mysql://localhost:3306/bankdemo","root","");
st=[Link]();
String str="select count(tid)+1 as a from transaction";
ResultSet rs= [Link](str);
[Link]();
lblmsg .setText([Link]("a")+"");
}
catch(Exception ea)
{
[Link]("Error.." + ea);
[Link]("Error ");
}
finally
{
try
{ [Link](); }
catch(Exception ex) { }
}
}
if([Link]("SUBMIT"))
{
int b;
String cid=[Link]();
String tid= lblmsg .getText();
String amt=[Link]();
String type=null;
String str="";
if([Link]()==true)
type=[Link]();
if([Link]()==true)
type=[Link]();

Connection con=null;
Statement st=null;
try
{
[Link]("[Link]");
con=[Link](
"jdbc:mysql://localhost:3306/bankdemo","root","");
[Link](false);
st=[Link]();
str="insert into transaction values(" + tid;
str=str + ","+ cid ;
str=str + ","+ amt ;
str=str + ",'" + [Link]() + "'"; // yyyy-m-d
str=str + ",'" + type + "')";
[Link](str);

if([Link]("WITHDRAW"))
{
str="update customer set amount =
amount - "+ amt+" where custid="+ cid;
}
else
{
str="update customer set amount=
amount + " + amt +" where custid="+cid;
}
[Link](str);
lblmsg .setText("Transaction done!!");
[Link]();
}
catch(Exception ec)
{
[Link]("Error : "+ec);
[Link]("Error : Transation failed");
try{
[Link]();
}catch( Exception ex){ }
}
finally
{
try
{ [Link](); }
catch(Exception ex)
{
}
}
}
}
}

public static void main(String[ ] args )


{
Transaction c = new Transaction();
}
}

======0000======

You might also like