Friday, 20 May 2011

detecting host name using java

import java.net.*;
import java.io.*;

public class GetHostName{
 public static void main(String [] args) {
   try {
        InetAddress addr = InetAddress.getLocalHost();
        byte[] ipAddr = addr.getAddress();
        String hostname = addr.getHostName();
        System.out.println("hostname="+hostname);
    } catch (UnknownHostException e) {
    }

    }
}
out put
host name=system-1

creating a file using java

import java.io.*;

public class Write_File {
    public static void main(String args[]) throws IOException {
        File flt = new File("codingdiary.doc");
        FileWriter wrt = new FileWriter(flt);

        CharSequence cq = "welcome to future";

        wrt.append(cq);
        wrt.flush();
        System.out.println("Output is generated in a file codingdiary.doc");

        flt = new File("sateesh.txt");
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new FileWriter(flt)));
        out.print("Welcome to java programming");
        out.flush();
        System.out.println("Output is generated in a file sateesh.txt");

        flt = new File("rachel_weisz");
        flt.createNewFile();
        System.out.println("An unknown extension file rachel_weisz is created");

        CharArrayWriter ch = new CharArrayWriter();
        cq = "newstrackindia.com";
        ch.append(cq);
        ch.flush();
        System.out.println(ch.toString());

    }
}


text editor using java

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

public class notepro extends JFrame implements ActionListener
{
    MenuBar mbar;
    Menu file,edit,format,font,font1,font2;
    MenuItem item1,item2,item3,item4;
    MenuItem item5,item6,item7,item8,item9,item10;
    MenuItem fname1,fname2,fname3,fname4;
    MenuItem fstyle1,fstyle2,fstyle3,fstyle4;
    MenuItem fsize1,fsize2,fsize3,fsize4;

    JPanel mainpanel;
    TextArea text;

    Font f;
    String months[]={
        "Jan","Feb","Mar","Apr",
        "May","Jun","Jul","Aug",
        "Sep","Oct","Nov","Dec"};

    GregorianCalendar  gcalendar;


    String command=" ";
    String str=" ";

    String str1=" ",str2=" ",str3=" ";
    String str4=" ";

    String str6=" ";
    String str7=" ",str8=" ",str9=" ";

    int len1;

    int i=0;
    int pos1;
    int len;

    public notepro(String str)
    {

    super(str);

    mainpanel=new JPanel();
    mainpanel=(JPanel)getContentPane();
    mainpanel.setLayout(new FlowLayout());



    mbar=new MenuBar();
    setMenuBar(mbar);

    file=new Menu("File");
    edit=new Menu("Edit");
    format=new Menu("Format");
    font=new Menu("Font");
    font1=new Menu("Font Style");
    font2=new Menu("Size");

    file.add(item1=new MenuItem("New..."));
    file.add(item2=new MenuItem("Open"));
    file.add(item3=new MenuItem("Save As..."));
    file.add(item4=new MenuItem("Exit"));
    mbar.add(file);


    edit.add(item5=new MenuItem("Cut"));
    edit.add(item6=new MenuItem("Copy"));
    edit.add(item7=new MenuItem("Paste"));
    edit.add(item8=new MenuItem("Delete"));
    edit.add(item10=new MenuItem("Select All"));
    edit.add(item9=new MenuItem("Time/Date"));
    mbar.add(edit);

    format.add(font);
    format.add(font1);
    format.add(font2);

    font.add(fname1=new MenuItem("Courier"));
    font.add(fname2=new MenuItem("Sans Serif"));
    font.add(fname3=new MenuItem("Monospaced"));
    font.add(fname4=new MenuItem("Symbol"));

    font1.add(fstyle1=new MenuItem("Regular"));
    font1.add(fstyle2=new MenuItem("Bold"));
    font1.add(fstyle3=new MenuItem("Italic"));
    font1.add(fstyle4=new MenuItem("Bold Italic"));

    font2.add(fsize1=new MenuItem("12"));
    font2.add(fsize2=new MenuItem("14"));
    font2.add(fsize3=new MenuItem("18"));
    font2.add(fsize4=new MenuItem("20"));

    mbar.add(format);



    item1.addActionListener(this);
    item2.addActionListener(this);
    item3.addActionListener(this);
    item4.addActionListener(this);
    item5.addActionListener(this);
    item6.addActionListener(this);
    item7.addActionListener(this);
    item8.addActionListener(this);
    item9.addActionListener(this);
    item10.addActionListener(this);
    fname1.addActionListener(this);
    fname2.addActionListener(this);
    fname3.addActionListener(this);
    fname4.addActionListener(this);
    fstyle1.addActionListener(this);
    fstyle2.addActionListener(this);
    fstyle3.addActionListener(this);
    fstyle4.addActionListener(this);
    fsize1.addActionListener(this);
    fsize2.addActionListener(this);
    fsize3.addActionListener(this);
    fsize4.addActionListener(this);


    text=new TextArea(26,60);
    mainpanel.add(text);

    f=new Font("Monotype Corsiva",Font.PLAIN,15);
    text.setFont(f);
    }




