Saturday, October 10, 2020

write python turtle program to draw letter E

 import turtle

t=turtle.Turtle()

t.penup()

t.setpos(0,50)

t.pendown()

t.pensize(20)

t.pencolor("red")

t.forward(100)

t.backward(100)

t.right(90)

t.forward(100)

t.left(90)

t.forward(100)

t.backward(100)

t.right(90)

t.forward(100)

t.left(90)

t.forward(100)

write python turtle program for creating Archimedean spiral

 from turtle import *

from math import *

color("blue")

down()

for i in range(200):

    t = i / 20 * pi

    x = (1 + 5 * t) * cos(t)

    y = (1 + 5 * t) * sin(t)

    goto(x, y)

up()

done()

write a python program for creating a class Student with method and constructor

class student:

  def __init__(self,name,age):

        self.name=name

        self.age=age


  def myfunc(self,a,b):

        a=a+b

        return a


p1=student("john",23)

print("My names is",p1.name)

d=p1.myfunc(2,3)

print("sum is",d)

write a python program for creating class person with adding constructor, method

 class Person:

  def __init__(self, name, age):

    self.name = name

    self.age = age


  def myfunc(self):

    print("Hello my name is " + self.name)


p1 = Person("John", 36)

p1.myfunc()

write a java program for demonstration of Finally block

 class Finally1 

{

public static void main(String[] args) 

{

int data =20;

//case 4:finally block not exceuted when use the following method

System.exit(0);

try

{

int c=data/0;

System.out.println("c value is"+c);

}

finally

{

System.out.println("Finally block exceuted");

}

System.out.println("rest of the code exceuted");

}

}


write a java program for exception propagation

 class  Exceptionprop

{

static void s()

{

int data= 20/0;

}

static void  n()

{

        s();

}

static void  m()

{

n();

}

public static void main(String[] args) 

{

m();

System.out.println("Exception Caught at m()");

}

}


write a java program for creating own exception

class InvalidageExeption extends Exception 

{

InvalidageExeption(String s)

{

super(s);

}

}



class TestException 

{

static void validate(int age) throws InvalidageExeption

{

if(age<18)

throw new InvalidageExeption("not valid");

}

public static void main(String[] args) throws InvalidageExeption

{

validate(13);


}

}

 

Sunday, October 4, 2020

write a java program creating static variables?

class static12 

{

int x=5;

int y=10;

static int z=7;

public static void main(String[] args) 

{

      static12  s1=new static12();

System.out.println(s1.x+s1.y);

         System.out.println(z);

}

}

 

write a java program using throw keyword ?

 class Ex2 

{

static void  validate(int age)

{

if(age<18)

throw new ArithmeticException("not valid");

else

       System.out.println("age is valid");

}

public static void main(String[] args) 

{

try

{

validate(13);

}

catch(Exception e)

{

System.out.println(e);

}

System.out.println("rest of code");

}

}


write a java program for generating arithmetic exception division by zero

 class  Ex1

{

public static void main(String[] args) 

{

int a=5;

try

{

float b=5/0;

}

catch(Exception e)

{

System.out.println("exception caught");

       System.out.println(e);


}

      System.out.println("rest of code");

}

}


write a java program demonstrating relationship between abstract class and interface

 interface In

{

public void ms();

}

interface In1 extends In

{

public void msg();

}

abstract class  A23 implements In1

{

public void msg1()

{

System.out.println("abstract class method");

}

}

class A21 extends A23

{

public void msg()

{

System.out.println("In1 interface is implemented");

}

public void ms()

{

System.out.println("In interface is implemented");

}

public static void main(String[] args) 

{

A21 a1=new A21();

a1.msg();

a1.msg1();

a1.ms();

}

};

write a java program for exhibiting multiple inheritance through the interfaces

 interface showbale

{

void show();

static void print()

{

System.out.println("Hello World!");

}

}

interface printable

{

void print();

}

class  A221 implements showbale,printable

{

public void show()

{

System.out.println("Hello World!");

}

public void print()

{

System.out.println("Hello World!");

}

public static void main(String[] args) 

{

A221 a2=new A221();

a2.print();

a2.show();

}

}


