我希望能够点击其中将改变位置并更改圆的圆。我不知道如何实现鼠标监听器。如何以正确的方式使用鼠标侦听器?
有没有把鼠标监听器在一个新的类中,它会改变x和y的位置,并改变颜色的方法吗?
class drawCircle extends JPanel{
int x = 70;
int y = 70;
int dx = 0;
int dy = 0;
drawCircle(){
addMouseMotionListener(new MouseMotionAdapter(){
public void mousePressed(MouseEvent e){
x = (int)(Math.random()*getWidth() - 70);
y = (int)(Math.random()*getHeight() - 70);
repaint();
}
});
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
int red = (int)(Math.random()*255);
int blue =(int)(Math.random()*255);
int green = (int)(Math.random()*255);
Color color = new Color(red,blue,green);
g.setColor(color);
g.fillOval(x + dx, y +dy, x + dx, y + dy);
g.drawString(" ", x + dx, y + dy);
}
}
+1简单直接。 – camickr