0% found this document useful (0 votes)
9 views

Java Experiments

Uploaded by

ak47.shadow.2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java Experiments

Uploaded by

ak47.shadow.2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

lOMoAR cPSD| 29418202

JAVA Experiments

Bachelor of Engineering in Information Technology (University of


Mumbai)

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Studocu is not sponsored or endorsed by any college or university

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Experiment no :- 01

Title: To study Inheritance,Interfaces and implement the program.

Problem Statement: Create a class Book and define a display method to display book
information. Inherit Reference_Book and Magazine classes from Book class and override display
method of Book class in Reference_Book and Magazine classes. Make necessary assumptions
required.

Theory:
Inheritance : The process by which one class acquires the properties(data members) and
functionalities(methods) of another class is called inheritance.

Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the


mechanism in java by which one class is allowed to inherit the features(fields and
methods) of another class.

Super Class: The class whose features are inherited is known as superclass(or a base class or a
parent class).
Sub Class: The class that inherits the other class is known as subclass(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition to
the superclass fields and methods.

Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can derive
our new class from the existing class. By doing this, we are reusing the fields and methods of
the existing class.

Syntax:
class derived-class extends base-class
{
//methods and fields
}
Types Of Inheritance :
1 .Single Inheritance

2. Multilevel inheritance

3. Hierarchical inheritance

4. Multiple Inheritance

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

5. Hybrid inheritance

Algorithm:
1. Start the Program
2. Create a Class
3. Declare the Display Method in different names of Books
4. Create another class and Extend the Parent class with declare display method
5. Call the main method and create object
6. Display the object
7. Stop the Program

Program:
class Book
{
void display()
{
System.out.println("Name - The Complete Reference Java 2");
System.out.println("Author - Herbert Schildt");
}
}
class Reference_Book extends Book
{
void display()
{
System.out.println("Name - Pure Java 2");
System.out.println("Author - Kenneth Litwak");
}
}
class Magazine extends Book
{
void display()
{
System.out.println("Name - Core Java");
System.out.println("Author - Cay S. Horstmann");
}
}
class TestInheritance
{
public static void main(String args[])
{ Book b; b=new Book();
b.display(); b=new
Reference_Book();
b.display(); b=new
Magazine(); b.display();

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

}
}

Actual Input/ Output:

Conclusion:
Inheritance is a strong weapon of Java that helps to make it a widely acceptable language. It
helps to reduce code duplication and also cuts down on the bugs. With the code written in the
parent class, you no longer need to write the same code for multiple child classes that has the
same properties.

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Experiment no :- 02

Title : To create classes for students and adding constructor and method in each
class using inheritance.

Theory:
Prior concept:
1) Classes, Objects and Variables

2) Constructor

3) Method

Creating objects in java-


Creating an object is referred to as instantiaing an object. Objects of specific class
are created using new operator which returns reference to that object. An objects in
java is a variable which is assigned a object reference. Classes create objects and
objects use method to communicate between them.

Syntax: class_name
object_name;

object_name=new class_name(); //instantiaing object of class


Syntax: class_name object_name=new class_name();
//creating object

Array-

An array is a homogeneous college of series of data element (either


primitive data type or reference) in which all elements are of same type and are
stored consecutively in the memory.
Creating an arraySyntax:

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

datatype array_name[ ]= new datatype[size];


Example:

int a[ ]= new int[5];

Array of Objects-

Array of objects is the collection of objects of the same class.

Syntax:

class_name array_name [ ]= new class_name[size];


Example:

Student s=new Student[5];

//Define an array of 5 objects of class student for (int i=0; i<5; i++)

s[i]=new Student ();

//to assign memory to individual object in array

Constructor-
Constructor is a special type of method which enables to initialize an object
when it is first created. It has the same name as the class in which it is declared.
It does not specify a return type not even void.

Syntax:
ConstructorName()

// initialization statements

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

A constructor may be parameterized.

Syntax:

// initialization statements

Types of Constructors:

● Default Constructor
● Parameterized Constructor
● Copy Constructor
● Default argument Constructor ● Multiple Constructor

Methods-

Java methods are where you put the operations on data (variables) in your Java
code. In other words, you group Java operations (code) inside Java methods. Java
methods must be located inside a Java class.

Java methods are similar to what is called functions or procedures in other


programming languages (e.g. Pascal or JavaScript). A method is a group of Java
statements that perform some operation on some data, and may or may not return
a result
Example:

public MyClass{

public void writeText(String text)

{ System.out.print(text); //prints the text parameter

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

}
}

