I am new to java and i have recently started trying to create a snake game. I have figured out a majority of the logic but one thing that i absolutely cannot do is figure out how to draw an image on a JFrame using (Graphics g). I am open to suggestions about the rest of my code as well if you wish to criticize, as i am just trying to learn as best and as thoroughly as i can.
Written below is my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Graphics;
import java.awt.image.*;
import javax.swing.ImageIcon;
import javax.imageio.ImageIO;
import java.awt.Toolkit;
public class SnakeGame {
public JFrame board;
public Image snakeHead;
public Image snakeBody;
public Image apple;
public boolean isFacingRight = true;
public boolean isFacingUp = false;
public boolean isFacingLeft = false;
public boolean isFacingDown = false;
public boolean inGame = true;
public int[] x;
public int[] y;
public int apple_x;
public int apple_y;
public int bodyParts = 3;
public static void main(String[] args) {
SnakeGame sm = new SnakeGame();
sm.initGUI();
}
public void initGUI() {
JFrame board = new JFrame("Snake");
JPanel panel = new JPanel();
board.add(panel);
ImageIcon SNAKE_HEAD = new ImageIcon("snakehead.png");
snakeHead = SNAKE_HEAD.getImage();
ImageIcon SNAKE_BODY = new ImageIcon("snakebody.png");
snakeBody = SNAKE_BODY.getImage();
ImageIcon APPLE = new ImageIcon("apple.png");
apple = APPLE.getImage();
board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
board.setLocationRelativeTo(null);
board.setVisible(true);
board.pack();
board.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
public void paintComponent(Graphics g) {
if(inGame) {
}
}
}