0

I don't quite understand why the graphics do not show up. I am new at Java and I am trying to do a tutorial of snake. At this stage, a black window with the title "Snake" should pop up, but what I get is an empty grey window instead.

Here is the code for my main class

import javax.swing.JFrame;

import java.awt.Color;


public class Main {

public static void main(String[] args){
    JFrame obj = new JFrame();
    Gameplay gameplay = new Gameplay();

    obj.setBounds(10,10,905,700);
    obj.setBackground(Color.DARK_GRAY);
    obj.setResizable(false);
    obj.setVisible(true);
    obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    obj.add(gameplay);
    }
}

Here is the code for class Gameplay

import javax.swing.*;
import java.awt.*;


public class Gameplay extends JPanel {
public ImageIcon titleImage;
public Gameplay(){


}


public void paint(Graphics g)
{
    // draw title image border
    g.setColor(Color.white);
    g.drawRect(24, 10, 851, 55);

    //draw the title image
    titleImage = new ImageIcon("snaketitle.jpg");
    titleImage.paintIcon(this, g, 25, 11 );

    //draw border for gameplay
    g.setColor(Color.WHITE);
    g.drawRect(24, 74, 851, 577);


    // draw background for the gameplay
    g.setColor(Color.black);
    g.fillRect(25, 75, 850, 575);
    }
}

Thanks for your help!

2 Answers2

0

The issue here is, that your snaketitle.png is most likely not found. You can check here for a more in depth explanation.

What you will have to do to fix this is get your image resource via the relative path to the resource. You can check out this aswell.

So in short, I would do:

    URL imageLocation = this.getClass().getResource("/path/to/the.resource");
    titleImage = new ImageIcon(imageLocation);
maloomeister
  • 2,461
  • 1
  • 12
  • 21
0

you should revalidate() and/or repaint() your JFrame. or add your gameplay component first to the contentpane of your JFrame, before making it visible. Besides that please note that all painting operations usually are safe to execute if you do them on the so called event dispatch thread (EDT). there are a lot of resources on that topic also here at Stackoverflow.

also have a look at SwingUtilities.invokeLater(...) which can be used to ensure that painting operations are executed on the EDT.