簡體   English   中英

為什么“ getWidth()”為我返回0?

[英]why is “getWidth()” returning 0 for me?

我之所以這樣問,是因為我想知道為什么會這樣-而不是我應該采取什么措施來解決這個問題。 我真的只想要一個技術解釋,為什么數學運算(分配給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

在初始化之前,數字類型的默認值為0 您可以在實例字段初始化期間getWidth()即,在寬度還沒有初始化的時候getWidth()調用getWidth()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM