嗯,这似乎很奇怪。我有点初始化变量,它在初始化后立即在构造函数中工作,但是在 draw 方法中它不再工作了......
好吧,这是代码,每当我尝试在方法 draw() 中调用对象位置的任何方法时,我都会遇到异常:
public class GlText extends GraphicObject {
String fullText = "";
public GlText(Bounds bounds) {
this.bounds = bounds;
this.position = getPosition();
System.out.println("BLOGAS: " + position.getX());
}
@Override
public void draw(Graphics g, AlignStrategy align) {
g.setColor(Color.orange);
g.setFont(new Font("Arial", Font.BOLD, 36));
FontMetrics metrics = g.getFontMetrics();
int textHeight = metrics.getHeight();
int textWidth = metrics.stringWidth(fullText);
// drawing position is recalculated according to text size, etc...
int x = 0;
int y = 0;
// calculating x according to text width
// !!!!!!!!!!!!!!! the Null pointer exception happens in the next line:
System.out.println("POSITION " + position.getX());**
System.out.println("TEXTWIDTH " + textWidth);
System.out.println("BOUNDS " + bounds.getX());
if (position.getX() - textWidth < bounds.getX())
x = bounds.getX();
else
x = position.getX() - textWidth;
// calculating y according to text height
if (position.getY() - textHeight < bounds.getY())
y = bounds.getY();
else
y = position.getY() - textHeight;
Bounds drawPos = new Bounds(x, y, textWidth, textHeight);
// ADDED ALIGN STRATEGY
Bounds alignedPosition = (Bounds) align.getAligned(drawPos, bounds);
g.drawString(fullText, alignedPosition.getX(), alignedPosition.getY());
}
public final Bounds getPosition() {
int x = 0;
int y = 0;
Random random = new Random();
random.setSeed(System.nanoTime());
x = bounds.getX() + random.nextInt(bounds.getWidth());
y = bounds.getY() + random.nextInt(bounds.getHeight());
Bounds newPosition = new Bounds(x, y, 0, 0);
return newPosition;
}
以下是异常的样子:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GraphicObjectPkg.GlText.draw(GlText.java:43)
这是我用 GlText 扩展的抽象类:
public abstract class GraphicObject {
protected Bounds bounds = new Bounds();
protected Bounds position = null;
public abstract void draw(Graphics g, AlignStrategy align);
}
好的,这是调用构造函数的地方,嗯,它是从外部调用的,但构造函数确实打印了“BLOGAS:180”行:
GlText myText = new GlText(currentBounds);
myText.setFullText("gerai");
mainGroup.addChild(myText);
最终编辑:感谢大家帮助我,由于您的帮助,我终于确定了问题所在,这是剩下的:
public void setFullText(String fullText) {
this.fullText = fullText;
position = null;
}
我已经修改了类,我完全忘记了这个方法有这样的东西......我通过使用 find 命令找到了这个,所以我想这次对我来说这个故事的寓意是你是否似乎没有创建任何其他变量,最好用编辑器上的查找功能测试一下...