    public void actionPerformed(ActionEvent ae)
    {


        command=(String)ae.getActionCommand();

        if(command.equals("New..."))
        {
        dispose();
        notepro note1 = new notepro("Untitled-Notepad");
        note1.setSize(500,500);
        note1.setVisible(true);
        }

        try
        {

        if(command.equals("Open"))
        {

        str4=" ";
        FileDialog dialog=new FileDialog(this,"Open");
        dialog.setVisible(true);

        str1=dialog.getDirectory();
        str2=dialog.getFile();
        str3=str1+str2;
        File f=new File(str3);
        FileInputStream fobj=new FileInputStream(f);
        len=(int)f.length();
        for(int j=0;j<len;j++)
        {
            char str5=(char)fobj.read();
            str4=str4 + str5;

        }

        text.setText(str4);

        }
        }
        catch(IOException e)
        {}


        try
        {

        if(command.equals("Save As..."))
        {
        FileDialog dialog1=new FileDialog(this,"Save As",FileDialog.SAVE);
        dialog1.setVisible(true);

        str7=dialog1.getDirectory();
        str8=dialog1.getFile();
        str9=str7+str8;


        str6=text.getText();
        len1=str6.length();
        byte buf[]=str6.getBytes();

        File f1=new File(str9);
        FileOutputStream fobj1=new FileOutputStream(f1);
        for(int k=0;k<len1;k++)
        {
        fobj1.write(buf[k]);
        }
        fobj1.close();
        }

        this.setTitle(str8);

        }
        catch(IOException e){}



        if(command.equals("Exit"))
        {
        System.exit(0);
        }

        if(command.equals("Cut"))
        {
        str=text.getSelectedText();
        i=text.getText().indexOf(str);
        text.replaceRange(" ",i,i+str.length());
        }

        if(command.equals("Copy"))
        {
        str=text.getSelectedText();
        }

        if(command.equals("Paste"))
        {
        pos1=text.getCaretPosition();
        text.insert(str,pos1);
        }
        if(command.equals("Delete"))
        {
        String msg=text.getSelectedText();
        i=text.getText().indexOf(msg);
        text.replaceRange(" ",i,i+msg.length());
        }
        if(command.equals("Time/Date"))
        {
        gcalendar=new GregorianCalendar();
        String h=String.valueOf(gcalendar.get(Calendar.HOUR));
        String m=String.valueOf(gcalendar.get(Calendar.MINUTE));
        String s=String.valueOf(gcalendar.get(Calendar.SECOND));
        String date=String.valueOf(gcalendar.get(Calendar.DATE));
        String mon=months[gcalendar.get(Calendar.MONTH)];
        String year=String.valueOf(gcalendar.get(Calendar.YEAR));
        String hms="Time"+" - "+h+":"+m+":"+s+"  Date"+"  -  "+date+" "+mon+" "+year;
        int loc=text.getCaretPosition();
        text.insert(hms,loc);
        }
        if(command.equals("Courier"))
        {

        String fontName=f.getName();
        String fontFamily=f.getFamily();
        int fontSize=f.getSize();
        int fontStyle=f.getStyle();

        f=new Font("Courier",fontStyle,fontSize);
        text.setFont(f);
        }
        if(command.equals("Sans Serif"))
        {
        String fontName=f.getName();
        String fontFamily=f.getFamily();
        int fontSize=f.getSize();
        int fontStyle=f.getStyle();

        f=new Font("Sans Serif",fontStyle,fontSize);
        text.setFont(f);
        }
        if(command.equals("Monospaced"))
        {
        String fontName=f.getName();
        String fontFamily=f.getFamily();
        int fontSize=f.getSize();
        int fontStyle=f.getStyle();

        f=new Font("Monospaced",fontStyle,fontSize);
        text.setFont(f);
        }

        if(command.equals("Symbol"))
        {
        String fontName=f.getName();
        String fontFamily=f.getFamily();
        int fontSize=f.getSize();
        int fontStyle=f.getStyle();

        f=new Font("Symbol",fontStyle,fontSize);
        text.setFont(f);
        System.out.println(f.getFamily());
        }
        if(command.equals("Regular"))
        {
        String fontName=f.getName();
        String fontFamily=f.getFamily();
        int fontSize=f.getSize();
        int fontStyle=f.getStyle();

        f=new Font(fontName,Font.PLAIN,fontSize);
        text.setFont(f);
        }
        if(command.equals("Bold"))
        {
        String fontName=f.getName();
        String fontFamily=f.getFamily();
        int fontSize=f.getSize();
        int fontStyle=f.getStyle();

        f=new Font(fontName,Font.BOLD,fontSize);
        text.setFont(f);
        }
        if(command.equals("Italic"))
        {
        String fontName=f.getName();
        String fontFamily=f.getFamily();
        int fontSize=f.getSize();
        int fontStyle=f.getStyle();

        f=new Font(fontName,Font.ITALIC,fontSize);
        text.setFont(f);
        }
        if(command.equals("Bold Italic"))
        {
        String fontName=f.getName();
        String fontFamily=f.getFamily();
        int fontSize=f.getSize();
        int fontStyle=f.getStyle();

        f=new Font(fontName,Font.BOLD|Font.ITALIC,fontSize);
        text.setFont(f);
        }

        if(command.equals("12"))
        {
        String fontName=f.getName();
        String fontFamily=f.getFamily();
        int fontSize=f.getSize();
        int fontStyle=f.getStyle();

        f=new Font(fontName,fontStyle,12);
        text.setFont(f);
        }

        if(command.equals("14"))
        {
        String fontName=f.getName();
        String fontFamily=f.getFamily();
        int fontSize=f.getSize();
        int fontStyle=f.getStyle();

        f=new Font(fontName,fontStyle,14);
        text.setFont(f);
        }
        if(command.equals("18"))
        {
        String fontName=f.getName();
        String fontFamily=f.getFamily();
        int fontSize=f.getSize();
        int fontStyle=f.getStyle();

        f=new Font(fontName,fontStyle,18);
        text.setFont(f);
        }
        if(command.equals("20"))
        {
        String fontName=f.getName();
        String fontFamily=f.getFamily();
        int fontSize=f.getSize();
        int fontStyle=f.getStyle();

        f=new Font(fontName,fontStyle,20);
        text.setFont(f);
        }
        if(command.equals("Select All"))
        {
        String strText=text.getText();
        int strLen=strText.length();
        text.select(0,strLen);
        }


    }