Sunday, August 30, 2020

write a python program for arithmetic operations for accepting input dynamcially

 #Python program to do arithmetical operations

num1=input('enter number')

num2=input('enter number')

sum=int(num1)+int(num2)

sub=int(num1)-int(num2)

mul=int(num1)*int(num2)

div=int(num1)/int(num2)

exp=int(num1)**int(num2)



print('sum of  {0} num1 {1} and num2 {2} '.format(sum,num1,num2))

print('subtract of {0} num1 {1}and num2 {2}'.format(sub,num1,num2))

print('multiplication of {0}num1 {1} and num2 {2}'.format(mul,num1,num2))

print('divison of {0} num1 {1}and num2 {2}'.format(div,num1,num2))

print('exp of {0} num1 {1} and num2 {2} '.format(exp,num1,num2))

write a python program for implicit type conversion

 num_int = 123

num_flo = 1.23


num_new = num_int + num_flo


print("datatype of num_int:",type(num_int))

print("datatype of num_flo:",type(num_flo))


print("Value of num_new:",num_new)

print("datatype of num_new:",type(num_new))

write a python program drawing grid

def grid(row, col):

  """version with string concatenation"""

  sep = '\n' + '+---'*col + '+\n'

  return sep + ('|   '*col + '|' + sep)*row


print(grid(3,7))

Write a python program for using relational operator

 x = 10

y = 12


# Output: x > y is False

print('x > y is',x>y)


# Output: x < y is True

print('x < y is',x<y)


# Output: x == y is False

print('x == y is',x==y)


# Output: x != y is True

print('x != y is',x!=y)


# Output: x >= y is False

print('x >= y is',x>=y)


# Output: x <= y is True

print('x <= y is',x<=y)

write a python program for factorial using recursion - check types

 def factorial (n):

    if not isinstance(n, int):

        print('Factorial is only defined for integers.')

        return None

    elif n < 0:

         print('Factorial is not defined for negative integers.')

         return None

    elif n == 0:

         return 1

    else:

         return n * factorial(n-1)

factorial('fred')

factorial(-2)

write pyhton program for print current time

 import datetime

print(datetime.datetime.now())

write python program for drawing cricle using turtle

 import turtle

count = 0

while(count < 360):

    turtle.forward(2)

    turtle.left(1)

    count = count + 1

print("Finished!")

write a python program to draw the polygon

 # import turtle library

import turtle

polygon = turtle.Turtle()

my_num_sides = 6

my_side_length = 70

my_angle = 360.0 / my_num_sides

for i in range(my_num_sides):

     polygon.forward(my_side_length) 

     polygon.right(my_angle) 

turtle.done()

write a python Program drawing triangle shape using turtle

import turtle

turtle.forward(200)

turtle.left(90)

turtle.forward(200)

turtle.left(135)

c =((200**2)+(200**2))**0.5

turtle.forward(c) 

write a python program using turtle - star shape

 import turtle

 my_pen = turtle.Turtle()

 for i in range(50): 

my_pen.forward(50)

 my_pen.right(144) 

turtle.done()

write a pyhton program using turtle to draw shape L

 import turtle             

my_pen = turtle.Turtle()      

my_pen.forward(150)           

my_pen.left(90)               

my_pen.forward(75)

Python Program for while Loop

 def countdown(n):

    while(n>0):

        print(n)

        n=n-1

    print("blast")

countdown(4)

Thursday, August 13, 2020

write a java program for bigdecimal?

 import java.math.*;

class FloatTy 

{

public static void main(String[] args) 

{

float v1=12.3f;

System.out.println(v1);

double v2=12.3;

        System.out.println(v2);

System.out.println("0.1f == 0.1 is " + (0.1f == 0.1));

        System.out.println("0.1f is actually " + new BigDecimal(0.1f));

        System.out.println("0.1 is actually " + new BigDecimal(0.1));

}

}


write a java program for Narrow Type casting - Implicit Type Casting - Reduced Modulo

 class Con12 

