(Move the arrow keys to move the hero Zil animation)

Java Code

/**
 * 
 * Date  Feb 14, 2006
 * Course : CS15x
 * @author : E.S.Boese  E-id : sugar
 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class KeyEventAnimation extends JApplet implements KeyListener
{
    Image img;
    JLabel zil;
    int x=0, y=0, speed=10;     // x,y coordinates and how many pixels move
    JPanel pane;
    public void init( )
    {
        pane = new JPanel( );
        pane.setLayout( null );
        pane.setBackground( Color.WHITE );
        img = getImage( getCodeBase( ), "zil_walk_front.gif" );
        zil = new JLabel( new ImageIcon(img) );
        zil.setSize( img.getWidth(this), img.getHeight(this) );
        
        addKeyListener(this);
        pane.add( zil, 0, 0 );
        add( pane, BorderLayout.CENTER );
        setFocusable(true);
    }
    public void keyReleased( KeyEvent ke ) { }
    public void keyTyped( KeyEvent ke ) { }
    public void keyPressed( KeyEvent ke )
    {
        int code = ke.getKeyCode( );
        if( code == KeyEvent.VK_UP )
            y -= speed;
        else if ( code == KeyEvent.VK_DOWN )
            y += speed;
        else if ( code == KeyEvent.VK_LEFT )
            x -= speed;
        else if ( code == KeyEvent.VK_RIGHT )
            x += speed;
        zil.setLocation(x,y); 
    }
}

Back to Code Examples
©2006- by E.S.Boese. All Rights Reserved