I have some code that should be making a player animate, walk, but for some reason it doesn't work. This is my code:
import javax.swing.*;
import java.awt.*;
/**
* Created by evengultvedt on 14.02.14.
*/
import javax.swing.*;
import java.awt.*;
//The board class, which the drawing is on
class Board extends JPanel {
//The image of the player
private Image imgPlayer;
public Board() {
setPreferredSize(new Dimension(400, 400));
setBackground(Color.WHITE);
setVisible(true);
//getting the player.gif file
ImageIcon player = new ImageIcon("player.gif");
//and put in the imgPlayer variable
imgPlayer = player.getImage();
}
public void paintComponent(Graphics graphics) {
Graphics2D graphics2D = (Graphics2D) graphics;
//this doesn't work
graphics2D.drawImage(imgPlayer, 10, 10, 100, 100, null);
//this works
graphics2D.drawString("Test drawing", 120, 120);
}
}
//The JFrame to put the panel on
class AnimatePlayer extends JFrame{
public AnimatePlayer() {
Board board = new Board();
add(board);
setTitle("PlayerTestAnimation");
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new AnimatePlayer();
}
});
}
}
The player.gif file is two pictures in one file, and is saved in the same directory as the java file.
Any help is appreciated, thank you. And I'm sorry for posting only code, but I don't know what more information you need. Please ask if there is something.
"The player.gif file is two pictures in one file, and is saved in the same directory as the java file."
Images should be loaded from the class path. Passing a String to the ImageIcon
loads the image from the file system, in which case your path wont work.
To load from the class path just do this
ImageIcon img = new ImageIcon(getClass().getResource("player.gif"));
As long as your file is in the same package as your .java file as you've described, the image should get built into your class path.
You can also use the ImageIO
class to read the image, which will throw an exception if the image can't be loaded, which will throw a FileNotFoundException
so you know your path is wrong
Image img;
try {
img = ImageIO.read(getClass().getResource("player.gif"));
} catch (IOException ex) {
ex.printStackTrace():
}
Also, you should be calling super.paintComponent(g)
in your paintComponent
method, and as good practice use @Override annotations when necessary
@Override
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Side Note
When painting on JPanel
you should override getPreferredSize()
which will give the JPanel
a preferred size, then you can just pack()
your frame, which you should be doing.
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
Also paintComponent
should be protected
and not public