Animate 1
Cross.java
import java.awt.*; public class Cross { // instance variables - replace the example below with your own private int x, y, size; private Color color; /** * Constructor for objects of class Cross */ public Cross(int x, int y,int size) { this.x=x; this.y=y; this.size=size; this.color = new Color (200,40,60); } public void paint(Graphics g) { g.setColor(color); g.fillRect(x+size/4, y, size/2,size); g.fillRect(x, y+size/4, size, size/2); } }
Animate1.java
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.ArrayList; public class Animate1 extends JApplet implements ActionListener { // instance variables - private Timer timer; private int x; private Cross cross; public void init() { // this is a workaround for a security conflict with some browsers // including some versions of Netscape & Internet Explorer which do // not allow access to the AWT system event queue which JApplets do // on startup to check access. May not be necessary with your browser. JRootPane rootPane = this.getRootPane(); rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE); // provide any initialisation necessary for your JApplet here Timer timer = new Timer(100, this); x=0; timer.start(); cross = new Cross(100, 50, 70); } /** * Paint method for applet. * * @param g the Graphics object for this applet */ public void paint(Graphics g) { // simple text displayed on applet g.setColor(Color.white); g.fillRect(0, 0, 500, 500); g.setColor(Color.black); g.drawString("Animate", 20, 20); g.setColor(Color.blue); g.drawString("x is now "+x, 20, 40); cross.paint(g); } public void actionPerformed(ActionEvent e) { x++; x%=100; repaint(); } }
We will get the object moving by defining a Moveable
interface which needs a move
method. The idea is we might have many
other objects that will be moveable and they can each implement their own move
method to move the way they want to.
- Make the
Moveable
interface - Change
Cross
so that it implements theMoveable
interface so it moves one to the right - Change
Animate
to activate themove
method of thecross
when the timer sends itsActionEvent
- Make a new class (like
Box
) that also implements theMoveable
interface - Make an ArrayList that can contain the different
Moveable
objects so you can make a loop to execute all theirmove
methods