The Source for Java Technology Collaboration
User: Password:
Register | Login help    

Search

Online Books:
java.net on MarkMail:


Swing Hack 6: Ghost Mouse

Posted by joshy on December 9, 2003 at 6:36 AM PST

I've been playing with Swing a lot lately for my new series of articles. In my research I came across another interesting class java.awt.Robot. It's a class that can automate the UI, mainly for testing. One particularly cool feature is the mouseMove function. Once I saw this I got evil ideas. :) Imagine rogue java programs that move the mouse cursor to mystify and befuddle the user. Spelling out hideous horrible messages. Redrum! Redrum!. :)

But I'm getting ahead of myself. The code below illustrates the technique. This creates a window with a button. When you click on the button the mouse will swirl around in an ever expanding circle of zombie horror! Or maybe just in a circle. Anyway, it was a good excuse to brush up on my parametric equations. Have fun!


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

public class GhostMouse {
    public static Dimension size;
    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        size = Toolkit.getDefaultToolkit().getScreenSize();

        JFrame frame = new JFrame("Ghost Mouse (tm)!");
        JButton button = new JButton("Gho Ghost");
        frame.getContentPane().add(button);
        button.addActionListener(new CircleListener(robot));

        frame.pack();
        frame.setLocation(
        (int)(size.getWidth()-frame.getWidth())/2,
        (int)(size.getHeight()-frame.getHeight())/2);
        frame.show();
    }
}

class CircleListener implements ActionListener {
    Robot robot;
    public CircleListener(Robot robot) {
        this.robot = robot;
    }

    public void actionPerformed(ActionEvent evt) {
        int originx = (int)GhostMouse.size.getWidth()/2;
        int originy = (int)GhostMouse.size.getHeight()/2;
        double pi = 3.1457;

        for(double theta = 0; theta < 4*pi; theta=theta+0.1) {
            double radius = theta * 20;
            double x = Math.cos(theta) * radius + originx;
            double y = Math.sin(theta) * radius + originy;
            robot.mouseMove((int)x,(int)y);
            try{Thread.sleep(25);} catch (Exception ex) { }
        }
    }

}

Related Topics >> Java Desktop      
Comments
Comments are listed in date ascending order (oldest first)