Java小程序忽略getWidth()
我正在尝试使用GRect在Java中构建一个金字塔。我使用getWidth()将棱锥体定位在画布的中心,但它往往会绊倒棱锥体的左侧 我正在通过Java 1.6学习编程和使用Java 1.6,因此我尝试获取一些其他人的代码,他们也显示了相同的错误。我试着画一个简单的矩形,效果很好 Java小程序会忽略getWidth()值,这是不是有什么问题。我使用println();获取getWidth()值并使其工作Java小程序忽略getWidth(),java,Java,我正在尝试使用GRect在Java中构建一个金字塔。我使用getWidth()将棱锥体定位在画布的中心,但它往往会绊倒棱锥体的左侧 我正在通过Java 1.6学习编程和使用Java 1.6,因此我尝试获取一些其他人的代码,他们也显示了相同的错误。我试着画一个简单的矩形,效果很好 Java小程序会忽略getWidth()值,这是不是有什么问题。我使用println();获取getWidth()值并使其工作 import acm.graphics.GRect; import acm.
import acm.graphics.GRect;
import acm.program.GraphicsProgram;
public class Pyramid extends GraphicsProgram {
/**
* eclipse generated SVUID
*/
private static final long serialVersionUID = 5703830460071233096L;
/** Width of each brick in pixels */
private static final int BRICK_WIDTH = 30;
/** Width 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() {
//centering the pyramid
int _canvasWidth = getWidth(); //canvas width
//println(_canvasWidth); //to check if getWidth returns a value
int _brickSpace = BRICKS_IN_BASE * BRICK_WIDTH; //space consumed by the base row
int _freeSpace = _canvasWidth - _brickSpace; //empty base level space
int _xOffset = _freeSpace / 2; //x for left most brick of base row
for(int row=0; row<BRICKS_IN_BASE; row++){ //the row number
int _rowTab = (BRICK_WIDTH/2) * row; //indentaion for each row
int _brickInRow = BRICKS_IN_BASE - row; //bricks as per row
for(int _brickNumber=0; _brickNumber<_brickInRow; _brickNumber++){ //placing bricks till _brickInRow
int x = (_xOffset + _rowTab) + (_brickNumber * BRICK_WIDTH);
int y = (BRICK_HEIGHT * (BRICKS_IN_BASE - row)); //y as per row num
GRect _brick = new GRect(x, y, BRICK_WIDTH, BRICK_HEIGHT); //creating brick instance
add(_brick);
}
}
}
}
导入acm.graphics.GRect;
导入acm.program.GraphicsProgram;
公共类金字塔扩展图形程序{
/**
*eclipse生成的SVUID
*/
私有静态最终长serialVersionUID=5703830460071233096L;
/**每个砖的宽度(以像素为单位)*/
专用静态最终整砖宽度=30;
/**每个砖的宽度(以像素为单位)*/
专用静态最终整砖高度=12;
/**金字塔底部的砖块数量*/
基础中的专用静态最终整型砖=14;
公开募捐{
//以金字塔为中心
int _canvasWidth=getWidth();//画布宽度
//println(_canvasWidth);//检查getWidth是否返回值
int _brickSpace=BRICKS\u IN_BASE*BRICK\u WIDTH;//基行消耗的空间
int _freeSpace=\u canvasWidth-\u brickSpace;//空的基本级别空间
int _xOffset=_freeSpace/2;//x表示基行最左侧的砖块
对于(int row=0;row我尝试了您的代码,它首先在中心绘制金字塔,但是当我调整查看器窗口的大小时,问题出现了。
关键是Java小程序有一个名为public void paint(Graphics g)
的继承方法,每当需要绘制小程序时都会调用该方法。调整查看器窗口的大小是使绘制方法被调用的情况之一
因此,要解决此问题,您需要覆盖paint方法,即添加这样的方法:
public void paint(Graphics g) {
this.run();
super.paint(g);
}
每次调整窗口大小时都会调用此方法。但请记住,您不需要多个棱锥体,因此在添加新的棱锥体之前,请将以下行添加到run
方法中,以删除所有以前的棱锥体
removeAll();
我尝试了public void paint(Graphics g){this.run();super.paint(g);}
但是我得到了两个金字塔,在我的旧的绊倒金字塔的左侧,然后在它的右侧是一个居中的金字塔。在我的系统上,甚至在调整窗口大小之前,金字塔就被绊倒了。没有调整大小的效果。而且你有removeAll()
行在run
方法的开头?你明白了。我把removeAll();
放在run(){}
之后……那是个错误……我太傻了。是的,即使调整大小,代码现在也能工作了。:)