0

I want to use an anonymous inner class to handle mouse actions for an object in my program. However, depending on a parameter, I want the inner class to act differently. For example:

Rectangle r1 = rectangleBuilder (Color.Red);
Rectangle r2 = rectangleBuilder (Color.Blue);

public Rectangle rectangleBuilder (final Color c) {
    r = new Rectangle (100, 100, c);

    r.dragListener = new DragListener () {
        @Override
        public void drag (double x, double y) {
            if (c == Color.Red) {
                r.setPosition (x, y);
            }
            if (c == Color.Blue) {
                r.setPosition (2 *x, 2 *y);
            }
        }
    }

    return r;
}

The idea is that when creating the object, the behavior when it's dragged is decided by its color. This was working fine but now for some reason I'm getting an exception saying that c (Color) is null. I'm wondering if this sort of approach is possible in Java.

Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
James Andrews
  • 3,257
  • 3
  • 31
  • 45
  • Nothing here would throw an exception if c were null; what line does the error occur on? – Ernest Friedman-Hill Apr 19 '13 at 19:48
  • Is it null when somebody passes it to _rectangleBuilder()_? Sounds like that's the problem... – jahroy Apr 19 '13 at 19:49
  • 1
    I'm afraid that `c` is indeed `null`; it has exactly nothing to do with this approach, as it's only affects the `r = new Rectangle (100, 100, c);` line – alf Apr 19 '13 at 19:49
  • Yes it is possible to pass the variable, if the variable is final! it seems you are passing null as argument to that method. – AllTooSir Apr 19 '13 at 19:50
  • When I put a break point in the inner class, I find that c is null. That means that the logic which decides how to set the position doesn't work. It's definitely not null when it pass it to rectangleBuilder. – James Andrews Apr 19 '13 at 19:51

2 Answers2

0

It turned out to be a strange issue completely unrelated to Java. The enum Color was in another class which happened to have a compile error. Apparently Eclipse was treating every instance the Color class as null.

James Andrews
  • 3,257
  • 3
  • 31
  • 45
0

If the jvm says that there is a null pointer, it means that the pointer is null. With the code here, there is only 1 solution it is call with a null pointer. Check the stacktrace and you will find where you call this method with a null object.

If it is normal that you pointer is null, you can define a default color.

if (c == null)
    r = new Rectangle(100, 100, Color.black);

and handle this case in the drag() method.

mki
  • 635
  • 3
  • 10