我正在使用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,否则对画布没有影响。
答案 0 :(得分:1)
实例变量不应该在构造函数之外进行初始化。可能会发生的是,在超类完全初始化之前调用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值导致图形对象由于显示机制而经常具有特定的生命周期,因此在构造函数调用之后仍然可能无法初始化高度和widht
答案 1 :(得分:0)
问题在于getWidth()
初始化时getHeight()
和RobotFace
= 0。从类级别删除这些行,并在createFace
方法中取消注释。
int _canvasWidth = getWidth();
int _canvasHeight = getHeight();
答案 2 :(得分:0)
好吧,我错误地在GObject初始化之前使用getWidth()和getHeight(),这使得getWidth()返回0.所以唯一的方法是确保在范围内调用getWidth() GObject正在被启动是为每个方法使用本地getWidth(),如createFace(),createMouth()。这个程序确实有效,但涉及很多复制粘贴。 因此,在替代类RobotFace2中,我在run()中创建了GObjects,即没有为createFace()等创建新方法。这样getWidth()只需要在run()中输入一次,而眼睛和嘴GRect可以锚定到面对GRect。 RobotFace2也可以工作。