RobotTest2.java

Download source: motion.zip

The robot starts at the center and heads off to explore, only to be stopped at the window edge.

Also see Robot.java


RobotTest2.java

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.geom.*;
import javax.swing.Timer;
import javax.swing.*;


class TestPanel extends JPanel
{
    Timer myTimer;
    int wait, wd, ht;
    Robot  robot;
    double simtime = 0.0;
    JLabel status = new JLabel(" ");

    
    TestPanel()
    {
	robot = new Robot(210,210,24,22,new Color(180,180,255));
	status.setBackground(Color.WHITE);
	status.setOpaque(true);
	status.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
	
    }

    public void showVelocity() {
	status.setText("   " + robot.showVelocity());
    }


    public void update()
    {
	wd = getWidth();
	ht = getHeight();
	double tstep = 0.05;
	double tmin = 1.0;
	robot.updateVelocity();
	double t = robot.intersect_window(wd,ht);
	if (t<tmin) tmin = t;
	if (tmin<=tstep) {
                robot.move(tmin);
		robot.setVelocity(0,0);
		showVelocity();
	}
	else robot.move(tstep);
	simtime += tstep;
	repaint();
    }



    public void paintComponent(Graphics g)
    {
	super.paintComponent(g);
	// draw grid
	g.setColor(Color.RED);
	int n;
	for (n=0; n<9; n++) {
	    g.drawLine(10,10+n*50,410,10+n*50);
	    g.drawLine(10+n*50,10,10+n*50,410);
        }
	robot.draw(g);
    }

    
    public void startAnimation()
    {
	if (myTimer == null)
	{
	    myTimer = new Timer(50,new TimerHandler() );
	    myTimer.start();
	}
	else if (!myTimer.isRunning()) myTimer.restart();
    }

    public void stopAnimation()
    {
	myTimer.stop();
    }

    private class TimerHandler implements ActionListener
    {
	public void actionPerformed(ActionEvent actionevent)
	{
	    update();
	}
    }
}

public class RobotTest2
{
    public static void main(String[] args)
   {
	EventQueue.invokeLater(new Runnable() {
	   public void run()
	   {
	       TestPanel panel = new TestPanel();
	       JFrame frame = new JFrame("Robot Motion");
	       frame.add(panel);
	       frame.add(panel.status,BorderLayout.SOUTH);
	       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	       frame.setSize(440,480);
	       frame.setVisible(true);
	       panel.startAnimation();
	   }
       });
   }
}


Maintained by John Loomis, updated Sat Feb 23 18:46:03 2019