[go: up one dir, main page]

0% found this document useful (0 votes)
95 views34 pages

JAVApractical VIVEKSINGH

Here is the program to create a frame using AWT and implement mouse events: import java.awt.*; import java.awt.event.*; public class FrameDemo extends Frame implements MouseListener{ public FrameDemo(){ addMouseListener(this); setSize(300,300); setLayout(null); setVisible(true); } public static void main(String args[]){ new FrameDemo(); } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void

Uploaded by

Twinkle
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)
95 views34 pages

JAVApractical VIVEKSINGH

Here is the program to create a frame using AWT and implement mouse events: import java.awt.*; import java.awt.event.*; public class FrameDemo extends Frame implements MouseListener{ public FrameDemo(){ addMouseListener(this); setSize(300,300); setLayout(null); setVisible(true); } public static void main(String args[]){ new FrameDemo(); } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void

Uploaded by

Twinkle
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
You are on page 1/ 34

Practical File

Course: B.Sc. (Hons.) Computer Science

I Year – II Semester

NAME: VIVEK SINGH


ROLL NO: 2102075

1
Programming in Java
1:- Design a class Complex having a real part (x) and an imaginary part (y).
Provide methods to perform the following on complex numbers:

a) Add two complex numbers. b) Multiply two complex numbers.

c) Override toString() method to display complex numbers in the form: x + i

Code:-

import java.util.*;

class Complex{

int x,y;

Complex(int a,int b)

{x=a;y=b;

}Complex()

{x=0;y=0;

} int addcomplex(Complex o)

{ int a=(x+o.x);

int b=(y+o.y);
System.out.println("Complex number after addition

is="+a+"+"+b+"i");

return 0; }

int mulcomplex(Complex o)

{ int a=x*o.x-y*o.y;

int b=y*o.x+o.y*x;

System.out.println("Complex no. after multiplication="+a+"+"+b+"i");

return 0; }

2
int tostring()

{ System.out.println("Complex number is :"+x+"+"+y+"i");

return 0; }}

class Complexp1{

public static void main(String args[])

{ Scanner sc=new Scanner(System.in);

int x,y=0;

System.out.print("Enter real part :");

x=sc.nextInt();

System.out.print("Enter imaginary part :");

y=sc.nextInt();

Complex A=new Complex(x,y);

A.tostring();

System.out.println("Enter real part :");

x=sc.nextInt();

System.out.println("Enter imaginary part :");

y=sc.nextInt();

Complex B=new Complex(x,y);

B.tostring();

A.addcomplex(B);

A.mulcomplex(B);

sc.close(); }}

Execution:-

3
2:- Create a class TwoDim which contains private members as x and y coordinates in package P1.
Define the default constructor, a parameterized constructor and override toString() method to display the co-ordinates. Now reuse
this class and in package P2 create another class ThreeDim, adding a new dimension as z as its
private member. Define the constructors for the subclass and override toString() method in the subclass also.
Write appropriate methods to show dynamic method dispatch. The main() function should be in a
package P.

Code:-

package P1;
public class TwoDim{
int x,y;
public TwoDim(){}
public TwoDim(int a,int b)
{ x=a;y=b; }
public String toString()
{ return "The coordinates are : "+x+","+y;
}}
package P2;
import P1.*;
public class ThreeDim extends TwoDim{
int z;
public ThreeDim(){
super(); }
public ThreeDim(int a,int b,int c)

4
{ super(a,b);
z=c;
} public String toString()
{ return super.toString()+","+z;
}}
package P;
import P1.*;
import P2.*;
public class Prac2 {
public static void main(String args[]){
TwoDim a = new TwoDim(2,3);
ThreeDim b = new ThreeDim(3,4,5);
System.out.println(a.toString());
System.out.println(b.toString());
}}
Execution:-

3. Define an abstract class Shape in package P1. Inherit two more classes: Rectangle in Package P2 and
Circle in package P3. Write a program to ask the user for the type of shape and then using the concept of
dynamic method dispatch, display the area of the appropriate subclass. Also write
appropriate methods to read the data. The main() function should not be in any
package.

Code:-

package P1;

5
public abstract class Shape{
public abstract double getArea();}
package P2;
import P1.Shape;
public class Rectangle extends Shape{
double l,b;
public Rectangle(double len, double br){
l = len;
b = br;}
public double getArea(){
double ar = l*b;
System.out.print("The area of the rectangle is : ");
return ar;}
}
package P3;
import P1.Shape;
public class Circle extends Shape{
double rad;
public Circle(double r){
rad = r;}
public double getArea(){
double ar = (3.14)*rad*rad;
System.out.print("The area of the Circle is : ");
return ar;}}
import P1.Shape;
import P2.Rectangle;
import P3.Circle;
import java.util.*;

6
class Prac3{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Shape sh;
System.out.println("choose option :\n1 For Rectangle \n2 for Circle \n");
int p;
p = sc.nextInt();
if(p==1)
{int l, b;
System.out.println("enter length and breadth");
l = sc.nextInt();
b = sc.nextInt();
sh = new Rectangle(l,b);
System.out.println(sh.getArea());
}else if(p==2)
{int r;
System.out.print("Enter the radius : ");
r = sc.nextInt();
sh = new Circle(r);
System.out.println(sh.getArea());
}else
{System.out.println("Invalid option");}
sc.close();}}
Execution;-

