Search This Blog

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) {

}

}

No comments:

Post a Comment