Search This Blog

Wednesday, June 2, 2010

A Simple Querry Analyser

This is a simple program that can be used in any platform form that supports java to analyse Database querries.......
In windows it can work with any databases provided it is registered through ODBC.In all other platforms it support only mysql.......

The default selection is 'linuxmysql' server do not change that if you are connecting to mysql database.If you want to connect to any other databases in windows follow the instructions in http://www.mundayweb.com/progs/jdbc-odbc-tut.php.

So if you want to add sql jdbc driver goto Datasources-->Add->give a suitable name for the driver(which is later supplied as server to the program)-->select a server and complete the procedures.


So you are done with the ODBC-JDBC driver settings.

The program consists of three source files.File name is given in the top of each source file.Put the three source files togein a folder named  testproj.

One more thing, you need to download a java-mysql connector package and either link it with the project or point the environment variable CLASSPATH to the folder containing the package.


==================================
//file:Main.java

package testproj;

/**
 *
 * @author sreenath
 */
public class Main {

    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        // TODO code application logic here
        DatabaseFront dbprop;
        dbprop=new DatabaseFront();
        dbprop.setVisible(true);

    }

}
==================================
/*
 * DatabaseFront.java
 *
 * Created on 30 May, 2010, 11:54:33 AM
 */

package testproj;



/**
 *
 * @author sreenath
 */
public class DatabaseFront extends javax.swing.JFrame {

    /** Creates new form DatabaseFront */
    public DatabaseFront() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // //GEN-BEGIN:initComponents
    private void initComponents() {

        lserver = new javax.swing.JLabel();
        luname = new javax.swing.JLabel();
        lpassword = new javax.swing.JLabel();
        tserver = new javax.swing.JTextField();
        tuname = new javax.swing.JTextField();
        tpassword = new javax.swing.JPasswordField();
        bok = new javax.swing.JButton();
        breset = new javax.swing.JButton();
        bcancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        lserver.setText("SERVER");

        luname.setText("USERNAME");

        lpassword.setText("PASSWORD");

        tserver.setFont(new java.awt.Font("DejaVu Sans", 1, 13));
        tserver.setText("linuxmysql");
        tserver.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tserverActionPerformed(evt);
            }
        });

        tuname.setFont(new java.awt.Font("DejaVu Sans", 1, 13));

        tpassword.setFont(new java.awt.Font("DejaVu Sans", 1, 13));

        bok.setText("OK");
        bok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bokActionPerformed(evt);
            }
        });

        breset.setText("RESET");
        breset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bresetActionPerformed(evt);
            }
        });

        bcancel.setText("CANCEL");
        bcancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bcancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lserver, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tserver, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(luname, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tuname, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lpassword, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tpassword, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(bok, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(breset, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(bcancel, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(44, 44, 44)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tserver, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lserver, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(luname, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tuname, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lpassword, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tpassword, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bcancel, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(breset, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bok, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }//
//GEN-END:initComponents

    private void bcancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bcancelActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_bcancelActionPerformed

    private void bresetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bresetActionPerformed
        // TODO add your handling code here:
        tserver.setText("");
        tuname.setText("");
        tpassword.setText("");
    }//GEN-LAST:event_bresetActionPerformed

    private void bokActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bokActionPerformed
        // TODO add your handling code here:
        char[] temppassword;
        sserver=tserver.getText();
        suname=tuname.getText();
        temppassword=tpassword.getPassword();
        spassword=String.copyValueOf(temppassword);
        for(int i=0;i
        {
            temppassword[i]=0;
        }
        tpassword.setText("");
        this.dispose();
        new DatabaseConn(sserver,suname,spassword);
      
    }//GEN-LAST:event_bokActionPerformed

    private void tserverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tserverActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tserverActionPerformed

    /**
    * @param args the command line arguments
    */
 

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bcancel;
    private javax.swing.JButton bok;
    private javax.swing.JButton breset;
    private javax.swing.JLabel lpassword;
    private javax.swing.JLabel lserver;
    private javax.swing.JLabel luname;
    private javax.swing.JPasswordField tpassword;
    private javax.swing.JTextField tserver;
    private javax.swing.JTextField tuname;
    // End of variables declaration//GEN-END:variables
    private  String suname;
    private  String spassword;
    private  String sserver;
}

==================================
/*
 * DatabaseConn.java
 *
 * Created on 30 May, 2010, 12:41:58 PM
 */

package testproj;

import java.awt.Color;
import java.awt.PopupMenu;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;
import java.util.Properties;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author sreenath
 */
public class DatabaseConn extends javax.swing.JFrame {

    /** Creates new form DatabaseConn
     * @param server
     * @param uname
     * @param password
     */
    public DatabaseConn(String server,String uname,String password) {
        this.server=server;
        this.uname=uname;
        this.password=password;
        prop=new Properties();
        prop.put("user",uname);
        prop.put("password",password);
        tablebuild=new StringBuilder();

        try
        {
          ResultSet resset=null;
          if(server.equals("linuxmysql"))
          {
            Class.forName(dbClassName);
            conn=DriverManager.getConnection(CONNECTION,prop);
            
          }
          else
          {
              conn=DriverManager.getConnection("JDBC:ODBC:"+server,uname,password);
          }

          
            initComponents();
            tresult.setForeground(Color.red);
            tresult.setBackground(Color.DARK_GRAY);
              tdatabase.addItem("");
              tdatabase.setSelectedIndex(0);
              resset=conn.getMetaData().getCatalogs();
              while(resset.next())
                {
                tdatabase.addItem(resset.getString(1));
                }
          
            this.setVisible(true);
            conn.close();
        }
        catch(Exception ex)
        {
          
            JOptionPane.showMessageDialog(this, ex.getMessage(),"ERROR",JOptionPane.ERROR_MESSAGE);
            this.dispose();
          
        }


    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // //GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tcommand = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        tresult = new javax.swing.JLabel();
        bexec = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        tdatabase = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        tcommand.setColumns(20);
        tcommand.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        tcommand.setRows(5);
        jScrollPane1.setViewportView(tcommand);

        tresult.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        tresult.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        tresult.setOpaque(true);
        jScrollPane2.setViewportView(tresult);

        bexec.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        bexec.setForeground(new java.awt.Color(180, 36, 26));
        bexec.setText("D
O
N
E
!");
        bexec.setOpaque(true);
        bexec.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bexecActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("DejaVu Sans", 1, 13));
        jLabel1.setText("Select DataBase");

        tdatabase.setEditable(true);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(bexec, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6))
                    .addComponent(tdatabase, javax.swing.GroupLayout.Alignment.LEADING, 0, 428, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 473, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 379, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(73, 73, 73)
                        .addComponent(bexec, javax.swing.GroupLayout.DEFAULT_SIZE, 240, Short.MAX_VALUE)
                        .addGap(66, 66, 66)))
                .addGap(18, 18, 18)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tdatabase, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 447, Short.MAX_VALUE)
        );

        pack();
    }//
