我试图在JFrame中不断地围绕鼠标创建一个圆圈,即圆圈围绕着屏幕。要做到这一点,我试图使用repaint()加上一个计时器,以便该圆不断更新其位置。现在,我有程序每秒重绘一次这个圈子。
class MouseJFrame extends JFrame implements MouseListener{
int circleXcenter;
int circleYcenter;
int circleRadius = 25;
boolean show = false;
int delay = 1000;
// listen for and respond to mouse events
public MouseJFrame(){
new Timer(delay, taskPerformer).start();
addMouseListener(this);
}
// paints a circle
public void paint(Graphics g){
super.paint(g);
if(show){
g.drawOval(circleXcenter,circleYcenter,
circleRadius*2,circleRadius*2);
}
}
// getX and getY return the location of the mouse
ActionListener taskPerformer = new ActionListener() {
public void mouseDragged(MouseEvent e){
int xLocation = e.getX();
int yLocation = e.getY();
show = true;
circleXcenter = xLocation-circleRadius;
circleYcenter = yLocation-circleRadius;
repaint();
}
public void mouseMoved(MouseEvent e){
int xLocation = e.getX();
int yLocation = e.getY();
show = true;
circleXcenter = xLocation-circleRadius;
circleYcenter = yLocation-circleRadius;
repaint();
}
};
// class to create MouseJFrame object
public class TestMouseJFrame{
public static void main(String[] a){
MouseJFrame myMouseJFrame = new MouseJFrame ();
myMouseJFrame.setSize(200, 200);
myMouseJFrame.setVisible(true);
}
}但是,我收到有关ActionListener的错误消息。当我尝试解决这个问题时,我会遇到一些其他错误。
我能做些什么来让程序按预期运行?