为什么我的折线一直从原点 (0,0) 开始绘制?

Why does my PolyLine keep drawing from origin (0,0)?

我正在创建一个 RandomWalk 程序。该程序的大部分功能都在正常运行,但是,存在一个主要问题。

绘制折线时,它一直被强制返回原点 (0,0) 而不是最后一个点所在的位置。我一直在尝试查看我的错误 missing/doing,但我找不到问题所在。

如有任何帮助,我们将不胜感激;如果需要更多信息,请询问。谢谢

主要Class

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

public class RandomWalk {
    public static void main (String[] args) {

        // Creating main frame
        JFrame main = new JFrame("RandomWalk - Version 1.0");
        main.setSize(800, 800);
        main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        main.setResizable(false);
        main.setLocationRelativeTo(null);

        // Creating content/container panel
        JPanel container = new JPanel();
        container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
        main.setContentPane(container);

        // Creating scene/canvas
        Draw canvas = new Draw();
        canvas.setAlignmentX(Component.CENTER_ALIGNMENT);

        container.add(canvas);

        main.toFront();
        main.setVisible(true);
    }
}

绘图Class

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

public class Draw extends JPanel {

    // Starting value for i
    public static int i = 1;

    // Increment for line length
    public static int inc = 10;

    // Choose amount of lines/moves
    public static int a = 10000;

    // Arrays for polyline points
    public static int[] xPoints = new int[a];
    public static int[] yPoints = new int[a];

    public Timer timer = new Timer(5, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            xPoints[0] = 400;
            yPoints[0] = 400;

            if (i < a) {

                double r = Math.random();

                if (r < 0.25) {
                    xPoints[i] = xPoints[i - 1] - inc;
                    yPoints[i] = yPoints[i - 1] - 0;
                    i++;
                } else if (r < 0.50) {
                    xPoints[i] = xPoints[i - 1] + inc;
                    yPoints[i] = yPoints[i - 1] + 0;
                    i++;
                } else if (r < 0.75) {
                    yPoints[i] = yPoints[i - 1] - inc;
                    xPoints[i] = xPoints[i - 1] - 0;
                    i++;
                } else if (r < 1.00) {
                    yPoints[i] = yPoints[i - 1] + inc;
                    xPoints[i] = xPoints[i - 1] + 0;
                    i++;
                }
                repaint();
            }
        }
    });

    public void paintComponent(Graphics g) {

        timer.start();

        g.drawPolyline(xPoints, yPoints, xPoints.length);
    }
}

您想使用 g.drawPolyline(xPoints, yPoints, i); 而不是 g.drawPolyline(xPoints, yPoints, xPoints.length);

这是因为如果你使用 xPoints.length,你就是在告诉它使用整个 xPointsyPoints 数组,即使你还没有初始化 xPoints[j] yPoints[j] 所有 j > i(因此它们都是 0)。如果您使用 i 作为长度,它只会读取索引 i 之前的那些数组,一切都很好。