//GEN-END:initComponents

    private void bexecActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bexecActionPerformed
        // TODO add your handling code here:
         try
        {
          if(server.equals("linuxmysql"))
          {
            Class.forName(dbClassName);
            conn=DriverManager.getConnection(CONNECTION,prop);
          }
          else
          {
              conn=DriverManager.getConnection("JDBC:ODBC:"+server,uname,password);
          }
          try
          {
              if((((String)tdatabase.getSelectedItem())==null)||(((String)tdatabase.getSelectedItem()).equals("")))
              {
                tresult.setText("No Database selected!");
              }
              else
              {

            

              conn.prepareStatement("use "+(String)tdatabase.getSelectedItem()).execute();
              selectedtext=tcommand.getSelectedText();
            
              if((selectedtext==null) || (selectedtext.equals("")))
              {
                  tresult.setText("No querry to execute!");
              }
              else
              {
                tresult.setText("");

                tablebuild.delete(0, tablebuild.length());
                tablebuild.append("
");                 statement=conn.prepareStatement(selectedtext);                                resulttype=statement.execute();                 if(resulttype==true)                 {                 rs=statement.getResultSet();                 rsmeta=rs.getMetaData();                                for(int i=1;i<=rsmeta.getColumnCount();i++)                 {                     tablebuild.append("");                 }                                while(rs.next())                 {                     tablebuild.append(" ");                     tablebuild.append(" ");                     for(int i=1;i<=rsmeta.getColumnCount();i++)                     {                         tablebuild.append("");                     }                 }                 tablebuild.append("
"+rsmeta.getColumnName(i)+"
"+rs.getString(i)+"
");
                tresult.setText(tablebuild.toString());
              

              }
              else
              {
                    tresult.setText("Number Of Rows Affected: "+statement.getUpdateCount());
              }

              }
            

              }

          }
          catch(Exception exc)
          {
              tresult.setText(exc.getMessage());
              conn.close();
            
          }
       }
         catch(Exception ex)
        {

            JOptionPane.showMessageDialog(this, ex.getLocalizedMessage(),"ERROR",JOptionPane.ERROR_MESSAGE);
            this.dispose();
        }
    }//GEN-LAST:event_bexecActionPerformed

    /**
    * @param args the command line arguments
    */
 

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bexec;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea tcommand;
    private javax.swing.JComboBox tdatabase;
    private javax.swing.JLabel tresult;
    // End of variables declaration//GEN-END:variables

    private String server;
    private String uname;
    private String password;
    private Connection conn;
    private Properties prop;
    private static final String CONNECTION ="jdbc:mysql://127.0.0.1";
    private static final String dbClassName = "com.mysql.jdbc.Driver";
    private java.sql.PreparedStatement statement;
    private String selectedtext;
    private ResultSet rs;
    private ResultSetMetaData rsmeta;
    private StringBuilder tablebuild;
    private boolean resulttype;
}==================================

