鼠标控制小球移动


如题,左上角显示鼠标箭头的坐标



import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.Random;
public class Test{
	private Frame f = new Frame("鼠标控制小球");
	//画布大小
	private final int SIZE=400;
	//重写paint()
	private MyCanvas area = new MyCanvas();
	//记录鼠标坐标
	private int x, y;
	private BufferedImage image = new BufferedImage(SIZE,SIZE,BufferedImage.TYPE_INT_RGB);
	private Graphics g = image.getGraphics();
	//小球半径
	private final int r=30;
	private Random rand = new Random();
	
	private void init(){
		area.setPreferredSize(new Dimension(SIZE,SIZE));
		//画白色背景
		g.setColor(Color.white);
		g.fillRect(0, 0, SIZE, SIZE);
		//画两条直线
		g.setColor(Color.black);
		g.drawLine(0,200,SIZE,200);
		g.drawLine(200,0,200,SIZE);
		area.repaint();
		
		area.addMouseMotionListener(new MouseMotionAdapter(){
			public void mouseMoved(MouseEvent e){
				x = e.getX();
				y = e.getY();
				//画白色背景
				g.setColor(Color.white);
				g.fillRect(0, 0, SIZE, SIZE);				
				//画变色小球
				g.setColor(new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)));
				g.fillOval(x-r/2, y-r/2, r,r);
				//画两条直线
				g.setColor(Color.black);
				g.drawLine(0,200,SIZE,200);
				g.drawLine(200,0,200,SIZE);
				//左上角显示鼠标当前坐标
				g.setColor(Color.red);
				g.setFont(new Font("Times", Font.BOLD, 14));
				g.drawString("鼠标箭头的坐标:", 0,20);
				g.drawString("X:"+x, 0,40);
				g.drawString("Y:"+y, 0,60);
				area.repaint();
			}
		});
		
		//关闭窗口
		f.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				System.exit(0);
			}
		});

		f.add(area);
		f.pack();
		f.setVisible(true);
	}
	
	private class MyCanvas extends Canvas{
		public void paint(Graphics g){
			g.drawImage(image, 0, 0, null);
		}
	}

	public static void main(String[] args){
		new Test().init();
	}
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2014-11-14 13:25  包清骏  阅读(329)  评论(0编辑  收藏  举报