7
Code:-

import java.util.Scanner;

class UnderAge extends Exception{


public String toString() {
return "Under Age \n Age is less than 18 "; }
public String getMessage() {
return "Age is less than 18 ";
}}
public class exceptionDemo {
public static void test(int age) throws UnderAge{
if(age<18){
throw new UnderAge();
}
else{
System.out.println("Age entered by You is " + age);
} }

8
public static void main(String[] args) throws UnderAge {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Age ");
int Age = sc.nextInt();
test(Age);
sc.close();
}}
Execution:-

Code:-

import java.util.*;

class OverFlowExcep extends Exception{

public String getMsg(){

return "Overflow exceotion : Maximum size of stack reached."; }}

class UnderFlowExcep extends Exception{

public String getMsg(){

return "Underflow exception : no element in the stack."; }}

class Stack{

int size,stk[],tos;

Stack(int s){

9
size=s;

stk = new int[size];

tos = -1; }

void display() throws UnderFlowExcep

{ if(tos<0) {

throw new UnderFlowExcep(); }

else{ System.out.println("Currently elements of stack are:");

for(int i=0;i<tos+1;i++)

{ System.out.println(stk[i]+" "); } } }

void push(int element) throws OverFlowExcep

{ if(tos==size-1) {

throw new OverFlowExcep();}

else{ stk[++tos]=element; } }

int pop() throws UnderFlowExcep

{ if(tos<0) { throw new UnderFlowExcep(); }

return stk[tos--]; }

int peek() throws UnderFlowExcep

{ if(tos<0) { throw new UnderFlowExcep(); }

else{ return stk[tos]; } }}

public class Practical5{

public static void main(String srgs[]){

Scanner sc = new Scanner(System.in);

int size;

System.out.println("Enter the size of the stack =");

10
size = sc.nextInt();

Stack stack = new Stack(size);

char ch='y';

int num = 0;

while(ch=='y'||ch=='Y')

{ System.out.println("Enter 1 to push element into stack.");

System.out.println("Enter 2 to pop element from stack.");

System.out.println("Enetr 3 to peek into stack.");

System.out.println("Enetr 4 to display the stack.");

num=sc.nextInt();

switch(num)

{ case 1: try{

System.out.println("Enter number you want to push=");

int element = sc.nextInt();

stack.push(element); }

catch(Exception e){ System.out.println(e); }

break;

case 2: try{

System.out.println("Element "+stack.pop()+" popped ."); }

catch(Exception e){ System.out.println(e); }

break;

case 3: try{ System.out.println("Top element of stack

is="+stack.peek());}

catch(Exception e){ System.out.println(e); }

11
break;

case 4: try{ stack.display(); }

catch(Exception e){ System.out.println(e); }

break; }

System.out.println("Do you want to operate again? enter y");

ch=sc.next().charAt(0); }

sc.close(); }}

Execution:-

12
13
Code:-

import java.io.*;
class Prac6{
public static void main(String args[]) throws IOException
{ int i;
try(FileInputStream fin=new FileInputStream(args[0]);
FileOutputStream fout=new FileOutputStream(args[1]))
{ do{ i=fin.read();
if(i != -1)
{ fout.write(i); }
}while(i != -1);
}catch(IOException e)
{ System.out.println("I/O error"+e); }
System.out.println("File copied sucessfully."); }}

14
Source file:-

Destination file before execution of code:-

Destination file after execution of code:-

15
Code:-

import java.io.*;
import java.util.Scanner;
public class Practical7 {
public static void main(String args[]) throws IOException
{ try(FileInputStream fin = new FileInputStream("Prac7.txt"))
{ Scanner sc = new Scanner(fin);
while(sc.hasNextLine())
{ String line = sc.nextLine();
if(line.startsWith("//"))
{ System.out.println(line); } }
sc.close(); }
catch(Exception e)
{ System.out.println(e); }
finally{ System.out.println("Reached the end of file."); }}}
Execution:-

08:-Write a program to create a frame using AWT. Implement mouseClicked(),


mouseEntered() and mouseExited() events such that:

a) Size of the frame should be tripled when mouse enters it.

16
b) Frame should reduce to its original size when mouse is clicked in it. c)
Close the frame when mouse exits it.

