java - Java中实例变量的作用是隐藏的

标签 java scope

我正在使用 GObject 类创建一个简单的面,该类将使用 GRect 和 GOval。我希望 GRect 和 GOval 锚定到我将 getWidth() 和 getHeight() 描述为实例变量的相同坐标。这样做时,我没有显示任何错误,但 Canvas 上没有结果。仅当我将 getWidth() 和 getHeight() 描述为局部变量时,我才能得到结果。为什么实例变量的效果没有显示出来?

/*
 * This is section 2 problem 2 to draw a face using GRect amnd GOval. The face is     centred in the canvas.
 * PS: The face is scalable w.r.t. canvas.
*/
package Section_2;
import java.awt.Color;
import java.awt.Graphics;

import acm.graphics.GRect;
import acm.program.GraphicsProgram;

/*
 * creates a robot face which is centered in the canvas.
 */
public class RobotFace extends GraphicsProgram{

private static final long serialVersionUID = 7489531748053730220L;

//canvas dimensions for centering
int _canvasWidth = getWidth();
int _canvasHeight = getHeight();
public void run(){

    removeAll();    //to make sure multiple instances of graphic are not drawn during resize as an effect of overriding Java paint method
    //draw objects
    createFace();

}

//currently only createFace() is implemented
/*
 * creates a rect which is centred in the canvas
 */
private void createFace() {

    //canvas dimensions for centering
    //int _canvasWidth = getWidth();
    //int _canvasHeight = getHeight();

    //make the face scalable
    int _faceWidth = _canvasWidth  / 6;
    int _faceHeight = _canvasHeight / 4;
    //to center the face
    int _faceX = (_canvasWidth - _faceWidth)/2;
    int _faceY = (_canvasHeight - _faceHeight)/2;

    GRect _face = new GRect(_faceX , _faceY, _faceWidth, _faceHeight);
    _face.setFilled(true);
    _face.setColor(Color.BLUE);
    add(_face);
}

/*
 * (non-Javadoc)
 * @see java.awt.Container#paint(java.awt.Graphics)
 * to override Java inherited paint method to retain graphic after resizing  
 */
public void paint(Graphics g) {
    this.run();
    super.paint(g);
}    
}

如果取消注释 getWidth() 和 getHeight() 的局部变量,您将获得 Rect ,否则对 Canvas 没有任何影响。

最佳答案

实例变量不应在构造函数之外初始化。可能发生的情况是在父类(super class)完全初始化之前调用 getXXX 方法,因此返回 0

编辑:

我的意思是,您应该更好地在类构造函数内初始化实例变量,以确保在调用其方法之前正确设置父类:

 public class RobotFace extends GraphicsProgram{

 //canvas dimensions for centering
 int _canvasWidth =0;
 int _canvasHeight = 0;

 public RobotFace() {
   super();
   _canvasWidth = getWidth();
   _canvasHeight = getHeight();
 }
 [...]

无论如何,这里不保证它会修复 0 值,因为由于显示机制,图形对象通常具有特定的生命周期,因此在构造函数调用后,高度和宽度可能仍未初始化

关于java - Java中实例变量的作用是隐藏的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15686562/

相关文章:

Java 本地化最佳实践

java - 如何让 ProGuard Maven 插件使用最新的 ProGuard 版本?

angularjs - AngularJS 中的范围未更新

php - 在所有 Yii View 中都有一个可用的变量

java - PHP $_POST 为空或 null

java - MediaPlayer 播放和重播问题

java - subList() 与其他类似的 Collections 方法有不同的行为,一旦 subList 被改变

javascript - 声明对象数组时的函数作用域问题

javascript - 访问 mqtt 回调范围之外的类属性

c++ - 存储类别、存储持续时间、文件范围、生命周期、链接困惑