Here I have a simple class that extends a class in the ACM graphics library called GRect. Grect is a basic rectangle that can be drawn to a GCanvas (Also part of ACM). What I want to achieve is a new object that is a rectangle, but has an attached label that moves with the rectangle.
In my code, I have created a class named labeledRect that extends GRect, and contains an instance variable "rectLabel" that is of type GLabel, that is initialized in labeledRects constructor. I want to override some of GRect's methods so that when labledRect is moved, rectLabel moves with it.
My issue is that despite "rectLabel" being declared as an instance variable, and initialized in the constructor, it becomes NULL in the overridden method "setLocation". I have also attempted to initialize "rectLabel" at declaration, but the same problem occurs.
import acm.graphics.*;
public class labeledRect extends GRect {
//GLabel declared as an instance variable
public GLabel rectLabel;
public labeledRect(double x, double y, double width, double height, String theLabel) {
//Call GRect constructor
super(x, y, width, height);
//Label initialized.
//Location setting and adding to the canvas works fine here.
rectLabel = new GLabel(theLabel);
rectLabel.setLocation(
x + (width / 2) - (rectLabel.getWidth() / 2),
y + (height / 2) + (rectLabel.getAscent() / 2.2));
}
public void setLocation(double x, double y)
{
//Setting GRect's location. Works correctly./
super.setLocation(x, y);
//Attempt to set the label's location
//and get a NullPointer exception for rectLabel
rectLabel.setLocation(
super.getX() - (rectLabel.getWidth() / 2),
super.getY() - (rectLabel.getHeight() / 2));
}
}