1

I did a small test according to a problem in another program I am writing. I need to draw an image to the screen, but it does not work. However, I am able to draw rectangles to the screen, I do not understand

Code:

Main class:

package test;
import javax.swing.JFrame;

public class Main extends JFrame{
    private static final long serialVersionUID = 1L;
    final static int WW = 800;
    final static int WH = 600;
    public Main(){
        setSize(WW,WH);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setTitle("Space Game");
        add(new testClass());
        setVisible(true);
    }
    public static void main(String[] args) {
        new Main();
    }
}

testClass class:

package test;
import java.awt.*;

import javax.swing.*;

public class testClass extends JPanel{
    private Image image;
    public testClass(){
        ImageIcon image = new ImageIcon("spaceship.png");
    }
    public void paintComponent(Graphics g){
        g.setColor(Color.BLACK);
        g.fillRect(50,50,50,50);
        g.drawImage(image,0,0,null);
    }
}

Please help and explain why it does not work. Sorry for bad English, any help is appreaciated :) *I am sorry if my question is newbie, I am new in programming...

OpenGLmaster1992
  • 281
  • 2
  • 5
  • 13

1 Answers1

3

There is one major error in your code: ImageIcon image has method scope, while Image image has class scope. So the image you are trying to paint in paintComponent is not the same image that you've loaded in the constructor.

Fixing that won't be enough to make it work though. What I would recommend doing is the following. Use an Image. Then, in the constructor, assign it using image = ImageIO.read(new File("spaceship.png"));

John C
  • 500
  • 3
  • 8