    public static void main(String args[])
    {
    notepro note = new notepro("Untitled-Notepad");
    note.setSize(500,500);
    note.setVisible(true);
    }
}

java program for employee informaion

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

class EmployeeInformation {
JFrame f;
JPanel p1,p2,p3;
JTabbedPane tp;
ImageIcon btnimg1,btnimg2;
JLabel l1, l2, l3, l4,l5,l6,l7,l8,l9,l10;
JTextField tf1,tf2,tf3,tf4,tf5,tf6,tf7,tf8,tf9,tf10;
JScrollPane sp1;
JButton savebtn,resetbtn,editbtn1,editbtn2,deletebtn ;

EmployeeInformation(){
f=new JFrame("Form");
p1=new JPanel(new GridLayout(5,2));
p2=new JPanel(new GridLayout(5,2));
p3=new JPanel(new GridLayout(2,2));
tp=new JTabbedPane();
l1=new JLabel("Employee ID:");
l2=new JLabel("Employee Name:");
l3=new JLabel("Employee Address:");
l4=new JLabel("Salary:");
l5=new JLabel("Enter Employee ID to delete record:");

l7=new JLabel("Employee ID:");
l8=new JLabel("Employee Name:");
l9=new JLabel("Employee Address:");
l10=new JLabel("Salary:");
tf1=new JTextField(12);
tf2=new JTextField(12);
tf3=new JTextField(12);
tf4=new JTextField(12);
tf5=new JTextField(12);
tf6=new JTextField(12);
tf7=new JTextField(12);
tf8=new JTextField(12);
tf9=new JTextField(12);
tf10=new JTextField(12);
savebtn=new JButton(" Add ");
resetbtn=new JButton(" Reset");
editbtn1=new JButton(" Edit ");
editbtn2=new JButton(" Save");
deletebtn=new JButton("Delete");
p1.add(l1);
p1.add(tf1);
p1.add(l2);
p1.add(tf2);
p1.add(l3);
p1.add(tf3);
p1.add(l4);
p1.add(tf4);
p1.add(savebtn);
p1.add(resetbtn);

p2.add(l7);
p2.add(tf7);
p2.add(l8);
p2.add(tf8);
p2.add(l9);
p2.add(tf9);
p2.add(l10);
p2.add(tf10);
p2.add(editbtn1);
p2.add(editbtn2);

p3.add(l5);
p3.add(tf5);
p3.add(deletebtn);
resetbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
tf1.setText("");
tf2.setText("");
tf3.setText("");
tf4.setText("");
}
});
savebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
String value1=tf1.getText();
String value2=tf2.getText();
String value3=tf3.getText();
String value4=tf4.getText();
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "test";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
System.out.println(value1+value2+value3+value4);
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, user, pass);
PreparedStatement st=con.prepareStatement("insert into employee(emp_id,emp_name,emp_address,salary) values(?,?,?,?)");
st.setString(1,value1);
st.setString(2,value2);
st.setString(3,value3);
st.setString(4,value4);
st.executeUpdate();
JOptionPane.showMessageDialog(p1,"Data is successfully inserted into database.");
con.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(p1,"Error in submitting data!");
}
}
});

deletebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){

String value1=tf5.getText();
Connection con = null;
         String url = "jdbc:mysql://localhost:3306/";
         String db = "test";
         String driver = "com.mysql.jdbc.Driver";
         String user = "root";
         String pass = "root";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, user, pass);
PreparedStatement st=con.prepareStatement("DELETE FROM employee WHERE emp_id = ?");
st.setString(1,value1);
st.executeUpdate();
JOptionPane.showMessageDialog(p3,"Record is deleted successfully.");
con.close();
}
catch(Exception exp3)
{
JOptionPane.showMessageDialog(p3,"Error in deleting record.");
}
}
});
editbtn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){

String value=tf7.getText();
Connection con = null;
         String url = "jdbc:mysql://localhost:3306/";
         String db = "test";
         String driver = "com.mysql.jdbc.Driver";
         String user = "root";
         String pass = "root";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, user, pass);
PreparedStatement st=con.prepareStatement("select * from employee where emp_id=?");
st.setString(1,value);
ResultSet res=st.executeQuery();
res.next();
tf7.setText(Integer.toString(res.getInt(1)));
tf8.setText(res.getString(2));
tf9.setText(res.getString(3));
tf10.setText(Integer.toString(res.getInt(4)));
con.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(p2,"Can not edit data");
}
}
});
editbtn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
Connection con = null;
         String url = "jdbc:mysql://localhost:3306/";
         String db = "test";
         String driver = "com.mysql.jdbc.Driver";
         String user = "root";
         String pass = "root";