Screen Shots
=========


































Thursday, March 18, 2010

A simple Game!

In this game you have to click on a button with your mouse........But its not that simple as you think..Try..this!!!

Source Code
=========
Set your Project as Shown in the above picture...
on.jpg and off.jpg are given below...........

on.jpg


off.jpg



And code:


package canvasclass;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JWindow;


/**
 *
 * @author sreenath
 */

class button extends JPanel implements MouseListener
{
    boolean mousepos;
    Image img;
    int x,y,width,height;
    button(int locx,int locy,int wid,int heig)
    {
        x=locx;
        y=locy;
        width=wid;
        height=heig;
        mousepos=false;
        this.setSize(width, height);
        this.setLocation(x, y);
        this.setVisible(true);
        this.addMouseListener(this);
    }
    public void paint(Graphics g)
    {
        g.clearRect(x, y, width, height);
        if(mousepos)
        {
           img =new ImageIcon(this.getClass().getResource("off.jpg")).getImage();
        }
        else
        {
           img =new ImageIcon(this.getClass().getResource("on.jpg")).getImage();
        }
        g.drawImage(img,0,0,width,height, null);
    }

    public void mouseClicked(MouseEvent e) {
        System.exit(0);
    }

    public void mousePressed(MouseEvent e) {

    }

    public void mouseReleased(MouseEvent e) {

    }

    public void mouseEntered(MouseEvent e) {
      
        mousepos=true;
        this.repaint();
    }

    public void mouseExited(MouseEvent e) {
        mousepos=false;
        this.repaint();
    }
}
public class Main extends JWindow {
int[] pixels = new int[16 * 16];//Inorder to create invisible cursor
button spot;

    Main() throws AWTException
    {
        GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(this);
        this.setAlwaysOnTop(true);
         this.setVisible(true);
        Robot r=new Robot();
        r.mouseMove(0, 0); //move cursor to top left position of screen
        spot=new button(750,500,75,75);
        this.add(spot);
      
      
        java.awt.Image image = java.awt.Toolkit.getDefaultToolkit().createImage(new java.awt.image.MemoryImageSource(16, 16, pixels, 0, 16));
        Cursor mycursor =Toolkit.getDefaultToolkit().createCustomCursor(image,new Point(0,0), "mycursor");     //transparent cursor
        this.setCursor(mycursor);
      
      
    }

    public static void main(String[] args) throws IOException, AWTException {
        // TODO code application logic here
       new Main();
    }





}

Monday, February 15, 2010

Fun With ROBOT class...

java.awt.Robot is a class which can make the mouse move,trigger key press,trigger key release,take screen capture etc..

I would like to show a simple example with Robot class.....................



