0

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) {
    
    
    }
}
}
    
camickr
  • 321,443
  • 19
  • 166
  • 288
  • 1
    You don't draw directly on a JFrame. You draw in the paintComponent method override of a JPanel that is then displayed in the JFrame. This has been well hashed on this site and on other sites in similar questions that I invite you to search for and review. – Hovercraft Full Of Eels Aug 07 '20 at 00:20
  • 1
    Custom painting is done by overriding `paintComponent(...)` of a JPanel and then you add the panel to the frame. In the `paintComponent(...)` method you use the `drawImage(...)` method of the Graphics object. Read the section from the Swing tutorial on [Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) for working example. Download the working example and then customize them to draw the image. The idea is to start with something that works and them make a small change. You can also search the forum/web for example that use the drawImage() method. – camickr Aug 07 '20 at 00:21

0 Answers0