0

因此,当用户按下我的 JButton 时,它会选择一个随机时间,然后在该时间之后,它会在屏幕上绘制一个椭圆形。但是,就我现在所拥有的而言,它会在按下按钮后立即绘制椭圆形。我希望它在随机时间后出现。

  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();
  }


   }
4

2 回答 2

0

问题是你的逻辑:

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

假设重绘是在设定的坐标处绘制你的椭圆形。

你可能应该这样做:

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.
}

您的 repaint() 方法需要检查 drawOval 设置:

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

  // draw other stuff.
}
于 2010-08-11T05:54:47.870 回答
0

您可以使用 Thread 类中的 sleep 函数使程序等待随机时间。像这样的东西:

try{
Thread.sleep(PopUpTime);
}
catch(Exception e)
{}
// and then compute new points and repaint
于 2010-08-11T06:49:00.740 回答