try
{
int x=JOptionPane.showConfirmDialog(p2,"Confirm edit? All data will be replaced");
if(x==0){
try{
String value1=tf7.getText();
String value2=tf8.getText();
String value3=tf9.getText();
String value4=tf10.getText();

Class.forName(driver);
con = DriverManager.getConnection(url+db, user, pass);;
Statement st=con.createStatement();
st.executeUpdate("update employee set emp_name='"+value2+"', emp_address='"+value3+"', salary='"+value4+"' where emp_id='"+value1+"'");
JOptionPane.showMessageDialog(p2,"Updated successfully");
con.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(p2,"Error in updating edit fields");
}
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(p2,"Error");
}
}
});
}
void dis()
{
f.getContentPane().add(tp);
tp.addTab("Add Record",p1);
tp.addTab("Edit Record",p2);
tp.addTab("Delete Record",p3);

f.setSize(350,180);
f.setVisible(true);
f.setResizable(true);
}
public static void main(String z[]){
EmployeeInformation pro=new EmployeeInformation();
pro.dis();
}
}

java odbc program

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

class Myframe extends JFrame implements ActionListener

 {

   JLabel lno,lname;
   JTextField tno,tname;
   JButton insert,view,update,search,nxt,pre,lst,frt,clr,dlt,exit;

   Connection cn;
   Statement st;
   ResultSet rs;
   Container conpane;


   Myframe()

   {

     lno=new JLabel("Eno");
     lname=new JLabel("Ename");

     tno=new JTextField(6);
     tname=new JTextField(15);

     insert=new JButton("Insert");
     view=new JButton("View");
     nxt=new JButton("Next");
     pre=new JButton("Previous");
     lst=new JButton("Last");
     frt=new JButton("First");
     clr=new JButton("Clear");
     dlt=new JButton("Delete");
     update=new JButton("Update");
     search=new JButton("Search");
     exit=new JButton("Exit");

     conpane = getContentPane();

     JPanel txtPanel,btnPanel;

    txtPanel = new JPanel();
    btnPanel = new JPanel();
     //setLayout(new GridLayout(2,2));
        conpane.add(txtPanel,BorderLayout.NORTH);
        conpane.add(btnPanel,BorderLayout.CENTER);
     txtPanel.add(lno);
     txtPanel.add(tno);

     txtPanel.add(lname);
     txtPanel.add(tname);

     btnPanel.add(insert);
     btnPanel.add(view);
     btnPanel.add(nxt);
     btnPanel.add(pre);
     btnPanel.add(lst);
     btnPanel.add(frt);
     btnPanel.add(clr);
     btnPanel.add(dlt);
     btnPanel.add(update);
     btnPanel.add(search);
     btnPanel.add(exit);

     insert.addActionListener(this);
     view.addActionListener(this);
     nxt.addActionListener(this);
     pre.addActionListener(this);
     lst.addActionListener(this);
     frt.addActionListener(this);
     clr.addActionListener(this);
     dlt.addActionListener(this);
     update.addActionListener(this);
     search.addActionListener(this);
     exit.addActionListener(this);

     try
                     {


                      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");


                      cn=DriverManager.getConnection("jdbc:odbc:employeedsn");
                      st=cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                     rs=st.executeQuery("select * from emp");
                     rs.next();

                }catch(Exception e){}


    }

    public void actionPerformed(ActionEvent a)

    {

    try
      {


         if(a.getSource()==search)
           {

            dbOpen();
             String str = JOptionPane.showInputDialog(null, "Enter empno : ");

            rs=st.executeQuery("select * from emp where eno="+str+"");

            rs.next();
            setText();
           }

         if(a.getSource()==update)
           {

             dbOpen();
             int ueno=Integer.parseInt(tno.getText());
             String uname=(tname.getText());


             st.executeUpdate("UPDATE emp SET eno=" + ueno +",ename='" + tname.getText() + "' WHERE eno="+ ueno +"  ");
             JOptionPane.showMessageDialog(null,"Record is updated");

           }


         if(a.getSource()==dlt)
            {
               int deno=Integer.parseInt(tno.getText());

               st.executeUpdate("DELETE FROM emp WHERE eno="+ deno);
               JOptionPane.showMessageDialog(null,"Record is deleted");

            dbClose();
            dbOpen();

            }



         if(a.getSource()==clr)
           {
                   tno.setText("");
                   tname.setText("");
                   rs.first();
           }


         if(a.getSource()==frt)
          {
                  rs.first();
                  setText();
           }


         if(a.getSource()==lst)
          {
                 rs.last();
                  setText();
            }

         if(a.getSource()==nxt)
          {

             if(!rs.isAfterLast())
              {

                 rs.next();
                 setText();

            }

          else
             {
                  JOptionPane.showMessageDialog(null,"Last Record");
                 rs.previous();
             }

           }


         if(a.getSource()==pre)
          {

            if(!rs.isBeforeFirst())
              {

                 rs.previous();
                 setText();

                 }

           else
            {
                 JOptionPane.showMessageDialog(null,"First Record");
                 rs.first();
            }

          }


        if(a.getSource()==insert)
        {
          int eno=Integer.parseInt(tno.getText());
          String name=(tname.getText());


         st.executeUpdate("insert into emp values("+eno+",'"+name+"')");
         JOptionPane.showMessageDialog(null,"Record inserted into database");

         dbClose();
            dbOpen();

        }



       if(a.getSource()==view)

       {

            rs.next();
            setText();
            dbClose();
            dbOpen();

       }

       if(a.getSource()==exit)
                   {
                       if(JOptionPane.showConfirmDialog(null,"Are You Sure You Want to Exit?","Confirm",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
                       System.exit(0);
                }



    }catch(Exception e)
      {
      }

}



public void dbOpen()
    {
        try
                {


                 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");


                 cn=DriverManager.getConnection("jdbc:odbc:employeedsn");
                 st=cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                rs=st.executeQuery("select * from emp");
                rs.next();

                }catch(Exception e){}
    }


public void setText(){
        try{
            tno.setText(rs.getString(1));
            tname.setText(rs.getString(2));
            }catch(Exception ex){}
            }


            public void dbClose()
                {
                    try{
                        st.close();
                    rs.close();
                    cn.close();
                    }catch(Exception e){}
    }

}

class jdbcdemoframe
{
    public static void  main(String s[])
    {
        Myframe f= new Myframe();
        f.setVisible(true);
        f.setTitle("Employee Information");
        f.setSize(350,250);
    }
}

pop up menu in java

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

public class PopUpMenu{
    JPopupMenu Pmenu;
    JMenuItem menuItem;
    public static void main(String[] args) {
        PopUpMenu p = new PopUpMenu();
    }

    public PopUpMenu(){
        JFrame frame = new JFrame("Creating a Popup Menu");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Pmenu = new JPopupMenu();
        menuItem = new JMenuItem("Cut");
        Pmenu.add(menuItem);
        menuItem = new JMenuItem("Copy");
        Pmenu.add(menuItem);
        menuItem = new JMenuItem("Paste");
        Pmenu.add(menuItem);
        menuItem = new JMenuItem("Delete");
        Pmenu.add(menuItem);
        menuItem = new JMenuItem("Undo");
        Pmenu.add(menuItem);
        menuItem.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){}
            });
        frame.addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent me){
                if(me.isPopupTrigger()){
                    Pmenu.show(me.getComponent(), me.getX(), me.getY());
                }
            }
            public void mouseReleased(MouseEvent Me){
                if(Me.isPopupTrigger()){
                    Pmenu.show(Me.getComponent(), Me.getX(), Me.getY());
                }
            }
        });
        frame.setSize(400,400);
        frame.setVisible(true);
    }
}

