Starconqueror
Starconqueror

Reputation: 1

Thread NullPointerException

Hey whenever i run this error output.

Exception in thread "Thread-2" java.lang.NullPointerException
    at GraphicsTest.render(GraphicsTest.java:50)
    at GraphicsTest.run(GraphicsTest.java:58)
    at java.lang.Thread.run(Unknown Source)

here is the code i cant figure out why it will not work. i have searched online and cant seem to find any answers. i am new and just wanna draw an image to the screen. then maybe try and create a bufferedImage array later on but that is looking like it will be awhile down the road haha. thanks in advance for any help :)

public class GraphicsTest extends JPanel implements Runnable{

public static BufferedImage image;
private boolean isRunning = false;

public void start() {
    isRunning = true;
    new Thread(this).start();

}

public static void main(String args[]) {

    GraphicsTest I = new GraphicsTest();

    JFrame window = new JFrame("Test Rendering");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setResizable(false);
    window.setLocationRelativeTo(null);
    window.setPreferredSize(new Dimension(600, 400));
    window.pack();
    window.setVisible(true);

    I.start();

    try {
        image = ImageIO.read(new File("Grap/roby.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public void render() {
    Graphics g = getGraphics();
    g.drawImage(image, 0, 0, null);
}

@Override
public void run() {

    while(isRunning) {

        render();

        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

}

Upvotes: 0

Views: 308

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347334

and just wanna draw an image to the screen

Try using something like...

GraphicsTest gt = new GraphicsTest();

try {
    image = ImageIO.read(new File("Grap/roby.png"));
    I.add(new JLabel(new ImageIcon(image));
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

JFrame window = new JFrame("Test Rendering");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(gt);
window.setLocationRelativeTo(null);
window.setPreferredSize(new Dimension(600, 400));
window.pack();
window.setVisible(true);

Take a look at How to Use Labels for more details.

Never use getGraphics to try and do custom painting, this is not how painting works in Swing.

If you're really intersted in knowing how painting works, take a look at Painting in AWT and Swing and Performing Custom Painting for more details.

You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

Upvotes: 2

Related Questions