{

public static void main(String[] args) 

{

int a=257;

byte b;;

        double c=323.142;

b=(byte)a;

System.out.println("a value is"+a+"b value is"+b);

b=(byte)c;

  System.out.println("c value is"+c+"b value is"+b);

    


}

}


write a java program for Boolean Variable ?

 class BoolTest {

public static void main(String args[]) {

boolean b;

b = false;

System.out.println("b is " + b);

b = true;

System.out.println("b is " + b);

// a boolean value can control the if statement

if(b) System.out.println("This is executed.");

b = false;

if(b) System.out.println("This is not executed.");

// outcome of a relational operator is a boolean value

System.out.println("10 > 9 is " + (10 > 9));

}   }


write a java program for the Simple Inheritance

 class Emp 

{

int bonus =4000;

void showbonus()

{

System.out.println("bonus is"+bonus);

}

}

class pro extends Emp

{

int sal=25000;

}

class p1 extends pro

{

int tot;

public static void main(String[] args) 

{

p1 p =new p1();

      p.tot=p.bonus+p.sal;

   p.showbonus();

System.out.println("total salary is "+p.tot);

}

};

Write a java program for constructor Chaining

 class Myclass //

{

String name;

int rollno;

Myclass()

{

System.out.println("no paramerterized constructor");

}

Myclass(int b)

{

this();

System.out.println("one paramerterized constructor");

}

Myclass(String a,int b)

{

this(10);

System.out.println("two paramerterized constructor");

this.print();

}

void print()

{

System.out.println("constructor is called print method");

}

public static void main(String args[])

{

    Myclass m1=new Myclass("Ramu",511);

}

};

write a java program for Hybrid inheritance

 class Hybri 

{

int bonus=2000,sal=5000;

}

class chlid1 extends Hybri

{

void showchild1()

{

System.out.println("bonus"+bonus+"sal"+sal);

}

};

class chlid2 extends Hybri

{

void showchild2()

{

System.out.println("bonus"+bonus+"sal"+sal);

}

};

class Driver1

{

public static void main(String[] args) 

{

chlid1 c1=new chlid1();

        chlid2 c2=new chlid2();

c1.showchild1();

c2.showchild2();

}

}


super class private varibales can't access in child

 class Priva  //super class private varibales can't access in child

{

int a=10;

private int b=20;

}

class Use extends Priva //chlid

int c=20;

}

class Dri

{


public static void main(String[] args) 

{

Use p1=new Use();

System.out.println("public variable"+p1.a);

       System.out.println("private variable"+p1.b);

      System.out.println("private variable"+p1.c);

}

}


write a java program for character variable increment in java

 class D1 

{

public static void main(String[] args) 

{

char ch='X';

ch++;

System.out.println(ch);

}

}


write a java program for character variable Decrement in java

 class D1 

{

public static void main(String[] args) 

{

char ch='X';

ch--;

System.out.println(ch);

}

}

Print the average of three numbers given by user by creating a class named 'Average' having a method to calculate and print the average.

 class  Average

{

int a=5,b=4,c=3;

float avg;

void calaverage()

{

avg=(a+b+c)/3;

}

void printavg()

{

System.out.println("Average of three varibales"+avg);

}

public static void main(String[] args) 

{

    Average a1=new Average();

     a1.calaverage();

a1.printavg();

}

}


•Write a Java class Book with following features:

 

Write a Java class Book with following features:
Instance variables :
title for the title of book of type String.
author for the author’s name of type String.
price for the book price of type double.
Instance methods:
public void setTitle(String title): Used to set the title of book.
public void setAuthor(String author): Used to set the name of author of book.
public void setPrice(double price): Used to set the price of book.
public String getTitle(): This method returns the title of book.
public String getAuthor(): This method returns the author’s name of book.
Public double getPrice( ): Used to set the price of book.
class Book 
{
String title,author;
double price;
void setTitle(String t)
{
title=t;
}
void setAuthor(String a)
{
author=a;
}
void setPrice(double p)
{
price=p;
}
String getTitle()
{
return title;
}
String getAuthor()
{
return author;
}
double getPrice()
{
return price;
}
public static void main(String[] args) 
{
Book b1=new Book();
b1.setTitle("introduction to java");
b1.setAuthor("Dietiel");
b1.setPrice(550.60);
System.out.println("Book Title   "+ b1.getTitle()+"Author   "+b1.getAuthor()+"Price   "+b1.getPrice());
}
}