Drawing board example code for java

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class DrawingBoardWithMatrix extends JFrame {

  public static void main(String[] args) {
    new DrawingBoardWithMatrix();
  }

  public DrawingBoardWithMatrix() {
    this.setSize(300, 300);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.add(new PaintSurface(), BorderLayout.CENTER);
    this.setVisible(true);
  }

  private class PaintSurface extends JComponent {
    ArrayList<Shape> shapes = new ArrayList<Shape>();

    Point startDrag, endDrag;

    public PaintSurface() {
      this.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
          startDrag = new Point(e.getX(), e.getY());
          endDrag = startDrag;
          repaint();
        }

        public void mouseReleased(MouseEvent e) {
          Shape r = makeRectangle(startDrag.x, startDrag.y, e.getX(), e.getY());
          shapes.add(r);
          startDrag = null;
          endDrag = null;
          repaint();
        }
      });

      this.addMouseMotionListener(new MouseMotionAdapter() {
        public void mouseDragged(MouseEvent e) {
          endDrag = new Point(e.getX(), e.getY());
          repaint();
        }
      });
    }
    private void paintBackground(Graphics2D g2){
      g2.setPaint(Color.LIGHT_GRAY);
      for (int i = 0; i < getSize().width; i += 10) {
        Shape line = new Line2D.Float(i, 0, i, getSize().height);
        g2.draw(line);
      }

      for (int i = 0; i < getSize().height; i += 10) {
        Shape line = new Line2D.Float(0, i, getSize().width, i);
        g2.draw(line);
      }

     
    }
    public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D) g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      paintBackground(g2);
      Color[] colors = { Color.YELLOW, Color.MAGENTA, Color.CYAN , Color.RED, Color.BLUE, Color.PINK};
      int colorIndex = 0;

      g2.setStroke(new BasicStroke(2));
      g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.50f));

      for (Shape s : shapes) {
        g2.setPaint(Color.BLACK);
        g2.draw(s);
        g2.setPaint(colors[(colorIndex++) % 6]);
        g2.fill(s);
      }

      if (startDrag != null && endDrag != null) {
        g2.setPaint(Color.LIGHT_GRAY);
        Shape r = makeRectangle(startDrag.x, startDrag.y, endDrag.x, endDrag.y);
        g2.draw(r);
      }
    }

    private Rectangle2D.Float makeRectangle(int x1, int y1, int x2, int y2) {
      return new Rectangle2D.Float(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1 - x2), Math.abs(y1 - y2));
    }
  }
}

