我正在使用 GObject 类创建一个简单的面孔,该类将使用 GRect 和 GOval。我希望 GRect 和 GOval 锚定到我将 getWidth() 和 getHeight() 描述为实例变量的相同坐标。我这样做时没有显示任何错误,但画布上没有结果。只有当我将 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 ,否则对画布没有影响。