Write a Java class Author with following features:

 

Write a Java class Author with following features:
Instance variables :
firstName for the author’s first name of type String.
lastName for the author’s last name of type String.
Instance methods:
public void setFirstName (String firstName): Used to set the first name of author.
public void setLastName (String lastName): Used to set the last name of author.
public String getFirstName(): This method returns the first name of the author.
public String getLastName(): This method returns the last name of the author.


class Author 

{

String firstname,lastname;

void setfirstname(String first)

{

firstname=first;

}

void setlastname(String last)

{

lastname=last;

}

String getfirstname()

{

return firstname;

}

String getlastname()

{

return lastname;

}

public static void main(String[] args) 

{

Author a1=new Author ();

a1.setfirstname("john");

a1.setlastname("k");

System.out.println("FirstName is"+a1.getfirstname()+"Last Nameis"+a1.getlastname());

}

}



Tuesday, May 12, 2020

Write a Java Program to Login Form to Connect Database validate username and password

Database Connecting Program

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class dbConnect {

        Connection conn = null;
        
        String host = "jdbc:mysql://localhost:3306/";
        String dbName = "cse1";
        String username = "root";
        String password = "vamsi";
        String driver = "com.mysql.jdbc.Driver";
        
        Connection con;
        PreparedStatement pst;
        ResultSet rs;
        
        dbConnect()
        {
                try{
                        Class.forName(driver);
                        con = DriverManager.getConnection(host + dbName, username, password);
                        pst = con.prepareStatement("SELECT * FROM login WHERE uname = ? and pwd = ?");
                }
                catch(Exception e)
                {
                        e.printStackTrace();    
                }
        }
        
        public Boolean vertify(String uname, String pwd)
        {
                try{
                        pst.setString(1, uname); //this replace the 1st "?" in the query for username
                        pst.setString(2, pwd);   //this replace the 2nd "?" in the query for password
                        
                        //execute the prepared statement
                        rs = pst.executeQuery();
                        if(rs.next())
                        {
                                //TRUE iff query founds any corresponding data
                                return true;
                        }
                        else
                        {
                                return false;
                        }                       
                }catch (Exception e)
                {
                        //TODO Auto-generate catch block
                        System.out.println("error while validating" + e);
                        return false;
                }
        }
}
_______________________________________________________________________________
Graphical User Interface

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

public class logInMenu1{
        Frame frame1 = new Frame("Log-in Form");
        
        Button SUBMIT;
        
        Label lUsername, lPassword;
        TextField username, password;
        
        dbConnect dbC=new dbConnect();
        
        public logInMenu1()
        {
                createAndShowGUI();
        }
        
        void login()
        {
                lUsername = new Label("Username");
                username = new TextField(15);
                
                lPassword = new Label("Password");
                password = new TextField(15);
                
                SUBMIT = new Button("SUBMIT");
                
                Panel panel = new Panel(new GridLayout(3,1));
                panel.setSize(200,50);
                panel.add(lUsername);
                panel.add(username);
                panel.add(lPassword);
                panel.add(password);
                panel.add(SUBMIT);
                frame1.add(panel, BorderLayout.CENTER);

                SUBMIT.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent e)
                        {
                                
                                String uname = username.getText();

                                String pwd = password.getText();
                                
                                System.out.println("value1: " + uname);
                                System.out.println("value2: " + pwd);
                                
                                if(dbC.vertify(uname, pwd))
                                {
                                        //a pop-up box
                                        JOptionPane.showMessageDialog(null, "You have logged in successfully", "Success",
                                                        JOptionPane.INFORMATION_MESSAGE);
                                }
                                else
                                {
                                        //a pop-up box
                                        JOptionPane.showMessageDialog(null, "Login failed!", "Failed!",
                                                        JOptionPane.INFORMATION_MESSAGE);
                                }
                        }
                });
        }
        
        void createAndShowGUI(){
                 frame1.setSize(400, 150);
                frame1.setVisible(true);
                frame1.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                    }
                });
                login();
        }
        
        public static void main(String[] args)
        {
          new logInMenu1();
        }

}