Types of methods:

● Static methods: A static method is a method that can be called and


executed without creating an object. ...
● Instance methods: These methods act upon the instance variables of a class.
...
● Factory methods: A factory method is a method that returns an object to
the class to which it belongs.

Program:
import java.io.*;

class graduate_student{
int Roll no,Marks;
string Name,subject;

InputStreamReader i = new InputStreamReader(System.io)

BufferedReader br = new BufferedReader(i);


void accept()

try {

System.out.print("Enter Roll no");

System.out.print("Enter Marks");

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Roll no=Integer.parseInt(br.readline())

Marks=Integer.parseInt(br.readline())

System.out.print("Enter Name");

System.out.print("Enter Subject")

Name=Integer.parseInt(br.readline())

Subject=Integer.parseInt(br.readline())

} catch(Exception
e){

void display() {

System.out.print(" Roll no is"roll no);

System.out.print(" Marks is"+marks);

System.out.print(" Name is"+,name);

System.out.print(" Subject is"+subject);

} class student_info{ public static


void main(String args[]){

int i;
graduate_student g[]= new graduate_student[5]
for(i=0; i<5; i++)

{ g[i]=new graduate_student();
} for(i=0; i<5; i++) {
g[i].accept(); } for(i=0; i<5;
i++)

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

{ g[i].display(); }

class research_student{
int Roll no,Marks;
string Name,subject;

InputStreamReader i = new InputStreamReader(System.io)


BufferedReader br = new BufferedReader(i);

void accept()

try {

System.out.print("Enter Roll no");

System.out.print("Enter Marks");

Roll no=Integer.parseInt(br.readline())

Marks=Integer.parseInt(br.readline()) System.out.print("Enter Name");

System.out.print("Enter Subject")

Name=Integer.parseInt(br.readline())

Subject=Integer.parseInt(br.readline())

} catch(Exception
e){

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

void display() {

System.out.print(" Roll no is"roll no);

System.out.print(" Marks is"+marks);

System.out.print(" Name is"+,name);

System.out.print(" Subject is"+subject);

} class student_info{ public static


void main(String args[]){

int i;

research_student r[]= new research_student[5]


for(i=0; i<5; i++) { r[i]=new
research_student(); } for(i=0; i<5; i++) {
r[i].accept(); } for(i=0; i<5; i++)
{ r[i].display(); }

}
}

Output:
For Research Students;

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

For Graduate Students;

Conclusion: So, Here we have displayed students records with their following attributes using
inheritance of interface in java.

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Experiment no :- 03

Title: To study Inheritance, Interfaces


Problem Statement: Consider a hierarchy, where a sportsperson can either
be an athlete

or a hockey player. Every sportsperson has a unique name. An athlete


is characterized by the event in which he/she participates; whereas a
hockey player is characterised by the number of goals scored by
him/her.

Perform the following tasks using Java :

( i)Create the class hierarchy with suitable instance variables and


methods.

(ii) Create a suitable constructor for each class.

(iii) Create a method named display_all_info with suitable parameters. This method should
display all the information about the object of a class.

(iv) Write the main method that demonstrates polymorphism.

Theory: Interfaces in Java


Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no body).
● Interfaces specify what a class must do and not how. It is the blueprint
of the class.
● An Interface is about capabilities like a Player may be an interface and
any class implementing Player must be able to (or must implement)
move(). So it specifies a set of methods that the class has to implement.
● If a class implements an interface and does not provide method bodies
for all functions specified in the interface, then the class must be
declared abstract.

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

To declare an interface, use interface keyword. It is used to provide total


abstraction. That means all the methods in an interface are declared with an
empty body and are public and all fields are public, static and final by default. A
class that implements an interface must implement all the methods declared in
the interface. To implement interface use implements keyword.

Why do we use interface ?

● It is used to achieve total abstraction.


● Since java does not support multiple inheritance in case of class, but by
using interface it can achieve multiple inheritance .

Algorithm:
Step 1: Start the program.

Step 2: Declare the Interface Sportperson.

Step 3: Declare the display_all_info member function.

Step 4: Declare te class Hockey and implements thw Interface Sportperson.

Step 5: Declare and define constructor Hockey and derive the fuction and from the
Interface and define it.

Step 6: Declsre the class Athletc and implements the interface Sportperson.

Step 7: Declare and define constructor Athletc and derive the fuction and from
the Interface and define it.

Step 8: Declare the main class.

Step 9: Declare the derived class object and call the function using object and also
invoke the constructor.

Step 10: Stop the Program.

Program: interface Sportsperson


{

void display_all_info();

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

class Hockey implements Sportsperson

String name;
int age; int
goals;

public Hockey(String n, int a, int g)

{ name =
n; age =
a; goals =
g; }

public void display_all_info()

System.out.println("Hockey Player:" + " Name: "+ name + " Age: "+ age +"
Number of goals:" + goals);

class Athlete implements Sportsperson


{

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

String type;
String name;
int age;

public Athlete(String n, int a, String t)

{ name =
n; age =
a; type =
t;

public void display_all_info()

System.out.println("Athlete:" + " Name: "+ name + " Age: "+ age +" Type of
athlete:" + type);

}
}

public class Exp3

public static void main(String args[])

Hockey h1 = new Hockey("Dhyan Chand",60,100);

Hockey h2 = new Hockey("Manpreet Singh",30,50);

Athlete a1 = new Athlete("P.T.Usha",50,"Running");

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Athlete a2 = new Athlete("Michael


Phelps",35,"Swimming"); h1.display_all_info();
h2.display_all_info(); a1.display_all_info();
a2.display_all_info();

}}

Atual Input/Output:

Conclusion: We have successfully implemented multiple Inheritance using


interface.

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Experiment no :- 04

Title:-
Inheritance And Exceptional Handling

Problem statement:-
Java program to create:-
i. A Class called Account that creates account with 1000Rs minimum
balance, a deposit() method to deposit amount, a withdraw() method to
withdraw amount and also throws LessBalanceException if an account holder
tries to withdraw money which makes the balance become less than 1000Rs.
ii. A Class called LessBalanceException which returns the statement that
says withdraw amount ( Rs) is not valid. iii. A Class which creates 2 accounts,
both account deposit money and one account tries to withdraw more money
which generates a LessBalanceException take appropriate action for the same.

Theory:-.
Exception handling is one of the most important feature of java programming that
allows us to handle the runtime errors caused by exceptions. In this guide, we
will learn what is an exception, types of it, exception classes and how to handle
exceptions in java with examples.

An Exception is an unwanted event that interrupts the normal flow of the


program. When an exception occurs program execution gets terminated. In such
cases we get a system generated error message. The good thing about exceptions
is that they can be handled in Java. By handling the exceptions we can provide a
meaningful message to the user about the issue rather than a system generated
message, which may not be understandable to a user.

Algorithm :-
1.The try-catch block is used to handle exceptions in Java. Here's the syntax of
try...catch block:
try {

// code

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

} catch(Exception e)
{ // code

2.Here, we have placed the code that might generate an exception inside the try block.
Every try block is followed by a catch block.

3.When an exception occurs, it is caught by the catch block. The catch block cannot
be used without the try block.

Program:-
import java.io.*; class LessBalanceException
extends Exception

double amt;

LessBalanceException(double wamt)

amt=wamt;

System.out.println("withdraw not possible"+amt);

} class
Account

public double bal;

Account(){bal=500.0;

}
public void deposit(double damt)

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

bal=bal+damt;

} public void withdraw(double wamt) throws


LessBalanceException

{ if((bal-wamt)<=1000)throw(new
LessBalanceException(wamt)); else{bal=bal-wamt;

System.out.println("Amount withdrawn:"+wamt);

System.out.println("balance:"+bal);

} } public class OwnExceptionDemo{public static void main(String


args[])

Account a1=new Account();


Account a2=new Account();
a1.deposit(5000);
a2.deposit(5000);

System.out.println("balance of a1:"+a1.bal);

System.out.println("balance of a2:"+a2.bal);
try

a1.withdraw(4000);
a2.withdraw(5000);

catch(LessBalanceException e)
{

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

System.out.println("cant withdraw"+e);

Input and output :

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Conclusion:-
Thus we have created account using java program

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Experiment no :- 05

Title : Create two threads such that one thread will print even number and another
will print odd number in an ordered fashion.

Theory :
Multithreading in Java :

Multithreading in Java is a process of executing multiple threads


simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing.


Multiprocessing and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a


shared memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than
process.

Advantages of Java Multithreading :


1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs


in a single thread.

How to create thread :

There are two ways to create a thread:

1. By extending Thread class : We create a class that extends the


java.lang.Thread class. This class overrides the run() method available
in the Thread class. A thread begins its life inside run() method. We
create an object of our new class and call start() method to start the
execution of a thread. Start() invokes the run() method on the Thread
object.

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

2. By implementing Runnable interface : We create a new class which


implements java.lang.Runnable interface and override run() method.
Then we instantiate a Thread object and call start() method on this object.

Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread Object class and implements Runnable interface.

Commonly used Constructors of Thread class:


o Thread() o Thread(String name)
o Thread(Runnable r) o
Thread(Runnable r,String name)

Prog
ram :
public class PrintEvenOddTester {
public static void main(String... args) {
Printer print = new Printer();

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Thread t1 = new Thread(new TaskEvenOdd(print, 30,


false)); Thread t2 = new Thread(new TaskEvenOdd(print,
30, true)); t1.start(); t2.start(); }

class TaskEvenOdd implements Runnable


{ private int max; private Printer print;
private boolean isEvenNumber;

TaskEvenOdd(Printer print, int max, boolean isEvenNumber)


{ this.print = print; this.max = max;

this.isEvenNumber = isEvenNumber;

@Override
public void run() {

int number = isEvenNumber == true ? 2 : 1;


while (number <= max) { if
(isEvenNumber) {
print.printEven(number);

} else {

print.printOdd(number);

}
number += 2;

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

class Printer { boolean isOdd = false;


synchronized void printEven(int number) {
while (isOdd == false) { try {
wait();

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println("Even:" + number);
isOdd = false; notifyAll();

synchronized void printOdd(int number) {


while (isOdd == true) {

try {
wait();

} catch (InterruptedException e) {

e.printStackTrace();
}

System.out.println("Odd:" + number);
isOdd = true; notifyAll();

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Input/output :

Conclusion : we had a look at how we can print odd and even numbers
alternatively using two threads in Java.

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Experiment no :- 06
Aim : Assume that two brothers, Joe and John, share a common bank account.
They both can, independently, read the balance, make a deposit, and withdraw
some money. Implement java application demonstrate how the transaction in a
bank can be carried out concurrently.

Theory :

Exception Handling :

The Exception Handling in Java is one of the powerful mechanism to


handle the runtime errors so that normal flow of the application can be maintained.

Dictionary Meaning:

Exception is an abnormal condition.In Java, an exception is an event that disrupts


the normal flow of the program. It is an object which is thrown at runtime.Exception
Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling –

The core advantage of exception handling is to maintain the normal flow


of the application. An exception normally disrupts the normal flow of the
application that is why we use exception handling.

Types of Java Exceptions -

There are mainly two types of exceptions: checked and unchecked. Here, an error
is considered as the unchecked exception. According to Oracle, there are three
types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
Checked Exception –
The classes which directly inherit Throwable class except RuntimeException and
Error are known as checked exceptions e.g. IOException, SQLException etc.
Checked exceptions are checked at compile-time.

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Unchecked Exception –
The classes which inherit RuntimeException are known as unchecked exceptions
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
Error - Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.

Synchronization :

Synchronization is the solution for this problem. A special keyword,


synchronized, prevents race conditions from happening. This keyword places a
lock (a monitor) on an important object or piece of code to make sure that only one
thread at a time will have access.

How do you protect the data? You must do two things:

● Mark the variables private.


● Synchronize the code that modifies the variables.

Program:
public class AccountTesting implements Runnable
{ private Account acct = new Account(); public
static void main(String[] args) {

AccountTesting r = new AccountTesting();

Thread one = new Thread(r);


Thread two = new Thread(r);
one.setName("Joe");
two.setName("John");
one.start();
two.start();

@Override

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

public void run() { for (int x = 0; x < 5;


x++) { makeWithdrawal(10); if
(acct.getBalance() < 0) {

System.out.println("account is overdrawn!");
}

}
}

private void makeWithdrawal(int amt) {


if (acct.getBalance() >= amt) {

System.out.println(Thread.currentThread().getName() + " is
going to withdraw");

try {

Thread.sleep(100);

} catch (InterruptedException ex) {

acct.withdraw(amt);

System.out.println(Thread.currentThread().getName() + "
completes the withdrawal");

} else {

System.out.println("Not enough in account for " +


Thread.currentThread().getName() + " to withdraw " + acct.getBalance());
}

} } class Account {
private int balance = 50; public

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

int getBalance() { return


balance; }

public void withdraw(int amount) {


balance = balance - amount;

Output :

Experiment no :- 07
Aim: Study of Swing
LO Number: 2-Design and develop Graphical User Interface using Abstract Window
Toolkit and Swings along with response to the events.

Problem statement: Write a Java program to implement Swing components namely


Buttons, , JLabels, Checkboxes, Radio Buttons, JScrollPane, JList,
JComboBox, Trees, Tables Scroll pan Menus and Toolbars to design interactive
GUI.

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Theory:
Java Swing is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java
1) JButton: JButton class is used to create a push-button on the UI. The
button can contain some display text or image. It generates an event when clicked
and double-clicked. A JButton can be implemented in the application by calling
one of its constructors.

2) JLabel: JLabel class is used to render a read-only text label or images on


the UI. It does not generate any event.

3) JTextField:JTextField renders an editable single-line text box. A user can


input non-formatted text in the box. To initialize the text field, call its constructor
and pass an optional integer parameter to it. This parameter sets the width of the
box measured by the number of columns. It does not limit the number of
characters that can be input in the box.

4) JCheckBox: JCheckBox renders a check-box with a label. The check-box


has two states – on/off. When selected, the state is on and a small tick is displayed
in the box.

5) JRadioButton: JRadioButton is used to render a group of radio buttons in


the UI. A user can select one choice from the group.

6) JList: JList component renders a scrollable list of elements. A user can


select a value or multiple values from the list. This select behavior is defined in
the code by the developer.
7) JComboBox: JComboBox class is used to render a dropdown of the list of
options.

8) JMenuBar, JMenu and JMenuItem: The JMenuBar class is used to


display menubar on the window or frame. It may have several menus.The object
of JMenu class is a pull down menu component which is displayed from the menu
bar. It inherits the JMenuItem class.The object of JMenuItem class adds a simple
labeled menu item. The items used in a menu must belong to the JMenuItem or
any of its subclass.

9) Java JFrame: The javax.swing.JFrame class is a type of container which


inherits the java.awt.Frame class. JFrame works like the main window where
components like labels, buttons, textfields are added to create a GUI. Unlike

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.

10) JPopupMenu: PopupMenu can be dynamically popped up at specific


position within a component. It inherits the JComponent class.

11) JTree: The JTree class is used to display the tree structured data or
hierarchical data. JTree is a complex component. It has a 'root node' at the top
most which is a parent for all nodes in the tree. It inherits JComponent class.

12) JTable: The JTable class is used to display data in tabular form. It is
composed of rows and columns.

13) JScrollPane: A JscrollPane is used to make scrollable view of a


component. When screen size is limited, we use a scroll pane to display a large
component or a component whose size can change dynamically.

Program Code: package


college;

import java.awt.event.ActionEvent; import


java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

public class Expt13 {


Expt13()
{

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

JFrame jf=new JFrame("Experiment 13");


jf.setLayout(null) ;
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
jf.setSize(600,750);

JMenuBar jmb=new JMenuBar();

jmb.setBounds(1,1,800,20); JMenu

jm=new JMenu("Menu"); jmb.add(jm);

JMenuItem i1=new JMenuItem("File");


JMenuItem i2=new JMenuItem("Open");
JMenuItem i3=new JMenuItem("Save");
JMenuItem i4=new JMenuItem("Exit");

jm.add(i1);
jm.add(i2);
jm.add(i3);
jm.add(i4);

jmb.add(jm);
jf.add(jmb);

JLabel jl=new JLabel("Enter


Name"); jl.setBounds(15,50,100,30);
jf.add(jl);

JTextField jt=new JTextField();


jt.setBounds(150,50,150,30);
jf.add(jt);

String item[]= {"Student","Fresher","Faculty"};

JComboBox jc= new JComboBox(item)


; jc.setBounds(15,100,100,30);
jf.add(jc);
JCheckBox type=new JCheckBox();
type.setText("Regular");

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

type.setBounds(150,100,150,50);
jf.add(type);

JLabel jg=new JLabel("Gender");


jg.setBounds(15,180,100,20);
jf.add(jg);

JRadioButton jrd1=new JRadioButton("Male");


JRadioButton jrd2=new JRadioButton("Female");

jrd1.setBounds(15,200,100,30);
jrd2.setBounds(15,240,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(jrd1);
bg.add(jrd2);
jf.add(jrd1);
jf.add(jrd2);

String[] week=
{ "January","Feburary","March","April","May","June","July"};
JList list= new JList(week) ;

JScrollPane jsp=new
JScrollPane(list);
jsp.setBounds(150,250,100,80);
jsp.getViewport().add(list);
jf.add(jsp);

String[] column= {"Roll no","Name","Branch"};


String[][] rows= {{"1","ABC","IT"},{"2","ASD","CS"}, {
"3","XCV","IT"},{"3","LMN","CS"}};;

JTable jtab=new
JTable(rows,column); JScrollPane sp = new
JScrollPane(jtab);
sp.setBounds(30,400,200,80);
sp.getViewport().add(jtab); jf.add(sp);

JButton jbt=new JButton("SUBMIT");


jbt.setBounds(50,500,150,100);
jf.add(jbt);

Downloaded by Ravi Rane


lOMoAR cPSD| 29418202

jbt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(jbt, "User
Registered");
}
}) ;

DefaultMutableTreeNode main=new
DefaultMutableTreeNode("MAIN");

DefaultMutableTreeNode top=new
DefaultMutableTreeNode("Options");

DefaultMutableTreeNode a1=new DefaultMutableTreeNode("My


Folder");
DefaultMutableTreeNode a2=new
DefaultMutableTreeNode("Files");
DefaultMutableTreeNode a3=new
DefaultMutableTreeNode("Java");

top.add(a1);
top.add(a2);
top.add(a3);

DefaultMutableTreeNode top2=new DefaultMutableTreeNode("Options


2 ");

DefaultMutableTreeNode b1=new DefaultMutableTreeNode("My


Folder");
DefaultMutableTreeNode b2=new
DefaultMutableTreeNode("Files");
DefaultMutableTreeNode b3=new
DefaultMutableTreeNode("Physics");

top2.add(b1);
top2.add(b2);
top2.add(b3);
main.add(top);
main.add(top2);

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

JTree tree=new JTree(main);


tree.setBounds(400,20,150,150);
jf.add(tree);

jf.setVisible(true) ;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Expt13 obj=new Expt13();
}
}
Output:

Conclusion:
Created a GUI with basic Java Swing Components. A Menu Bar is created in
which menu is included. In the menu there is menu items like File ,Open, Save
and Exit. Label is used to display some information on the frame like here it is
used to display Enter Name. In front of the label a text box is used to take input
from user. There is ComboBox for selecting one item from the drop down. A
table is used to display information of students. There is a list to select name of
month. Scroll Pane is added to table and list for scrolling vertically. A tree is
created with two sub tree named option and option 2. Both the sub trees have
three sub tree. At the end of the frame button named SUBMIT is created. The
button is added an ActionListener. When button is clicked a message box appears
with message written as “User Registered”.

Downloaded by Ravi Rane


lOMoAR cPSD| 29418202

Experiment no :- 08

Title : Write a java program to create a student profile form using AWT
controls.

Problem Statement :
Java program to store a Student Information in a File using AWT.
Theory :
Swing is a part of the JFC (Java Foundation Classes). Building Graphical User
Interface in Java requires the use of Swings. Swing Framework contains a large
set of components which allow a high level of customization and provide rich
functionalities, and is used to create window-based applications. Java swing
components are lightweight, platform-independent, provide powerful
components like tables, scroll panels, buttons, list, colour chooser, etc.
In this article, we will see how to write the students information in a Jframe and
store it in a file.

Approach: To solve this problem, the following steps are followed:

1 .First, we need to create a frame using JFrame.


2.Next create JLabels, JTextFields, JComboBoxes, JButtons and set their
bounds respectively.
3 .Name these components accordingly and set their bounds.
4 .Now, in order to save the data into the text file on button click, we need to
add Event Handlers. In this case, we will add ActionListener to perform an
action method known as actionPerformed in which first we need to get the
values from the text fields which is default as a “string”.
5.Finally, the Jbuttons, JLabels, JTextFields and JComboBoxes are added to the
JFrame and the text is stored in a text file.

Algorithm :

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Step1:First, we need to create a frame using JFrame.


step 2:Next create JLabels, JTextFields, JComboBoxes, JButtons and set their
bounds respectively.
Step 3:Name these components accordingly and set their bounds.
Step 4:Now, in order to save the data into the text file on button click, we need
to add Event Handlers. In this case, we will add ActionListener to perform an
action method known as actionPerformed in which first we need to get the
values from the text fields which is default as a “string”.
Step 5:Finally, the Jbuttons, JLabels, JTextFields and JComboBoxes are added
to the JFrame and the text is stored in a text file.

Program :

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class GFG {

// Function to write a student


// information in JFrame and
// storing it in a file
public static void StudentInfo()
{

// Creating a new frame using JFrame


JFrame f
= new JFrame(
"Student Details Form");

// Creating the labels


JLabel l1, l2, l3, l4, l5;

// Creating three text fields.


// One for student name, one for

Downloaded by Ravi Rane


lOMoAR cPSD| 29418202

// college mail ID and one


// for Mobile No
JTextField t1, t2, t3;

// Creating two JComboboxes


// one for Branch and one
// for Section
JComboBox j1, j2;

// Creating two buttons


JButton b1, b2;

// Naming the labels and setting //


the bounds for the labels l1 = new
JLabel("Student Name:");
l1.setBounds(50, 50, 100, 30); l2 =
new JLabel("College Email ID:");
l2.setBounds(50, 120, 120, 30); l3 =
new JLabel("Branch:");
l3.setBounds(50, 190, 50, 30); l4 =
new JLabel("Section:");
l4.setBounds(420, 50, 70, 30); l5 =
new JLabel("Mobile No:");
l5.setBounds(420, 120, 70, 30);

// Creating the textfields and


// setting the bounds for textfields
t1 = new JTextField();
t1.setBounds(150, 50, 130, 30); t2
= new JTextField();
t2.setBounds(160, 120, 130, 30);
t3 = new JTextField();
t3.setBounds(490, 120, 130, 30);

// Creating two string arrays one for


// braches and other for sections
String s1[]
= { " ", "CSE", "ECE", "EEE",
"CIVIL", "MEC", "Others" };
String s2[]

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

= { " ", "Section-A", "Section-B",


"Section-C", "Section-D",
"Section-E" };

// Creating two JComboBoxes one for // selecting branch and


other for
// selecting the section
// and setting the bounds j1
= new JComboBox(s1);
j1.setBounds(120, 190, 100, 30);
j2 = new JComboBox(s2);
j2.setBounds(470, 50, 140, 30);

// Creating one button for Saving


// and other button to close
// and setting the bounds b1 =
new JButton("Save");
b1.setBounds(150, 300, 70, 30);
b2 = new JButton("close");
b2.setBounds(420, 300, 70, 30);

// Adding action listener


b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{

// Getting the text from text fields


// and JComboboxes
// and copying it to a strings

String s1 = t1.getText();
String s2 = t2.getText();
String s3 = j1.getSelectedItem() + "";
String s4 = j2.getSelectedItem() + "";
String s5 = t3.getText();
if (e.getSource() == b1) {
try {

Downloaded by Ravi Rane


lOMoAR cPSD| 29418202

// Creating a file and


// writing the data //
into a Textfile.
FileWriter w
= new FileWriter(
"GFG.txt", true);

w.write(s1 + "\n");
w.write(s2 + "\n");
w.write(s3 + "\n");
w.write(s4 + "\n");
w.write(s5 + "\n");
w.close();
}
catch (Exception ae) {
System.out.println(ae);
}
}

// Shows a Pop up Message when


// save button is clicked
JOptionPane
.showMessageDialog(
f,
"Successfully Saved"
+ " The Details");
}
});

// Action listener to close the form


b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
f.dispose();
}
});

// Default method for closing the frame

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

// Adding the created objects


// to the frame f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.add(l3);
f.add(j1);
f.add(l4);
f.add(j2);
f.add(l5);
f.add(t3);
f.add(b1);
f.add(b2);
f.setLayout(null);
f.setSize(700, 600);
f.setVisible(true);
}
// Driver code
public static void main(String args[])
{
StudentInfo();
}}

Actual input/output :
a) The window displayed on running the program:

Downloaded by Ravi Rane


lOMoAR cPSD| 29418202

b) Entering the data:

c) The dialog box showed after clicking on the save buttonbutton:

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

d) The text file in which the data is stored:

Conclusion : Thus we have to studied Java program to store a


Student Information in a File using AWT controls. Also we are learn
about GUI programming(AWT,event handling, swing) .

Downloaded by Ravi Rane


lOMoAR cPSD| 29418202

Experiment no :- 09
Title: To study GUI programming- I(AWT,Event Handling, Swing) and
implement the program.

Problem statement: Write a Java Program to create a color palette. Declare


a grid of Buttons to set the color names. Change the background color by
clicking on the color button.

Theory:
1.The GridLayout class is a layout manager that lays out a container's
components in a rectangular grid.

2.An action event is a semantic event which indicates that a component-defined


action occurred.

3.ActionListener in Java is a class that is responsible for handling all action


events such as when the user clicks on a component. action listeners are used
for JButtons.

4.The JButton class is used to create a labeled button that has platform
independent implementation.

5.JLabel is used to display a short string or an image icon. JLabel can display
text, image or both.

6.JFrame is a top-level container that provides a window on the screen.

7 .The Color class is used to encapsulate colors in the default sRGB color .

8 .setVisible(true) is a blocking operation and blocks until dialog is closed.

9 .The setSize() method of Java Vector class is used to set the size of a vector.

10.The getContentPane() method retrieves the content pane layer so that you
can add an object to it.

11 .Object getSource() Returns the object on which the event occurred.

12.setTitle(String title) Sets the title for this frame to the specified string.
Algorithm:

Algorithm Steps:

Step 1: Write a html applet tag with code set class name and comment the tag

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

Step 2: Import all necessary packages and classes

Step 3: Define a class that extends applet and implements action listener and
action listener

Step 4: Declare an array of buttons to set colors, for background colors

Step 5: Declare JFrame

Step 6: Declare a string color.

Step 7: Declare jButton,jLable for button and color. Step


8: In the actionPerformed() method, do the following

i) Get the action Listener commond the string, color


ii)Create an array of 9 buttons for various colors

iii)Add action listener to each button and add all of them to button panel iv) If
background is checked then set the background color to the selected color

v)Create a text area and change its font to desired one.

vi)Create the palettepanel and set is layout to border layout


