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

标签 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
    }
}

最佳答案

橡皮鸭调试是真实的:)我找到了问题

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

创建新的。

即我替换了

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

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

关于Java Graphics2D g2.drawLine 正在添加点/坐标,而不是绘制线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59204432/

相关文章:

Java Swing 调整 BorderLayout.CENTER 大小

java - DWR 是 MVC 吗?

java - 设置超时时套接字不关闭

c# - 在 .Net 中清除位图

java - 在java绘图应用程序中检测Graphics2d手绘的直线及其曲线

java - AWT - 旋转整个 Swing 面板

java - Sonatype OSS 索引分析器请求组件错误报告 javax.net.ssl.SSLHandshakeException :

java - 查询 DNS 服务记录以查找主机名和 TCP/IP

java - 了解生成括号的函数

java - 线程未更新 GlassPane 上的进度栏