java.lang.NullPointerException on Canavas?

Hello!

This might be the wrong forum, but I couldn’t find a different place to post it. My problem is is that I’m getting a java.lang.NullPointerException when ever I try to draw on a canvas. Can anyone tell me why I’m getting this?

Thanks,
Laserdude45

This can be the case if one variable isn’t initialized, and there’s not much to do than checking the init status with != null conditions or to catch the Exception whenever it arises. :-[

Ahh gezz :frowning:

I’ve already done the catch. I know what function it occurs in. Its using variables declared outside of the function. Should I declare those public?

No, that won’t change anything. You should check where this variable is given a value (or rather, should be)

If you show some code, it would make it easier to figure out the problem.


 private void canvas1MousePressed(java.awt.event.MouseEvent evt) {                                     
        try {
        g.drawString("Debug!",x,y);
        }
        catch (NullPointerException e) {
            System.out.println(e);
        }
    }          

and where I’m initing variables…


Graphics g;
MouseEvent evt;
int x = evt.getX();
int y = evt.getY();

Btw, I’m Declaring the variables in the public class area…

I’d change the code like a more directly way, see:


 private void canvas1MousePressed(java.awt.event.MouseEvent evt) {                                     
        try {
        this.evt = evt;  // btw: this event maybe left unstored with x and y stored at every caught event
        g.drawString("Debug!", x = evt.getX(), y = evt.getY());
        }
        catch (NullPointerException e) {
            System.out.println(e);
        }
    }          

:wink:
and where I’m initing variables… with no x and y initialized here.


Graphics g;
MouseEvent evt;
int x, y;

You do not have a valid Graphics object. You should limit your drawing to the paint(Graphics g) method. After you can learn active rendering.

How do I do that? :stuck_out_tongue:

http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html

That link is specific to your question. I would recommend that you read the entire tutorial, not just that part of it. A lot of questions people have could easily be answered by doing that tutorial. It is well worth the time.

essentially for your request, you will be able to paint on one component with the mouse, would that be?
That is, java supports many kinds of painting features. But for the correct purpose of the forum here’s one snippet you could try, because this is really “as is” in every java painting code :


class MousePaintComponent extends JComponent implements MouseListener{
       Point evt = new Point(0, 0);

        public MousePaintComponent(Dimension size, boolean db) {
                   super();
                   this.size = size;
                   setDoubleBuffered(db);
        }

        protected void paintComponent(Graphics g) {
                  super.paintComponent(g);
                  Graphics2D g2 = (Graphics2D)g;
                  g.drawString("Debug!", evt.x, evt.y);
        }
        Dimension size = null;
        public void update(Graphics g) {
                 g.clearRect(0, 0, size.width, size.height)
                 super.update(g);
       }
        public setSize(int width, int height ) {
                 this.size = new Dimension(width, height);
         }
       /** MOUSE LISTENER METHOD*/
       public void mousePressed(MouseEvent e) { evt.x = e.getX(); evt.y = e.getY();  repaint(); }
       public void mouseReleased(MouseEvent e) { evt.x = 0; evt.y = 0;  repaint(); }
       public void mouseDragged(MouseEvent e) { // a bit buggy repaint(); }
}

here is the graphics updated at each call to repaint(), whether using double buffering.or not. :wink: There are other ways to implements kinda mouseListeners but this is one I use.

Java threading is a world of trouble. Typically, in java programs you will have at least three threads
active at all times - the “mouse” thread, the “repaint” thread, and the main application run loop.

You basically have two choices:

Be very, very careful every time to manipulate a data structure to consider what might happen if one
of the other threads ran “right now”, and combat concurrency issues with careful use of synchronized
primitives. Getting this right, and keeping it right, is a never ending struggle. You’re very likely to either
miss an important synchronization issue, or to overuse synchronization and end up with deadlocks.
The nastiest aspect of this design is that programs seem to work, because the bugs are only exposed
by infrequent timing windows. These problems are practically impossible to debug because they are
very hard to reproduce.

The other choice is to coerce your program back into a single threaded model, so that every piece of
code is executed in exactly one thread, and a few critical data changes are protected with synchronization.

Personally, I do EVERYTHING to one thread. In my applets, the mouse and canvas repaint threads
just quickly note the activity and exit without doing any real work. All the substantial code runs
in the main event loop, which can safely assume that everything is happening serially in exactly
the sequence it naturally provides.

Using one program flow does eliminate many problems, and it’s not hard for a beginner to do this either. When we were working on a software engineering project a few years back I refactored the code to process the game via a list of commands. It meant that you essentially had one program flow, and since the list was thread safe I had no issues making mouse/button clicks or text commands work with it.

At the end of the day just know where there is going to be an issue and deal with the issues. And when you don’t know how to deal with deadlock/ race conditions you probably don’t want to be synchronizing everything either!

Why are we discussing the difficulties of threading here?

The original poster doesn’t have a threading problem, he’s just trying to call methods on an uninitialized Graphics variable, which has been pointed out and for which CaptainJester gave a link to an appropriate tutorial.

Let’s not confuse him with complicated threading issues he doesn’t have :slight_smile:

We are simulating threading by having multiple conversations in a thread not about threading ::slight_smile:

LOL, time to make JGO thread-safe ;D

ROFL lol :smiley:

I jumped to the conclusion that the reason the variables were not initialized was a thread race between the
paint thread and the initialization thread. It happens often enough.