color fading java program

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class ColorFadingAnimation extends JPanel {
  private Rectangle2D rect = new Rectangle2D.Float(20f, 20f, 80f, 50f);

  private float alpha_rectangle = 1f;

  public ColorFadingAnimation() {
    new RectRunnable();
  }

  public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(new Color(50, 50, 50));
    RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2d.setRenderingHints(rh);
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha_rectangle));
    g2d.fill(rect);
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame("Color fading aniamtion");
    frame.add(new ColorFadingAnimation());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(250, 150);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }

  class RectRunnable implements Runnable {
    private Thread runner;

    public RectRunnable() {
      runner = new Thread(this);
      runner.start();
    }

    public void run() {
      while (alpha_rectangle >= 0) {
        repaint();
        alpha_rectangle += -0.01f;

        if (alpha_rectangle < 0) {
          alpha_rectangle = 0;
        }
        try {
          Thread.sleep(50);
        } catch (Exception e) {
        }
      }
    }
  }
}

java menu program

import java.awt.*;
import java.awt.event.*;

public class MainWindow extends Frame {
  public MainWindow() {
    super("Menu Window");
    setSize(400, 400);
    FileMenu fileMenu = new FileMenu(this);
    HelpMenu helpMenu = new HelpMenu(this);
    MenuBar mb = new MenuBar();
    mb.add(fileMenu);
    mb.add(helpMenu);
    setMenuBar(mb);
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        exit();
      }
    });
  }

  public void exit() {
    setVisible(false);
    dispose();
    System.exit(0);
  }

  public static void main(String args[]) {
    MainWindow w = new MainWindow();
    w.setVisible(true);
  }
}

class FileMenu extends Menu implements ActionListener {
  MainWindow mw; 
  public FileMenu(MainWindow m) {
    super("File");
    mw = m;
    MenuItem mi;
    add(mi = new MenuItem("Open"));
    mi.addActionListener(this);
    add(mi = new MenuItem("Close"));
    mi.addActionListener(this);
    add(mi = new MenuItem("Exit"));
    mi.addActionListener(this);
  }

