0

I have a class with a JPanel, and paintComponent(). I also have a class that implements Runnable, and which I plan to draw images onto the paintComponent once the thread is started. My Constructor takes in the JPanel, and from there I call getGraphics(). However through testing, and searching this always seems to return null.

    System.err.println("Thread Started");
    isRunning = true;
    System.err.println(pap.getGraphics());
    Graphics g = pap.getGraphics();   //pap is the name of the JPanel
    while (isRunning)
    {
        while(xPos <= pap.getWidth() + 1)
        {
            xPos+=horizontalDirection;
            System.err.println(xPos);
            drawImage(upImgs[1], xPos, yPos, g);
            pap.repaint();
            pause();
            //g.drawOval(xPos, 10, 10, 10);
            if(xPos >= pap.getWidth())
                horizontalDirection = -horizontalDirection;
            if(xPos < 1)
                horizontalDirection = 1;
        }        
        //pap.repaint();
        //pause(); // let this thread sleep a bit
    }
    System.err.println("Thread Ended");

returns Thread Started 2 null Exception in thread "Thread-1" java.lang.nullPointerException

How can I properly get the paintComponent to draw on it from this separate class?

1 Answer 1

2

You can't do that. Awt/Swing are not thread safe, so drawing can only be done from the gui thread.

Sign up to request clarification or add additional context in comments.

3 Comments

Could I have my thread "bump" a method in the GUI thread and it could paint itself from there?
Use SwingUtilities.invoke or .invokelater to run the code on the gui thread.
What you should do, is make a class which extends JComponent and which then repaint itself. To force a repaint you then can call the repaint() method from your other thread.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.