import java.awt.AWTException;
import java.awt.FlowLayout;
import java.awt.GraphicsEnvironment;
import java.awt.Robot;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class Main extends JFrame implements MouseListener{

/**
Mouse listener interface is implemented to get mouse events like mouse clicked,pressed,released,entered and exited events.
*/
Robot R;
JButton intel;
JButton notintel;
JLabel lab;
JPanel p;
Main()
{
try {
R = new Robot(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice());
/*
constructor of robot class takes a graphic device as argument.We supply the default screen device
*/
} catch (AWTException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
intel=new JButton("INTELLIGENT");
notintel=new JButton("NOT INTELLIGENT");
lab=new JLabel("SELECT THE OPTION WHICH SUIT YOU");
p=new JPanel(new FlowLayout());
//flow layout is applied to the panel....
this.add(p);
p.add(lab);
p.add(intel);
p.add(notintel);
intel.addMouseListener(this);
//mouse listener registered with buttons
notintel.addMouseListener(this);
this.setAlwaysOnTop(true);
this.setUndecorated(true);//to avoid close bar
this.setSize(300,75);
this.setVisible(true);//to display the JFrame
this.setLocation(500, 500);
}
public static void main(String[] args) {
// TODO code application logic here
new Main();
}

public void mouseClicked(MouseEvent e) {
JButton b=(JButton) e.getSource();
if(b.getText().equals("NOT INTELLIGENT")) {
System.exit(0);
}

}

public void mousePressed(MouseEvent e) {

}

public void mouseReleased(MouseEvent e) {

}

public void mouseEntered(MouseEvent e) {

JButton b=(JButton) e.getSource();
if(b.getText().equals("INTELLIGENT")) {
R.mouseMove(400,400);//mouse is moved using object of robot class
}
}

public void mouseExited(MouseEvent e) {

}

}

Sunday, February 14, 2010

Some Experiments With JAVA For Beginners....




I am Using NETBEANS IDE 6.8 for developing java programs. I am not a professional Java programmer, but just a beginner. So i thought sharing some programs with others will be fun and also their responses will be a great benefit..

First I am going to develop an application which will float on your desktop.



For that Create a new project in the netbeans ide. And then add a new package named "resource" drag and drop the one image(in my case its bella.jpg) to this package...

Then code the Main.java ........
/*import necessary classes*/
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JWindow


public class Main extends JWindow { /*this JWindow is floating on the screen*/

Image ico; /*this holds the image that we want to draw on the screen*/
int width=200; int height=300; /*specify the height and width of the application*/
Dimension d;

Main()
{
ico=new ImageIcon(this.getClass().getResource("/resource/bella.jpg")).getImage();
/* The image is retrieved from the package using this.getClass().getResource(String filename)
so that the application become portable. */


this.setSize(width, height); /*height and width of the JWindow is set.*/
this.setVisible(true);
d= Toolkit.getDefaultToolkit().getScreenSize(); /*a dimension consist of a width & height
Toolkit.getDefaultToolkit().getScreenSize() gives the current screen size*/

d.height=d.height-height; /*to get bottom limit of the screen*/
d.width=d.width-width; /*to get right limit of the screen*/
}
public void paint(Graphics g) /*this paint method is invoked automatically*/
{
if(g!=null)
g.drawImage(ico, 0, 0, width, height,null);
/* Above code draws image ico at (0,0) and scale the image to the width and height specified*/
else
System.out.println("null");
}



public static void main(String[] args) throws InterruptedException {

new Main().flow(0,0,3,3);
/*Initial positon of the window when execution started and the increment factor of both x and
y. It can be chaned to experiment your self */
}


void flow(int x,int y,int incx,int incy) throws InterruptedException {
while(true)
{
x=x+incx; y=y+incy; /*new x and y position for window is calculated*/
this.setLocation(x, y); /*change the location of the window to the new location*/
Thread.sleep(30); /*put a small delay between two adjacent relocation of window
remember 'main' it self starts as a thread. */

if(x<0)>
{
incx=-incx;//reverse the increment value so that window goes to opposite x direction
}
else if(x>d.width)
{
incx=-incx;//reverse the increment value so that window goes to opposite x direction
}
if(y<0)
{
incy=-incy;//reverse the increment value so that window goes to opposite y direction
}
if(y>d.height)
{
incy=-incy;//reverse the increment value so that window goes to opposite y direction
}
}
}

}