write a java program to store data emp table

import java.sql.*;  
class MysqlCon1{  
public static void main(String args[]){  
try{  
Class.forName("com.mysql.jdbc.Driver");  
Connection con=DriverManager.getConnection(  
"jdbc:mysql://localhost:3306/cse1","root","");  
Statement stmt=con.createStatement();  
int result=stmt.executeUpdate("insert into emp values(122,'raghu')");  
System.out.println(result+" records affected");   
con.close();  
}catch(Exception e){ System.out.println(e);}  
}  

write a java program to read data from the emp database display details

import java.sql.*;  
class MysqlCon{  
public static void main(String args[]){  
try{  
Class.forName("com.mysql.jdbc.Driver");  
Connection con=DriverManager.getConnection(  
"jdbc:mysql://localhost:3306/cse1","root","vamsi");  
//here sonoo is database name, root is username and password  
Statement stmt=con.createStatement();  
ResultSet rs=stmt.executeQuery("select * from emp");  
while(rs.next())  
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
con.close();  
}catch(Exception e){ System.out.println(e);}  
}  

write jdbc program to test java connection

import java.sql.*;
public class TestJdbc {
    public static void main(String[] args) {
        Connection conn = null;

        String url = "jdbc:mysql://localhost:3306/";        
        String driver = "com.mysql.jdbc.Driver";

        String dbName = "cse1", userName = "root", 
            password = "vamsi";      

        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url+dbName, userName, password);
            System.out.println("Connected to the database");
            conn.close();
            System.out.println("Disconnected from database");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Monday, May 11, 2020

write java program using Grid Bag Layout

import java.awt.Button;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
public class AWTGridBagLayoutDemo extends JFrame {
public static void main(String[] args) {
AWTGridBagLayoutDemo gbld = new AWTGridBagLayoutDemo();
}
public AWTGridBagLayoutDemo() {
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbcnt = new GridBagConstraints();
setLayout(gbl);
setTitle("Java Layout Manager: GridBag Layout");
GridBagLayout layout = new GridBagLayout(); //create grid bag layout
this.setLayout(layout);
//below code is customization of grid fashion
gbcnt.fill = GridBagConstraints.HORIZONTAL;
gbcnt.gridx = 1;
gbcnt.gridy = 0;
this.add(new Button("Smart Phone"), gbcnt);
gbcnt.gridx = 2;
gbcnt.gridy = 0;
this.add(new Button("Laptop"), gbcnt);
gbcnt.fill = GridBagConstraints.HORIZONTAL;
gbcnt.ipady = 20;
gbcnt.gridx = 1;
gbcnt.gridy = 1;
this.add(new Button("Tablet"), gbcnt);
gbcnt.gridx = 2;
gbcnt.gridy = 1;
this.add(new Button("Desktop"), gbcnt);
gbcnt.gridx = 1;
gbcnt.gridy = 2;
gbcnt.fill = GridBagConstraints.HORIZONTAL;
gbcnt.gridwidth = 2;
this.add(new Button("Computer"), gbcnt);
}
}

write a java program to create calculator for addition,subtraction,multiplication,division operations

import java.awt.*;
import java.awt.event.*;
 
class Calculator implements ActionListener
{
//Declaring Objects
Frame f=new Frame();
Label l1=new Label("First Number");
Label l2=new Label("Second Number");
Label l3=new Label("Result");
TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();
Button b1=new Button("Add");
Button b2=new Button("Sub");
Button b3=new Button("Mul");
Button b4=new Button("Div");
Button b5=new Button("Cancel");
Calculator()
{
//Giving Coordinates
l1.setBounds(50,100,100,20);
l2.setBounds(50,140,100,20);
l3.setBounds(50,180,100,20);
t1.setBounds(200,100,100,20);
t2.setBounds(200,140,100,20);
t3.setBounds(200,180,100,20);
b1.setBounds(50,250,50,20);
b2.setBounds(110,250,50,20);
b3.setBounds(170,250,50,20);
b4.setBounds(230,250,50,20);
b5.setBounds(290,250,50,20);
//Adding components to the frame
f.add(l1);
f.add(l2);
f.add(l3);
f.add(t1);
f.add(t2);
f.add(t3);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
f.setLayout(null);
f.setVisible(true);
f.setSize(400,350);
f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            } });
}
public void actionPerformed(ActionEvent e)
{
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());
if(e.getSource()==b1)
{
t3.setText(String.valueOf(n1+n2));
}
if(e.getSource()==b2)
{
t3.setText(String.valueOf(n1-n2));
}
if(e.getSource()==b3)
{
t3.setText(String.valueOf(n1*n2));
}
if(e.getSource()==b4)
{
t3.setText(String.valueOf(n1/n2));
}
if(e.getSource()==b5)
{
System.exit(0);
}

}
public static void main(String...s)
{
new Calculator();
}
}






