import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class AnimationExample implements KeyListener
{
static final int WIDTH = 500;
static final int HEIGHT = 400;
JFrame frame = new JFrame("Threads for Animation");
Drawing draw = new Drawing();
int x, y = (int)(Math.random() * HEIGHT);
int shipX = 200, shipY = 300;
Animation animation = new Animation();
public AnimationExample()
{
frame.add(draw,"Center");
frame.addKeyListener(this);
frame.setLocation(100,200);
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// start the animation (causes the run()method to be called)
animation.start();
}
// called when a key is pressed (if the key is held down it will
// get called repeatedly until another key is pressed
public void keyPressed(KeyEvent e)
{
int typed = e.getKeyCode();
if (typed == KeyEvent.VK_LEFT)
{
shipX -= 10;
// and move over to the right side of the screen
if (shipX < 0)
shipX = WIDTH;
}
else if (typed == KeyEvent.VK_RIGHT)
{
shipX += 10;
if (shipX > WIDTH)
shipX = 0;
}
else if (typed == KeyEvent.VK_UP)
{
shipY -= 10;
if (shipY < 0)
shipY = HEIGHT-100;
}
else if (typed == KeyEvent.VK_DOWN)
{
shipY += 10;
if (shipY > HEIGHT)
shipY = 0 + 100;
}
draw.repaint();
}
// called when a key that was pressed is released
public void keyReleased(KeyEvent e)
{
}
// called when a key is pressed and released immediatley (typed)
public void keyTyped(KeyEvent e)
{
}
public static void main (String[] args)
{
new AnimationExample();
}
class Drawing extends JComponent
{
public void paint(Graphics g)
{
Rectangle r = new Rectangle(shipX, shipY, 50, 100);
g.setColor(Color.black);
g.fillRect(0,0,frame.getWidth(),frame.getHeight());
g.setColor(Color.white);
g.fillOval(shipX+8, shipY+16, 50/6, 100/6);
g.drawOval(shipX, shipY, 50/2, 100/2);
g.drawRect(shipX, shipY + 50, 10, 50);
g.drawRect(shipX+15, shipY+50, 10, 50);
g.setColor(Color.yellow);
g.fillOval(x, y, 10, 10);
// if the bullet hits the ship
if (r.contains(x, y))
{
g.setColor(Color.red);
g.fillRect(shipX, shipY, 50, 105);
// stop the animation
animation.interrupt();
}
}
}
// a class for keeping track of bullet positions (note: it doesn't draw
// the bullets, the Drawing class does that)
class Animation extends Thread
{
// do the animation
public void run()
{
try
{
while (true)
{
sleep(100); // pause for 100 milliseconds
x += 10;
if (x >= WIDTH)
{
x = 30;
y = (int)(Math.random() * HEIGHT);
}
draw.repaint();
}
}
catch (InterruptedException e)
{
// goes here if thread is interupted (gets out of endless animation loop)
}
}
}
}
|