我的程序定义了一个panel,每次在鼠标移进这个panel的时候,鼠标上就回显示一个小球,移出的时候小球消失。但是我的程序运行结果什么都不显示,我觉得我的思路没问题,但是在实现的时候可能有问题,请大家看一下程序,多多指教,谢谢
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
import java.util.*;
/*
* When the mouse move to the panel,there will be a
* ball appear at the same time.when it moves out of the panel
* the ball disappear.
*/
public class MousewithBall {
public static void main(String[] args){
JFrame frame=new DrawBallFrame();
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class DrawBallFrame extends JFrame{
public DrawBallFrame(){
panel=new DrawBallPanel();
add(panel);
}
private DrawBallPanel panel;
}
class DrawBallPanel extends JPanel{
private ArrayList <Point> points;
public DrawBallPanel(){
points=new ArrayList <Point> ();
//gets tje bounds of the panel
r= this.getBounds();
//add the listener
addMouseMotionListener(new MouseMotionHandler());
}
public void paintComponent(Graphics g){
super.paintComponents(g);
Graphics2D g2=(Graphics2D)g;
for(Point r:points){
double x=r.getX();
double y=r.getY();
//draw the ball
g2.fillOval((int)x,(int)y,15,15);
}
}
public Point returnPoint(int x,int y){
return new Point(x,y);
}
public void add(Point p){
points.add(p);
}
private Rectangle r;
private class MouseMotionHandler extends MouseMotionAdapter{
public void mouseMoved(MouseEvent e){
int x=e.getX();
int y=e.getY();
if(r.contains(x,y))
{returnPoint(x,y);
repaint();}
}
}
}
------解决方案--------------------
private Rectangle r;
这个没有初始化值