Sunday, May 10, 2020

write a java program to demonstrate Font Metrics Class

import java.awt.*;
/* <APPLET CODE ="FontMetricsClass.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class FontMetricsClass extends java.applet.Applet
  {
       public void paint(Graphics g)
            {
                String s="Hello Java";
                Font f=new Font("Arial",Font.BOLD+Font.ITALIC,20);
                g.setFont(f);
                FontMetrics met=g.getFontMetrics(f);
                int ascent=met.getAscent();
                int height=met.getHeight();
                int leading=met.getLeading();
                int baseline=leading+ascent;
                for(int i=0;i<10;i++)
                   {
                       g.drawString("Line"+String.valueOf(i),10,baseline);
                       baseline+=height;
                   }
           }
  }    
   

write a java program to create Dialog using awt

import java.awt.*;  
import java.awt.event.*;  
public class DialogExample {  
    private static Dialog d;  
    DialogExample() {  
        Frame f= new Frame();  
        d = new Dialog(f , "Dialog Example", true);  
        d.setLayout( new FlowLayout() );  
        Button b = new Button ("OK");  
        b.addActionListener ( new ActionListener()  
        {  
            public void actionPerformed( ActionEvent e )  
            {  
                DialogExample.d.setVisible(false);  
            }  
        });  
        d.add( new Label ("Click button to continue."));  
        d.add(b);  
        d.setSize(300,300);    
        d.setVisible(true);  
d.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            } });
    }  
    public static void main(String args[])  
    {  
        new DialogExample();  
    }  
}  

write a java program to create popupmenu

import java.awt.*;  
import java.awt.event.*;  
class PopupMenuExample  
{  
     PopupMenuExample(){  
      final  Frame f= new Frame("PopupMenu Example");  
        final PopupMenu popupmenu = new PopupMenu("Edit");   
         MenuItem cut = new MenuItem("Cut");  
         cut.setActionCommand("Cut");  
         MenuItem copy = new MenuItem("Copy");  
         copy.setActionCommand("Copy");  
         MenuItem paste = new MenuItem("Paste");  
         paste.setActionCommand("Paste");      
         popupmenu.add(cut);  
         popupmenu.add(copy);  
         popupmenu.add(paste);        
         f.addMouseListener(new MouseAdapter() {  
            public void mouseClicked(MouseEvent e) {              
                popupmenu.show(f , e.getX(), e.getY());  
            }                 
         });  
         f.add(popupmenu);   
         f.setSize(400,400);  
         f.setLayout(null);  
         f.setVisible(true);  
f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            } });
     }  
public static void main(String args[])  
{  
        new PopupMenuExample();  
}  
}  

write a java program for creating Menu using awt

import java.awt.*;  
import java.awt.event.*;
class MenuExample  
{  
     MenuExample(){  
         Frame f= new Frame("Menu and MenuItem Example");  
         MenuBar mb=new MenuBar();  
         Menu menu=new Menu("Menu");  
         Menu submenu=new Menu("Sub Menu");  
         MenuItem i1=new MenuItem("Item 1");  
         MenuItem i2=new MenuItem("Item 2");  
         MenuItem i3=new MenuItem("Item 3");  
         MenuItem i4=new MenuItem("Item 4");  
         MenuItem i5=new MenuItem("Item 5");  
         menu.add(i1);  
         menu.add(i2);  
         menu.add(i3);  
         submenu.add(i4);  
         submenu.add(i5);  
         menu.add(submenu);  
         mb.add(menu);  
         f.setMenuBar(mb);  
         f.setSize(400,400);  
         f.setLayout(null);  
         f.setVisible(true);  
f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            } });
}  
public static void main(String args[])  
{  
new MenuExample();  
}  
}  

Wednesday, May 6, 2020

write a java program to handle Mouse Events Using Mouse Adapter

import java.awt.*;  
import java.awt.event.*;  
public class MouseAdapterExample extends MouseAdapter{  
    Frame f;  
    MouseAdapterExample(){  
        f=new Frame("Mouse Adapter");  
        f.addMouseListener(this);  
          
        f.setSize(300,300);  
        f.setLayout(null);  
        f.setVisible(true);  
f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            } });
    }  
    public void mouseClicked(MouseEvent e) {  
        Graphics g=f.getGraphics();  
        g.setColor(Color.BLUE);  
        g.fillOval(e.getX(),e.getY(),30,30);  
    }  
      
public static void main(String[] args) {  
    new MouseAdapterExample();  
}  
}  

write a java program to handle KeyEvents using KeyAdapter

import java.awt.*;  
import java.awt.event.*;  
public class KeyAdapterExample extends KeyAdapter{  
    Label l;  
    TextArea area;  
    Frame f;  
    KeyAdapterExample(){  
        f=new Frame("Key Adapter");  
        l=new Label();  
        l.setBounds(20,50,200,20);  
        area=new TextArea();  
        area.setBounds(20,80,300, 300);  
        area.addKeyListener(this);  
          
        f.add(l);f.add(area);  
        f.setSize(400,400);  
        f.setLayout(null);  
        f.setVisible(true);  
f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            } });
    }  
    public void keyReleased(KeyEvent e) {  
        l.setText("Key Released");  
    }  
  
    public static void main(String[] args) {  
        new KeyAdapterExample();  
    }  
}  

write a java program to handle mouse events using Mouse Listener

import java.awt.*;  
import java.awt.event.*;  
public class MouseListenerExample extends Frame implements MouseListener{  
    Label l;  
    MouseListenerExample(){  
        addMouseListener(this);  
          
        l=new Label();  
        l.setBounds(20,50,100,20);  
        add(l);  
        setSize(300,300);  
        setLayout(null);  
        setVisible(true); 
addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            } });
    }  
    public void mouseClicked(MouseEvent e) {  
        l.setText("Mouse Clicked");  
    }  
    public void mouseEntered(MouseEvent e) {  
        l.setText("Mouse Entered");  
    }  
    public void mouseExited(MouseEvent e) {  
        l.setText("Mouse Exited");  
    }  
    public void mousePressed(MouseEvent e) {  
        l.setText("Mouse Pressed");  
    }  
    public void mouseReleased(MouseEvent e) {  
        l.setText("Mouse Released");  
    }  
public static void main(String[] args) {  
    new MouseListenerExample();  
}  
}  

write a java program to handle key press events using Key Listener

import java.awt.*;  
import java.awt.event.*;  
public class KeyListenerExample extends Frame implements KeyListener{  
    Label l;  
    TextArea area;  
    KeyListenerExample(){  
          
        l=new Label();  
        l.setBounds(20,50,100,20);  
        area=new TextArea();  
        area.setBounds(20,80,300, 300);  
        area.addKeyListener(this);  
        add(l);
add(area);  
        setSize(400,400);  
        setLayout(null);  
        setVisible(true);  
addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            } });
    }  
    public void keyPressed(KeyEvent e) {  
        l.setText("Key Pressed");  
    }  
 public void keyReleased(KeyEvent e) {  
   l.setText("Key Released");  
   }  
    public void keyTyped(KeyEvent e) {  
        l.setText("Key Typed");  
    }  
  
    public static void main(String[] args) {  
        new KeyListenerExample();  
    }  
}