vii)Add the palettepanel to the applet

Step 9: In the actionPerformed() method, do the following:

i) Get the action command in the string, color


ii) the background color to the selected color

iii) If background is checked then set the background color to the selected color

Program:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

Downloaded by Ravi Rane


lOMoAR cPSD| 29418202

import javax.swing.*;

public class abcd extends JFrame implements ActionListener{

private JButton red,blue,green,yellow,black,cyan,pink,orange,gray; private


JLabel label;

JFrame f;

public abcd()
{
f = new JFrame() ;
red = new JButton("red") ;
green = new JButton("green") ;
blue = new JButton("blue") ;
yellow = new JButton("yellow") ; black
= new JButton("black") ;
cyan = new JButton("cyan") ; pink
= new JButton("pink") ; orange =
new JButton("orange") ; gray = new
JButton("gray") ;

label = new JLabel("Select Background") ;

red.addActionListener(this) ;
green.addActionListener(this) ; blue.addActionListener(this)
; yellow.addActionListener(this) ;

black.addActionListener(this) ;
cyan.addActionListener(this) ;
pink.addActionListener(this) ;
orange.addActionListener(this) ;
gray.addActionListener(this) ;

f.add(red);
f.add(green);
f.add(blue) ;
f.add(yellow) ;
f.add(black) ;
f.add(cyan) ;

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

f.add(pink) ;
f.add(orange) ;
f.add(gray) ;
f.add(label) ;

f.setVisible(true) ;
f.setSize(500,500);
f.setTitle("Color Changer") ;
f.setLayout(new GridLayout(4,3,40,40));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
f.getContentPane().setBackground(Color.white) ;

public static void main(String[] args)


{ new
abcd() ; }

public void actionPerformed(ActionEvent e)


{ if (e.getSource() ==
red)
{
label.setText("Red selected") ;
f.getContentPane().setBackground(Color.RED) ;

if (e.getSource() == green)
{
label.setText("Green selected") ;
f.getContentPane().setBackground(Color.GREEN) ;
}

if(e.getSource() == blue)
{

Downloaded by Ravi Rane


lOMoAR cPSD| 29418202

label.setText("Blue selected") ;
f.getContentPane().setBackground(Color.BLUE) ;
}
if(e.getSource() == yellow)
{
label.setText("Yellow selected") ;
f.getContentPane().setBackground(Color.YELLOW) ;
}
if (e.getSource() == black)
{ label.setText("black
selected") ;

f.getContentPane().setBackground(Color.BLACK) ;

if (e.getSource() == cyan)
{
label.setText("Cyan selected") ;
f.getContentPane().setBackground(Color.CYAN) ;
}

if(e.getSource() == pink)
{
label.setText("Pink selected") ;
f.getContentPane().setBackground(Color.PINK) ;
}
if(e.getSource() == orange)
{
label.setText("orange selected") ;
f.getContentPane().setBackground(Color.ORANGE) ;

}
if(e.getSource() == gray)
{ label.setText("Grey
selected") ;

f.getContentPane().setBackground(Color.GRAY) ;

Downloaded by Ravi Rane ([email protected])


lOMoAR cPSD| 29418202

} }

ACTUAL INPUT/ OUTPUT:

CONCLUSION: How to change background color by clicking on color name.

Downloaded by Ravi Rane

You might also like