java为什么“getWidth()”为我返回0?
我问这个问题是因为我想知道为什么会这样——而不是我应该做些什么来规避这个问题。我只想从技术上解释一下为什么数学运算(分配给currentXMargin)中的getWidth()没有返回值。我用GLabel表示testValue1和testValue2;testValue1显然返回正确的像素量,而testValue2返回-210(当然是金字塔的一半);它需要说167(就像我硬编码公式的testValue1一样)。更重要的是,当我尝试在GRect构造函数中使用currentXMargin时,它也无法在那里工作,返回相同的结果(-210,如果我使用变量,则返回正确的数量,如果我只是硬编码公式),金字塔底部离屏幕左侧有一半距离
那么为什么getWidth不在currentXMargin赋值(在run方法下面)中向操作返回一个值呢
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
public class Pyramid extends GraphicsProgram {
/** Width of each brick in pixels */
private static final int BRICK_WIDTH = 30;
/** Height of each brick in pixels */
private static final int BRICK_HEIGHT = 12;
/** Number of bricks in the base of the pyramid */
private static final int BRICKS_IN_BASE = 14;
public void run() {
double testValue1 = (getWidth() - (BRICKS_IN_BASE * BRICK_WIDTH))/2;;
GLabel test = new GLabel("width: "+testValue1,0,10);
add(test);
double testValue2 = currentXMargin;
GLabel test2 = new GLabel("width: "+testValue2,0,20);
add(test2);
//doRow();
}//run
private int brickCount = BRICKS_IN_BASE;
private double currentXMargin = (getWidth() - (BRICKS_IN_BASE * BRICK_WIDTH))/2;
private double currentYMargin;
GRect brick[] = new GRect[14];
private void doRow(){
for(int i=0;i<brickCount;i++){
brick[i] = new GRect(currentXMargin,10,BRICK_WIDTH,BRICK_HEIGHT);
add(brick[i]);
currentXMargin += BRICK_WIDTH;
}
currentYMargin -= BRICK_HEIGHT;
brickCount -= 1;
}//doRow
}//class
# 1 楼答案
0
是数值类型的默认值,直到它们被初始化为止。在初始化实例字段期间,即在宽度尚未初始化时调用getWidth()