如果有人能帮助我,我将非常感激。
我的程序有两个类。一个绘制矩形和网格,另一个是查看器。问题是,当我试图改变贪婪+矩形的位置时,即更新Viewer类中的X和Y常量,比例会发生变化。只有当X=0和Y=0时,网格才适合。
我使用相同的坐标数组来绘制网格和矩形,但不知何故比例是错误的,这让我感到惊讶。
谢谢。我代码:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.math.BigDecimal;
public class Viewer extends Applet {
public static final double R_WDTH = 12;//rectangle width
public static final double X = 10;//the grid fits in only when X=Y=0
public static final double Y = 10;
public static final int ROWS = 25;
public static final int COLUMNS = 12;
RectangleAndGrid cup = new RectangleAndGrid(X, Y, R_WDTH, ROWS, COLUMNS);
public void paint(Graphics g) {
cup.draw((Graphics2D)g);
}
}
public class RectangleAndGrid {
private double x, y, blockWidth;
private int rows, columns;
private double coordX[][], coordY[][];
private Rectangle2D.Double cupSpace;
public RectangleAndGrid(double cX, double cY, double givenBlockWidth, int r, int c){
x = cX;
y = cY;
blockWidth = givenBlockWidth;
rows = r;
columns = c;
BigDecimal currX = BigDecimal.valueOf(x);
BigDecimal currY = BigDecimal.valueOf(y);
coordX = new double[rows + 1][columns + 1];
coordY = new double[rows + 1][columns + 1];
for(int i = 0; i <= rows; i++){
for(int j = 0; j <= columns; j++){
coordX[i][j] = currX.doubleValue();
coordY[i][j] = currY.doubleValue();
currX = currX.add(BigDecimal.valueOf(blockWidth));
}
currX = BigDecimal.valueOf(x);
currY = currY.add(BigDecimal.valueOf(blockWidth));
}
cupSpace = new Rectangle2D.Double(coordX[0][0], coordY[0][0], coordX[rows][columns], coordY[rows][columns]);
}
public void draw(Graphics2D g2d){
g2d.setColor(Color.CYAN);
g2d.fill(cupSpace);
g2d.setColor(Color.BLACK);
g2d.draw(cupSpace);
Line2D.Double line = new Line2D.Double();
for(int i = 0; i <= rows; i++){
line.setLine(coordX[i][0], coordY[i][0], coordX[i][columns], coordY[i][columns]);
g2d.draw(line);
}
for(int i = 0; i <= columns; i++){
line.setLine(coordX[0][i], coordY[0][i], coordX[rows][i], coordY[rows][i]);
g2d.draw(line);
}
}
}
首先,你的方法有点奇怪,不完全是坏的,只是有点奇怪- IMHO
Rectangle2D
有四个参数:x
、y
、width
和height
。在你的代码中,你正在传递网格的顶部,左侧和右下角,这意味着,你的"杯子"的宽度/高度实际上比x
像素更宽(y
像素更高)
基本上,你需要从右下角的坐标中减去x
/y
的偏移量…
cupSpace = new Rectangle2D.Double(coordX[0][0], coordY[0][0], coordX[rows][columns] - coordX[0][0], coordY[rows][columns] - coordY[0][0]);