java - 这段用红、黄、绿灯绘制红绿灯的代码是如何工作的?

标签 java

我在理解教科书中这个例子的概念时遇到了很多困难。这个想法是用红、黄、绿灯画一个红绿灯。我有一些问题。我无法弄清楚代码的哪一部分是做什么的。

  1. 我是否可以假设 cxcy 确定页面的中心?
  2. fxfy 是否可以确定框架的中心?
  3. 我不知道 dy 做了什么,也不知道为什么 3 个灯要除以 4 而不是 3,而 LAMP_RADIUS 让我完全困惑。
  4. 在红色、黄色和绿色的所有三个 add(createFilledCircle) 上,我不明白它们在红绿灯框架内的位置是如何计算的。
  5. 在方法createFilledCircle()中,我不明白GOval Circle = newGOval(x-r, y-r, 2 * r, 2 * r);。我不明白 x-r 和 y-r 的作用以及它与位置的关系。
import acm. graphics.*;
import acm. program.*;
import java.awt.*;

public class DrawStoplight extends GraphicsProgram {

    public void run () {
        double cx = getWidth() / 2;
        double cy = getHeight() / 2; 
        double fx = cx - FRAME_WIDTH / 2; 
        double fy = cy- FRAME_HEIGHT / 2; 
        double dy = FRAME_HEIGHT / 4 + LAMP_RADIUS / 2; 
        GRect frame = new GRect(fx, fy, FRAME_WIDTH, FRAME_HEIGHT);
        frame.setFilled(true);
        frame.setColor(Color.GRAY);
        add(frame);
        add(createFilledCircle(cx, cy - dy, LAMP_RADIUS, Color.RED));
        add(createFilledCircle(cx, cy, LAMP_RADIUS, Color.YELLOW));
        add(createFilledCircle(cx, cy + dy, LAMP_RADIUS, Color.GREEN));
    }

    private GOval createFilledCircle(double x, double y, double r, Color color){
        GOval circle = new GOval(x-r, y-r, 2 * r, 2 * r)
        circle.setColor(color);
        circle.setFilled(true);
        return circle;
    }

    private static final double FRAME_WIDTH = 50; 
    private static final double FRAME_HEIGHT = 100; 
    private static final double LAMP_RADIUS = 10; 

}

最佳答案

1. Am I right to assume cx and cy are to figure out the center of the page?

是的

2. Are fx and fy to figure out the center of the frame?

不完全是。他们正在计算框架的左上角。它们从中心开始,并在每个方向上“备份”帧大小的一半。

3. I don't know what dy does and why it's divided by 4 and not 3 for 3 lights and the LAMP_RADIUS totally confuses me. 

进一步查看代码。 dy 是灯光之间的垂直距离。黄灯正好绘制在中心,红色是上面的 dy,绿色是下面的 dy。除数是4,因为作者选择将红灯的底部边缘与距框架顶部1/4框架高度的点对齐。同样,他选择将绿灯的顶部与底部距框架高度 1/4 的点对齐。他本可以选择许多其他计算 dy 的方法。

4. On all three add(createFilledCircle) for red, yellow and green I don't understand how their position is calculated inside the stoplight frame. 

它们都有相同的 x 坐标:框架的中心。 y 坐标的计算方式如 3 中所述。请记住,在屏幕坐标中,正方向向下,因此增加 y 会使灯光变低。减少则越高。

5. In the method createFilledCircle() I don't understand GOval circle = newGOval(x-r, y-r, 2 * r, 2 * r);. I don't understand what x-r and y-r does and how that relates to position.

去阅读 newGOval 的手册定义。它在矩形内刻了一个椭圆形。参数是矩形的左上角,后面是宽度和高度。因此,如果 (x,y) 是中心,则给出一个对角线为 (x-r, y-r) 到 (x+r, y+r) 的盒子。当您在其中刻出一个椭圆形时,您会根据需要得到一个以 (x,y) 为中心的圆。

关于java - 这段用红、黄、绿灯绘制红绿灯的代码是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12905482/

相关文章:

java - 如何将 `java` 添加到 Vista 上的命令路径?

java - 使用 DOM 解析 XML 注释

java - 构造函数LinkedHashMultimap不可见

Java 垃圾收集和图形处理方法

java - 有没有理由不使用 Java 8 的 parallelSort?

java.sql.SQLException :field id does not have a default value

java - 实例化通用对象

java - 在 javadoc 中引用父类(super class)

java - 如何强制执行对象创建的某些方法?

Java - 将对象存储在遵循其类继承的层次结构中