我正在尝试在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的错误消息。当我尝试修复此问题时,我会遇到其他错误。 我该怎么做才能让我的程序按预期运行?