如何在绘制对象之间添加延迟?

时间:2015-05-27 16:08:09

标签: java swing timer actionlistener

所以我有一个让机器人穿过迷宫的程序。当它运行时,它会同时绘制机器人所处的每个位置。我查看了Swing Timers,但我对Action Listeners感到困惑。我在哪里创建ActionListener类?我会把它放在里面?

import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import java.awt.Robot;
import java.awt.AWTException;
import java.util.*;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;





public class RightRobotTest 
{
public static void main (String[] args)
{


    JFrame rightFrame = new JFrame();

    rightFrame.setSize(600, 400);
    rightFrame.setTitle("Right Robot");
    rightFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    RightMazeComponent Rcomponent = new RightMazeComponent();
    rightFrame.add(Rcomponent);

    rightFrame.setLocationRelativeTo(null);

   rightFrame.setVisible(true);

/*   //Timer
     Timer timer = new Timer(5000, actionPerfromed());

     timer.start();
     try{
        Thread.sleep(5000);
        }
    catch (InterruptedException e)
    {
    }
    timer.stop();

*/



}
}

 class RightMazeComponent extends JComponent 
 {
public void paintComponent(Graphics g)

{
    Graphics2D g2 = (Graphics2D) g;

    int[][] outline ={       
                     {1, 1, 1, 1, 1, 1, 1},
                     {0, 0, 1, 1, 1, 0, 0},
                     {1, 0, 1, 1, 0, 0, 1},
                     {1, 0, 1, 1, 0, 1, 1},
                     {1, 0, 0, 0, 0, 1, 1},
                     {1, 1, 0, 1, 0, 0, 1},
                     {1, 1, 0, 1, 0, 1, 1},
                     {1, 1, 1, 1, 1, 1, 1}   };

    MazeBuilder original = new MazeBuilder(outline); 
    original.draw(g2);      

    Rectangle robot2 = new Rectangle (70, 20, 10, 10);
    g2.setColor(Color.RED);
    g2.draw(robot2);


    int rPos = 1;
   int cPos = 0;
    int count2 = 0;

    //Right robot
    boolean rightFinish = true;


      int lastmove = 4;

     int Rchoice = original.MoveRightRobot(rPos, cPos);           


String move = "";
int value = 0;





while(rightFinish)
{
  move = Integer.toString(Rchoice) + Integer.toString(lastmove);
  value = Integer.parseInt(move);
  System.out.println(value);

switch (value)
{
 //down
  case 14:

   case 11:
  case 12:
 case 10:
                                      robot2.translate(0, 50);
                                      g2.draw(robot2);
                                      cPos++;
    Rchoice =    original.MoveRightRobot(rPos,cPos);
                                      lastmove = 0;
                                      count2++;
                                      break;
     //right
     case 24:               
     case 21:
    // case 23:
    case 20:
                                     robot2.translate(50,0);
                                     g2.draw(robot2);
                                     rPos++;
        Rchoice = original.MoveRightRobot(rPos,cPos);
                                     lastmove = 1;
                                     count2++;
                                     break;

   //left
   case 30:
   case 31:
   case 32:
   case 33:
   case 34:
                                     robot2.translate(-50, 0);
                                     g2.draw(robot2);
                                     rPos--;
              Rchoice = original.MoveRightRobot(rPos,cPos);
                                     lastmove = 2;
                                     count2++;
                                     break;

   //up
   case 40:
    case 41:
   case 42:
   case 43:
   case 44:
                                    robot2.translate(0, -50);
                                    g2.draw(robot2);
                                    cPos--;
           Rchoice = original.MoveRightRobot(rPos,cPos);
                                    lastmove = 3;
                                    count2++;
                                    break;

   //special cases

  case 23:                         
                                 if(original.MoveLeft(rPos,cPos) == true)
                                {
                                     robot2.translate(-50, 0);
                                     g2.draw(robot2);
                                     rPos--;
             Rchoice = original.MoveRightRobot(rPos,cPos);
                                     lastmove = 2;
                                     count2++;
                                     break;
                                }


                         else if(original.MoveRight(rPos, cPos) == true)
                                {
                                    robot2.translate(50,0);
                                     g2.draw(robot2);
                                     rPos++;
            Rchoice = original.MoveRightRobot(rPos,cPos);
                                     lastmove = 1;
                                     count2++;
                                     break;
                                }

                                else
                                {
                                    robot2.translate(0, -50);
                                    g2.draw(robot2);
                                    cPos--;
             Rchoice = original.MoveRightRobot(rPos,cPos);
                                    lastmove = 3;
                                    count2++;
                                    break;
                                }


 case 22:                            
                                if(original.MoveDown(rPos, cPos) == true)
                                {
                                     robot2.translate(0, 50);
                                      g2.draw(robot2);
                                      cPos++;
        Rchoice = original.MoveRightRobot(rPos,cPos);
                                      lastmove = 0;
                                      count2++;
                                      break;
                                }

                             else if(original.MoveLeft(rPos, cPos) == true)
                                {
                                     robot2.translate(-50, 0);
                                     g2.draw(robot2);
                                     rPos--;
             Rchoice = original.MoveRightRobot(rPos,cPos);
                                     lastmove = 2;
                                     count2++;
                                     break;
                                 }

                                 else
                                 {
                                     robot2.translate(0, -50);
                                    g2.draw(robot2);
                                    cPos--;
            Rchoice = original.MoveRightRobot(rPos,cPos);
                                    lastmove = 3;
                                    count2++;
                                    break;
                                 }





}//Switch end
if(cPos == 6)
      {
        rightFinish = false;
        System.out.println("RIGHT ROBOT FINISH");
      }
      if(count2 == 25)
      {
            rightFinish = false;
            System.out.println("Right Robot Error.");
      }

    }


}



//BUILDS MAZE AND INCLUDES METHODS THAT CHECK WHAT MOVES ARE FREE
 class MazeBuilder
  {                 
    int[][] outline ={       
                     {1, 1, 1, 1, 1, 1, 1},
                     {0, 0, 1, 1, 1, 0, 0},
                     {1, 0, 1, 1, 0, 0, 1},
                     {1, 0, 1, 1, 0, 1, 1},
                     {1, 0, 0, 0, 0, 1, 1},
                     {1, 1, 0, 1, 0, 0, 1},
                     {1, 1, 0, 1, 0, 1, 1},
                     {1, 1, 1, 1, 1, 1, 1}   };

public  MazeBuilder(int[][] maze)
{
}
public void draw(Graphics2D g2)
{

for (int i = 0; i < 8; i++)
{
    for (int j = 0; j < 7; j++)
    {
        /*if (outline[i][j] == 2)
        {
        Rectangle robot = new Rectangle( i, j*50, 50, 50);
            g2.draw(block);
        }*/

        if (outline[i][j] == 1)
        {
        Rectangle wall = new Rectangle( i*50, j*50, 50, 50);
            g2.draw(wall);
            g2.fill(wall);
        }
    }
}


 }

    int rowpos = 1;
    int colpos = 1;

    boolean down = true;
    boolean up = true;
    boolean left = true;
    boolean right = true;

  public boolean MoveDown(int rowpos, int colpos)
    {
        if(colpos != 6 && outline[rowpos][colpos+1] == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

public boolean MoveUp(int rowpos, int colpos)
{
    if (colpos != 0 && outline[rowpos][colpos - 1] == 0)
        {
            return true;
        }
        else
        {   
            return false;
        }
}

public boolean MoveLeft(int rowpos, int colpos)
{
    if (rowpos != 0 && outline[rowpos - 1][colpos] == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

public boolean MoveRight(int rowpos, int colpos)
{
    if( outline[rowpos + 1][colpos] == 0)
    {
        return true;
    }

    else
    {
        return false;
    }
}   

 //RETURNS VALUE AS TO WHICH DIRECTION ROBOT SHOULD MOVE

 public int MoveRightRobot(int rPos, int cPos)
 {
        boolean down = MoveDown(rPos,cPos);
        boolean up = MoveUp(rPos, cPos);
        boolean left = MoveLeft(rPos, cPos);
        boolean right = MoveRight(rPos, cPos);
        int RC = 7;

        if(right == true)
        {
            RC = 2;
        }

        else if (down == true)
        {
            RC = 1;
        }

        else if (left == true)
        {
            RC = 3;
        }

        else if (up == true)
        {
            RC = 4;
        }
        return RC;
}
}
}

3 个答案:

答案 0 :(得分:2)

在问题中发布了太多代码来研究和调整它。相反,如果你想让你的机器人穿过迷宫,你可以在这里高级概述。

你想要一种循环:

  • 在机器人当前位置画迷宫
  • 计算机器人的下一个位置
  • 将机器人移动到这个新位置,并将迷宫与机器人一起绘制到这个新位置。确保此步骤与第一步之间有足够的延迟,以便人类可以遵循此

想要使用Swing Timer,你走在正确的轨道上。如果你想要每秒更新一次机器人的位置,你会写一个Timer来做:

Timer timer = new Timer( 1000, action -> {
  newPosition = calculateNewPosition();
  setNewPositionOfRobotInMaze( maze, newPosition);
  maze.repaint();
  if ( robotReachedEnd() ){
    ((Timer)action.getSource()).stop();
  }
});
timer.setRepeats( true );
timer.start();

每经过一秒钟,计时器将被触发,而计时器将触发动作监听器。动作监听器中的代码将更新机器人位置并要求迷宫进行重新绘制。

您可能还想阅读Swing concurrency guide,这清楚地解释了为什么您甚至不应该将Thread.sleep与Swing代码结合使用的尝试。

答案 1 :(得分:-1)

Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {

//code here

}, 1000, 0);

计时器scheduleAtFixedRate方法参数: TimerTask - 包含代码; 延迟 - 每次运行之间; startDelay - 如果它应该在启动计时器之前延迟(运行一次)

答案 2 :(得分:-2)

您可以将新的Java 8 lambda表达式用于句柄计时器事件

Timer timer = new Timer(5000, action -> {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
        }
    });