Saturday, November 21, 2009

Mouse Follower



In this program a circle moves along with the movement
of the mouse cursor.













Program

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class MouseMotion {
public static void main(String[] args) {
JFrame f = new JFrame("Aim For the Center");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Circle circle = new Circle();
Container panel = circle ;

MouseListen ml = new MouseListen(circle) ;

panel.add(new JLabel("Circle!", SwingConstants.CENTER), BorderLayout.CENTER);
f.getContentPane().add(panel, BorderLayout.CENTER);
f.setSize(500,600) ;
f.addMouseMotionListener(ml);
//f.pack();
f.setVisible(true) ;
}
}
class MouseListen extends MouseMotionAdapter{
Circle circle ;
MouseListen(Circle circle){
this.circle = circle ;
}
public void mouseMoved(MouseEvent me) {
super.mouseMoved(me);
int x = me.getX() ;
int y = me.getY() ;
circle.setPos(x,y) ;
}
}
class Circle extends JPanel{
Shape circle ;
int topX ,topY,width,height ;
public Circle() {
super();
setOpaque(false); // we don't paint all our bits
setLayout(new BorderLayout());
setBorder(BorderFactory.createLineBorder(Color.yellow));
topX = 10 ;//getX() ;
topY = 10 ;//getY() ;
width = 50 ;
height = 50 ;
}

public Dimension getPreferredSize() {
Dimension layoutSize = super.getPreferredSize();
int max = Math.max(layoutSize.width,layoutSize.height);
return new Dimension(max+100,max+100);
}
public void setPos(int xpos,int ypos){
topX = xpos - 30 ;
topY = ypos - 30 ;
repaint() ;
}

public void paintComponent(Graphics g)
{

circle = new Ellipse2D.Float(topX,topY,width,height);
Graphics2D g2d = (Graphics2D) g ;
//initCircle();
g2d.setColor(Color.BLUE) ;
g2d.draw(circle) ;
}

}

No comments:

Post a Comment