【问题标题】:Java drawOval after random time when user pressed Jbutton用户按下 Jbutton 后随机时间后的 Java drawOval
【发布时间】:2011-03-28 04:34:47
【问题描述】:

所以当用户按下我的 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();
  }


   }

【问题讨论】:

    标签: java timer jbutton


    【解决方案1】:

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

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

    【讨论】:

    • 这不是一个好主意,您正在阻塞事件调度线程。
    【解决方案2】:

    问题在于你的逻辑:

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

    【讨论】:

    • 评论 // setup timer 是我想让你放的地方。
    猜你喜欢
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    相关资源
    最近更新 更多