简体   繁体   English

用户按下Jbutton的随机时间后的Java drawOval

[英]Java drawOval after random time when user pressed Jbutton

So when the user presses my JButton, it picks a random time, and after that time, it will draw a oval to the screen. 因此,当用户按下我的JButton时,它将随机选择一个时间,然后在该时间之后,它将在屏幕上绘制一个椭圆形。 However, with what I have now, it draws the oval right after the button is pressed. 但是,对于我现在所拥有的,它在按下按钮后立即绘制了椭圆形。 I want it to appear after a random time. 我希望它在随机时间后出现。

  public void actionPerformed(ActionEvent e) 
  {
  if (e.getSource() == startButton)
  {
      popUpTime = random.nextInt(5000);
      timer = new Timer(popUpTime, this);

      x = random.nextInt(400) + 70;
          y = random.nextInt(400) + 100;

          points[current++] = new Point(x, y);

      timer.start();
      start();

      repaint();
  }


   }

The problem is your logic: 问题是您的逻辑:

if event is start button, then setup oval and timer and call repaint();

assumedly repaint is drawing your oval at the set coordinates. 假定重新绘制是在设置的坐标处绘制椭圆形。

You probably should do something like this: 您可能应该执行以下操作:

if (e.getSource() == startButton)  {
  drawOval = false;  // flag to repaint method to NOT display oval
  // setup timer 
  repaint();  // oval will not be drawn
else {
  // assuming timer has fired (which is a bit weak)
  x = ....;
  y = ...;
  drawOval = true;
  repaint();  // oval will be drawn.
}

Your repaint() method will need to check the drawOval setting: 您的repaint()方法将需要检查drawOval设置:

public void repaint() {
  if (drawOval) {
    // draw it
  } else {
    // may need to clear oval
  }

  // draw other stuff.
}

You could use the sleep function from the Thread class to make the program wait for a random time. 您可以使用Thread类中的sleep函数使程序等待随机时间。 Something like this: 像这样:

try{
Thread.sleep(PopUpTime);
}
catch(Exception e)
{}
// and then compute new points and repaint

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM