将圆圈移动到随机位置

Move circle to random place

我正在制作这个 java 小程序,它画了一个圆圈,当我用鼠标悬停在圆圈上时,我需要将圆圈移动到一个随机的位置,现在我的小程序在一个随机的地方画圆圈并且当我用鼠标悬停圆圈时改变颜色,但如何让它也移动到随机位置?任何建议将不胜感激。

import java.awt.*; 
import java.applet.*; 
import java.awt.event.*;

public class circle extends Applet implements MouseMotionListener 
{ 
 // The X-coordinate and Y-coordinate of the last Mouse Position. 
     int xpos; 
     int ypos;
//generate random place for circle (in coordinates from 0 to 400
     int x=(int)(Math.random() * 401);
     int y=(int)(Math.random() * 401);
     int width;
     int height;

 // wll be true when the Mouse is in the circle 
     boolean active;

     public void init()  
     {
         width=40;
         height=40;
  // Add the MouseMotionListener to applet 
      addMouseMotionListener(this); 
     }
     public void paint(Graphics g)  
     { 
          if (active){g.setColor(Color.black);} 
          else {g.setColor(Color.blue);}
          g.fillRoundRect(x, y, width, height, 200, 200);

  // This will show the coordinates of the mouse 
  // at the place of the mouse. 
          g.drawString("("+xpos+","+ypos+")",xpos,ypos);

     }

 // This will be excuted whenever the mousemoves in the applet 
     public void mouseMoved(MouseEvent me)  
     {  
          xpos = me.getX(); 
          ypos = me.getY(); 
  // Check if the mouse is in the circle 
         if (xpos > x&& xpos < x+width && ypos > y  
        && ypos < y+height)  
               active = true; 
          else  
              active = false; 
  //show the results of the motion 
          repaint();

     }

     public void mouseDragged(MouseEvent me)  
     { 
     }

  }

只需复制

    x=(int)(Math.random() * 401);
    y=(int)(Math.random() * 401);

在你的 paint() 方法中进入条件

    public void paint(Graphics g)  
     { 
      if (active){ 
          g.setColor(Color.black);
          //here
          x=(int)(Math.random() * 401);
          y=(int)(Math.random() * 401);
      }
      ...

到"refresh"鼠标悬停时的位置


编辑

正如@MadProgrammer 在下面的评论中所写,paint() 方法不是放置应用程序逻辑的最佳位置。更改位置的更好位置是将 active 标志设置为 True.

的侦听器

与其将 x,y... 行粘贴到 pain() 方法中,不如将其粘贴到此处:

    public void mouseMoved(MouseEvent me)  
    {
       ...
       if (xpos > x&& xpos < x+width && ypos > y && ypos < y+height)  
       {
           active = true;
           //here
           x=(int)(Math.random() * 401);
           y=(int)(Math.random() * 401);
       } 
       else  
           ...
    }