Hello people of stackoverflow, I am currently creating a small game just to learn more about graphics and game creation in Java. However, I am stuck. I'm trying to create a "walking animation" by looping through several small images and then repainting them every image. I'm not sure if there is a particular way to do this or if the images are being repainted so quick that I cannot actually see the "animation". I've broken the game up currently into a Ninja, GameBoard, and Interface class. The interface does the basic GUI creation calls and adds the GameBoard to the GUI. The GameBoard has keyboard listeners and paints the images to the board. The Ninja class has keyboard events and basically is in charge of getting the correct images for the ninja animations.
INTERFACE CLASS
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
public class Interface extends JFrame
{
int height;
int width;
public Interface()
{
height = 600;
width = 600;
initInterface();
}
public Interface(int h, int w)
{
height = h;
width = w;
initInterface();
}
private void initInterface()
{
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.add(new GameBoard());
this.setTitle("Ninja Clash");
this.setSize(height,width);
this.setResizable(false);
}
}
GAMEBOARD CLASS
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class GameBoard extends JPanel
{
public Ninja ninja;
public GameBoard()
{
addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.BLACK);
setDoubleBuffered(true);
ninja = new Ninja();
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(ninja.getImage(), 20,20,null);
}
private class TAdapter extends KeyAdapter
{
public void keyPressed(KeyEvent e)
{
ninja.keyPressed(e, 1);
repaint();
ninja.keyPressed(e, 2);
repaint();
}
public void keyReleased(KeyEvent e)
{
ninja.keyReleased(e);
repaint();
}
}
}
NINJA CLASS
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Ninja
{
Image ninja;
public Ninja()
{
ImageIcon iI = new ImageIcon(this.getClass().getResource("nin1.png"));
ninja = iI.getImage();
}
public Image getImage()
{
return ninja;
}
public void keyPressed(KeyEvent e, int count)
{
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{
if (count == 1)
{
ImageIcon icon = new ImageIcon(this.getClass().getResource("nin2.png"));
ninja = icon.getImage();
}
else
{
ImageIcon icon = new ImageIcon(this.getClass().getResource("nin3.png"));
ninja = icon.getImage();
}
}
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == 39)
{
ImageIcon icon = new ImageIcon(this.getClass().getResource("nin1.png"));
ninja = icon.getImage();
}
}
}