  public void actionPerformed(ActionEvent e) {
    String item = e.getActionCommand();
    if (item.equals("Exit")) 
      mw.exit();
    else 
      System.out.println("Selected FileMenu " + item);
  }
}

class HelpMenu extends Menu implements ActionListener {
  MainWindow mw; 
  public HelpMenu(MainWindow m) {
    super("Help");
    mw = m;
    MenuItem mi;
    add(mi = new MenuItem("Basics"));
    mi.addActionListener(this);
    add(mi = new MenuItem("Advanced"));
    mi.addActionListener(this);
    addSeparator();
    add(mi = new CheckboxMenuItem("Manual"));
    mi.addActionListener(this);
  
    Menu subMenu = new Menu("Miscellaneous");
    subMenu.add(mi = new MenuItem("Help"));
    mi.addActionListener(this);
    subMenu.add(mi = new MenuItem("Other Option"));
    mi.addActionListener(this);
    add(subMenu);
  }
 
  public void actionPerformed(ActionEvent e) {
    String item = e.getActionCommand();
    if (item.equals("Basics"))
      System.out.println("Basics");
    else if (item.equals("Help")) 
      System.out.println("Help");
  }
}

pass value from html to java script

<HTML>
<HEAD>
<TITLE> Pass value from HTML to JavaScript </TITLE>
<script language="JavaScript" >
function hello(name)
{
         alert("Hello! "+name);
}
</script>
</HEAD>
<BODY>
Get Hello Message<br>
<input type="button" onclick='hello("sateesh");' value="Click"/>
</BODY>
</HTML>

Java program to find largest and smallest number in an array

public class FindLargestSmallestNumber {


public static void main(String[] args) {



//array of 10 numbers

int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};



//assign first element of an array to largest and smallest

int smallest = numbers[0];

int largetst = numbers[0];



for(int i=1; i< numbers.length; i++) { if(numbers[i] > largetst)

largetst = numbers[i];

else if (numbers[i] < smallest) smallest = numbers[i]; } System.out.println("Largest Number is : " + largetst); System.out.println("Smallest Number is : " + smallest); } }

java creating and deleting file automatically

import java.util.*;
import java.io.*;
public class ab extends TimerTask
{
static File file;
public static void main(String[] args ) throws IOException
{
file = new File ("test.dat");
if (! file.exists() )
{
file.createNewFile();
}
System.out.println("File Created");
ab test = new ab();
Timer t = new Timer ();
t.schedule(test, 30*1000L);
try
{
while (file.exists())
{
System.out.print('.');
Thread.sleep(1000);
}
}
catch (InterruptedException ie)
{
System.out.println("Error");
}
System.exit(0);
} //end of main
public void run()
{
file.delete();
}
} //end of public class ab

java welcome program

public class Welcome{

public static void main (String[] args){

String[] greeting = new String[3];

greeting[0] = "Welcome to Core Java";

greeting[1] = " by sateesh";

greeting[2] = "bagadhi";

for (int i=0; i< greeting.length; i++) System.out.println(greeting[i]); } }

java sample program to read data from the key board

import java.io.* ;

class Tut1 {
public static void main(String args[])
{
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream) ;

System.out.println("Welcome To My First Java Program");

try {
System.out.println("Please Enter In Your First Name: ");
String firstName = bufRead.readLine();

System.out.println("Please Enter In The Year You Were Born: ");
String bornYear = bufRead.readLine();

System.out.println("Please Enter In The Current Year: ");
String thisYear = bufRead.readLine();

int bYear = Integer.parseInt(bornYear);
int tYear = Integer.parseInt(thisYear);

int age = tYear-bYear ;
System.out.println("Hello " + firstName + ".You are " + age + " years old");
}
catch (IOException err) {
System.out.println("Error reading line");
}
catch(NumberFormatException err) {
System.out.println("Error Converting Number");
}
}
}