Code:-

Import java.awt.*;
Import java.awt.event.*;

Class MyFrame extends Frame{


int width = 300;
int height= 300;
Dimension D;
Stringmsg=" ";

MyFrame(){
addMouseListener(new MyMouseAdapter(this));
addWindowListener(new MyWindowAdapter(this));
setSize(width, height);
setBackground(Color.MAGENTA);
setVisible(true);
D= getSize(); }
Public void paint(Graphics g){
g.drawString(msg, 50, 100); }}

classMyMouseAdapterextendsMouseAdapter{
MyFrame Frame;
MyMouseAdapter(MyFrame Frame){
this.Frame=Frame; }
publicvoidmouseClicked(MouseEvent me){
Frame.msg=" MOUSE CLICKED ";
Frame.setSize(Frame.D);
Frame.repaint(); }
publicvoid mouseEntered(MouseEvent me){
Frame.msg=" MOUSE ENTERED ";
Frame.setSize(Frame.D.height*3,Frame.D.width*3);
Frame.repaint(); }
publicvoidmouseExited(MouseEvent me){
Frame.msg=" MOUSE EXITED ";
Frame.repaint();
System.exit(0); }}
classMyWindowAdapterextendsWindowAdapter{

17
MyFrame Frame;
MyWindowAdapter(MyFrame Frame){
this.Frame=Frame; }
publicvoidwindowClosing(WindowEvent we){
Frame.setVisible(false);
//System.exit(0); }}

class Practical8 {
publicstaticvoidmain(String[] args) {
MyFrame F= newMyFrame(); }}

Execution:-

Initially When mouse entered When Mouse Clicked

09:-Using AWT, write a program to display a string in frame window with pink
color as background.

Code:-

Import java.awt.Frame;
Import java.awt.FlowLayout;
Import java.awt.Color;
Import java.awt.TextField;
Import java.awt.event.*;

classMyFrameextendsFrame{
publicMyFrame(){
addWindowListener(newMyWindowAdapter());
setBounds(50,50,400,200);
setVisible(true);
setBackground(Color.PINK);
setLayout(newFlowLayout());

18
TextFieldtf= newTextField("THIS TEXT WILL GET DISPLAYED IN
FRAME");
add(tf); }

classMyWindowAdapterextendsWindowAdapter{
publicvoidwindowClosing(WindowEvent we){
System.exit(0); }}}

publicclass Practical9 {
publicstaticvoidmain(String[] args) {
MyFrameobj= newMyFrame(); } }
Execution:-

10 :- Using AWT, write a program to create two buttons named “Red” and
“Blue”. When a button is pressed the background color should be set to the
color named by the button’s label.

Code:-

Impor tjava.awt.*;
impor tjava.awt.event.*;

class MyFrameextends Frame implementsActionListener{


int width = 300;
int height= 300;
String msg =" ";
Button b1, b2;
MyFrame(){

19
addWindowListener(new MyWindowAdapter());
setSize(width, height);
setTitle("Practical- 10");
setLayout(newFlowLayout());

b1=new Button("RED");
b1.addActionListener(this);
b1.setBackground(Color.RED);
add(b1);

b2=new Button("BLUE");
b2.addActionListener(this);
b2.setBackground(Color.BLUE);
add(b2);

setVisible(true); }
Public void paint(Graphics g){
g.drawString(msg, 70, 200);; }
publicvoidactionPerformed(ActionEvent e){
Object source = e.getSource();
if(source == b1){
setBackground(Color.RED);
msg="CLICKED ON RED BUTTON ";
repaint(); }
if(source ==b2){
setBackground(Color.BLUE);
msg="CLICKED ON BLUE BUTTON ";
repaint(); } }}

Class MyWindowAdapter extends WindowAdapter{


Public void windowClosing(WindowEvent we){
System.exit(1); }}

class Practical10{
public static void main(String[] args) {
MyFrame F= newMyFrame(); }}

20
Execution:-

11) Using AWT, write a


program using appropriate
adapter class to display the message
(“Typed character is: <typedCharacter>") in the
frame window when user types any key.
Code:-

import java.awt.*;

import java.awt.event.*;

class myframek extends Frame

{ String msg= "Typed Characters are: ";

String msg1= " ";

String msg2= " ";

myframek (String s)

{ super(s);

setBackground(Color.cyan);

setForeground(Color.gray);

addKeyListener(new MyKeyAdapterk(this));

addWindowListener((WindowListener)new

MyWindowAdapterk(this));}

public void paint(Graphics g)

{ g.drawString(msg, 100, 100);

g.drawString(msg1, 100, 120);

21
g.drawString(msg2, 100, 130); } }

class MyKeyAdapterk extends KeyAdapter

{ myframek o1;

int counter=0;

MyKeyAdapterk (myframek o3)

{ o1=o3; }

public void keyTyped(KeyEvent ae)

{ counter++;

if(counter<=20)

o1.msg+=Character.toString(ae.getKeyChar());

else if(counter<=40)

o1.msg1+=Character.toString(ae.getKeyChar());

else

o1.msg2+=Character.toString(ae.getKeyChar());

o1.repaint(); } }

class MyWindowAdapterk extends WindowAdapter

{ myframek o1; MyWindowAdapterk(myframek o5)

{ o1=o5;}

public void windowClosing(WindowEvent ae)

{ o1.setVisible(false); } }

public class KeyTypedevent {

public static void main(String[] args) {

myframek o1=new myframek("KeyTypedEventHandling");

o1.setSize(new Dimension(400, 400));

22
o1.setVisible(true); } }

Execution:-

12>Using AWT, write a program to create two buttons labelled ‘A’and ‘B’.
When button ‘A’ is pressed, it displays your personal information (Name,
Course, Roll No, College) and when button ‘B’ is pressed, it displays your
CGPA in previous semester.

Code:-

import java.awt.*;

import java.awt.event.*;

class student

{ String Name, Course, College;

int Rollno;

double cgpa;

student(String s, String c, String cg, int roll, double cgpa)

{ Name=s;

Course=c;

College=cg;

Rollno=roll;

this.cgpa=cgpa; } }

class Myframebutton2 extends Frame implements ActionListener{

23
Button b1, b2;

String msg=" ";

student s1= new student("Vivek Singh "," B.sc(h) Computer

Science ","BCAS ", 2102075 ,10);

Myframebutton2() {

b1=new Button("A");

b2=new Button("B");

setLayout (new FlowLayout());

add(b1);

add(b2);

b1.addActionListener(this);

b2.addActionListener(this);

addWindowListener(new MyWindowAdapterb2(this)); }

public void actionPerformed(ActionEvent ae) {

String s=ae.getActionCommand();

msg=" ";

if(s.equals("A"))

msg+="Name : "+ s1.Name + "Course : "+ s1.Course + "College: " +

s1.College + "Rollno : " + s1.Rollno ;

else if(s.equals("B"))

msg+="CGPA : "+ s1.cgpa;

repaint();

public void paint(Graphics g)

{ g.drawString(msg,100,100); }}

24
class MyWindowAdapterb2 extends WindowAdapter{

Myframebutton2 o1;

MyWindowAdapterb2(Myframebutton2 o2)

{o1=o2;}

public void windowClosing(WindowEvent ae)

{o1.setVisible(false);}}

public class Buttonstudentcgpa {

public static void main(String[] args) {

// TODO Auto-generated method stub

Myframebutton2 o1=new Myframebutton2();

o1.setTitle("ButtonEventHndling2");

o1.setSize(new Dimension(400,400));

o1.setVisible(true); } }

Execution:-

13>Rewrite all the above GUI programs using Swing.


13.(1)-

25
Code:-

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class panel extends JPanel

{String s="Hello";

protected void paintComponent(Graphics g)

{super.paintComponent(g); g.drawString(s, 50, 100);}}

class Mouse extends JFrame

{Dimension d;

//JFrame o1;

panel p;

Mouse(){

super("MouseEventHndling swings");

p=new panel();

//setTitle(""); setSize(500,500);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); d=getSize();

p.setLayout(new FlowLayout()); add(p);

addMouseListener(new MyMouseAdapter(this, d)); setVisible(true);}}

class MyMouseAdapter extends MouseAdapter

{JFrame o1; Dimension d; String msg=" ";

MyMouseAdapter(JFrame o2, Dimension d1){

o1=o2; d=d1;}

public void mouseEntered(MouseEvent me)

26
{Dimension d1; d1=o1.getSize();

o1.setSize(d1.width*3, d1.height*3); o1.repaint();}

public void mouseClicked(MouseEvent me){

msg="Mouse Clicked window size="+d.width+"and"+d.height;

o1.setSize(d);}

public void mouseExited(MouseEvent me)

{o1.setVisible(false);}}

public class MouseSwings {

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run(){

new Mouse(); }});}}

Execution:-

13.(2)- Source Code:-

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

27
class PanelS extends JPanel{

String s="Hello";

protected void paintComponent(Graphics g){

super.paintComponent(g); setBackground(Color.pink); g.drawString(s,

100, 100);}}

class FrameS extends JFrame{

PanelS p; FrameS()

{super("Frame Swing"); p=new PanelS(); setSize(400,400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(p);

setVisible(true);}}

public class FrameSwing {

public static void main(String[] args) {

// TODO Auto-generated method stub

SwingUtilities.invokeLater(new Runnable()

{public void run()

{new FrameS();}});}}

Execution:-

28
13.(3)- Source Code:-

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

class SwingsDemo extends JFrame implements ActionListener

{JButton b1, b2; SwingsDemo()

{setTitle("Button swing program"); b1= new JButton ("Red");

b2= new JButton("Blue"); setSize(new Dimension (500,500));

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new

FlowLayout()); getContentPane().add(b1);

getContentPane().add(b2); b1.addActionListener(this);

b2.addActionListener(this); setVisible(true);}

public void actionPerformed(ActionEvent ae)

{String s=ae.getActionCommand();

if(s.equals("Red"))

getContentPane().setBackground(Color.RED);

if(s.equals("Blue")) getContentPane().setBackground(Color.BLUE);}}

public class SwingButton {

public static void main(String[] args) {

// TODO Auto-generated method stub

SwingUtilities.invokeLater(new Runnable()

{public void run(){new SwingsDemo();

}});}}
Execution:-

29
13.(4)- Source Code:-

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

class PanelK extends JPanel

{String msg1="Typed Characters :"; String msg2=" ";

String msg3=" ";

protected void paintComponent(Graphics g)

{super.paintComponent(g); g.drawString(msg1, 150,150);

g.drawString(msg2, 150,170);

g.drawString(msg3, 150,190);}}

class FrameK extends JFrame

{PanelK p1; FrameK()

{super("Key Event Handling Swings"); setSize(450,450);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); p1=new

PanelK();
30
add(p1);

addKeyListener(new MyKeyAdapter(p1)); setVisible(true);}

class MyKeyAdapter extends KeyAdapter

{int counter=0; PanelK p2;

MyKeyAdapter(PanelK p3){

p2=p3;}

public void keyTyped(KeyEvent ke)

{counter++;

if (counter<=20) p2.msg1+=ke.getKeyChar(); else if (counter<=40)

p2.msg2+=ke.getKeyChar();

else

p2.msg3+=ke.getKeyChar();

p2.repaint(); }}}

public class KeyEventHandlingSwings {

public static void main(String[] args) {

// TODO Auto-generated method stub

SwingUtilities.invokeLater(new Runnable()

{ public void run()

{ new FrameK(); }}); }}

Execution:-

31
13.(5)- Source Code:-

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


class student

{String Name, Course, College;


int Rollno;
double cgpa;
student(String s, String c, String cg, int roll, double cgpa)
{Name=s; Course=c; College=cg; Rollno=roll; this.cgpa=cgpa;}}
class Panel extends JPanel
{String msg1=" "; String msg2=" "; String msg3=" "; String msg4=" ";
public void paintComponent(Graphics g){
super.paintComponent(g); g.drawString(msg1, 150, 200);
g.drawString(msg2, 150, 220);
g.drawString(msg3, 150, 240);
g.drawString(msg4, 150, 260);}}
class Button extends JFrame implements ActionListener
{JButton b1, b2; Panel p1;
student s1= new student(" Vivek Singh " , " B.Sc(H) Computer science"
, " BCAS ", 2102075 , 8.1 );
Button(){
setTitle("ButtonABCGPA"); setSize(500,500);
p1=new Panel(); b1=new JButton("A"); b2=new JButton("B");

32
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1.setLayout(new FlowLayout());
p1.add(b1);
p1.add(b2);
add(p1); b1.addActionListener(this); b2.addActionListener(this);
setVisible(true);}
public void actionPerformed(ActionEvent ae)
{String s=ae.getActionCommand();
if(s.equals("A")){
p1.msg1="Name="+s1.Name; p1.msg2="Course="+s1.Course;
p1.msg3="College="+s1.College; p1.msg4="Rollno="+s1.Rollno;
p1.repaint();}
else if(s.equals("B"))
{p1.msg1="CGPA="+s1.cgpa; p1.msg2=" ";
p1.msg3=" ";
p1.msg4=" ";
p1.repaint();}}}
ublic class ButtonAandB {
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable(){
public void run()
{new Button();}} );}}

Execution:-

33
34

You might also like