I have been coding a game in Java for a while, and I got stuck on Image handling. I don't know why but it worked in all my previous games. Do I have it right? Thanks for advice!
public class Game extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private Timer gameLoop;
public static final int WIDTH = 800;
public static final int HEIGHT = 500;
public static final Dimension SCREEN_SIZE = new Dimension(WIDTH, HEIGHT);
public static final int FRAMERATE = 60;
public static final String TITLE = "MedievalGame";
public BufferedImage[] images = new BufferedImage[4];
public int x = 100;
public int y = 100;
public int width = 100;
public int height = 100;
public Game() {
this.setPreferredSize(SCREEN_SIZE);
this.setFocusable(true);
try {
images[0] = ImageIO.read(getClass().getResourceAsStream("path"));
} catch (IOException e) {
e.printStackTrace()
}
gameLoop = new Timer(1000 / FRAMERATE, this);
gameLoop.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(images[0], x, y, width, height, null);
}
public void actionPerformed(ActionEvent e) {
this.repaint();
}
public static void main(String[] args) {
JFrame window = new JFrame(TITLE);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.add(new Game());
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
}
}
I checked many similar questions, but none solved my problem.