Courtesy from Lachlan:
/* Lachlan McCarty * 11-16-14 * 1.8.0_25 * LM_MovingCar.java * Write a program, YI_MovingCar.java that animates a car * so that it moves across a frame. */ import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JFrame; import javax.swing.JComponent; import javax.swing.Timer; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class LM_MovingCar { private final int FRAME_WIDTH = 450; private final int FRAME_HEIGHT = 100; private final int DELAY = 100; private final LM_MovingCarComponent component = new LM_MovingCarComponent(); private final JFrame frame = new JFrame(); public LM_MovingCar() { frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setTitle("Moving Car"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(component); frame.setVisible(true); ActionListener listener = new LM_TimerListener(); Timer t = new Timer(DELAY, listener); t.start(); } public static void main(String[] args) { new LM_MovingCar(); } private class LM_TimerListener implements ActionListener { public void actionPerformed(ActionEvent event) { component.increaseCoor(1,0); } } private class LM_MovingCarComponent extends JComponent { private final int MULTIPLIER = 2; //ok to change private int xpadding = 10; // ok to change private int ypadding = 10; // ok to change private int CAR_WIDTH = 60*MULTIPLIER; // do not change private int CAR_HEIGHT = 40*MULTIPLIER; // do not change public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // turn on antialiasing so it doesn't look like crap RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHints(rh); g2.drawRect(0*MULTIPLIER+xpadding,10*MULTIPLIER+ypadding,60*MULTIPLIER,10*MULTIPLIER); g2.drawOval(10*MULTIPLIER+xpadding,20*MULTIPLIER+ypadding,10*MULTIPLIER,10*MULTIPLIER); g2.drawOval(40*MULTIPLIER+xpadding,20*MULTIPLIER+ypadding,10*MULTIPLIER,10*MULTIPLIER); g2.drawPolygon(new int[]{10*MULTIPLIER+xpadding,20*MULTIPLIER+xpadding,40*MULTIPLIER+xpadding,50*MULTIPLIER+xpadding}, new int[]{10*MULTIPLIER+ypadding,0*MULTIPLIER+ypadding,0*MULTIPLIER+ypadding,10*MULTIPLIER+ypadding}, 4); } public void increaseCoor(int x, int y) { if (xpadding+x+CAR_WIDTH <= FRAME_WIDTH) xpadding += x; if (ypadding+y+CAR_HEIGHT <= FRAME_HEIGHT) ypadding += y; repaint(); } } }