Java Graphics2D g2.drawLine将添加点/坐标,而不是绘制线

时间:2019-12-05 22:54:37

标签: java graphics2d

我正在尝试编写基于字符数组(字符串)命令绘制多条线的代码。

在我的示例中,F表示向下移动,+表示逆时针旋转,-表示顺时针旋转。

在我的结果中,仅绘制了第一行。

Image

行的结果仅显示坐标。

我的代码在下面。

import java.awt.*;
import javax.swing.*;

public class Draw extends JFrame{ //extends JFrame to help construct appropriate GUI

    int angle = 0;
    Graphics2D g2;

    public static void main(String[] args) { //main method
        Draw d =new Draw();
        d.setVisible(true);
    }

    public void paint(Graphics g) {
        super.paint(g);  // fixes the immediate problem.
        this.g2 = (Graphics2D) g;
        Coordinate s, e;
        s = new Coordinate(450, 450); 
        this.currentCoordinate = new Coordinate(450, 490);

        // this line is drawn!
        g2.drawLine(s.x, s.y, this.currentCoordinate.x, this.currentCoordinate.y);

        for (char c : "FFF+F-F".toCharArray()) {
            String character = String.valueOf(c);
            paintBasedOnSymbol(this.currentCoordinate, character);
        }
    }

    private Coordinate paintBasedOnSymbol(Coordinate c, String s) {

        switch(s) {
            case "F":
                c.setY(c.y + 10);
                c.setX(c.x + this.angle);
                // any lines triggered here are not drawn!
                g2.drawLine(this.currentCoordinate.x, this.currentCoordinate.y, c.x, c.y);
                break;
            case "+":
                this.angle += 15;
                break;
            case "-":
                this.angle -= 15;
                break;
            default:
                break;
        }

        this.currentCoordinate = c;

        return c;
    }

    public Draw(){ //constructor used to directly implement the frame UI
        JPanel panel=new JPanel();
        getContentPane().add(panel);
        setSize(900,900);

        JButton button =new JButton("press");
        panel.add(button);
        setDefaultCloseOperation(EXIT_ON_CLOSE); //make sure program stops when window is closed
    }
}

1 个答案:

答案 0 :(得分:0)

橡胶鸭子调试是真实的:)我发现了问题

如果遇到此问题,请不要编辑原始坐标的x / y值。

创建新的。

即我替换了

            c.setY(c.y + 10);
            c.setX(c.x + this.angle);

使用

new Coordinate(c.x + this.angle, c.y + 10);