我正在创建一个RandomWalk程序。该程序的大多数程序都可以正常工作,但是存在一个主要问题。

绘制折线时,它会继续被迫回到原点(0,0),而不是最后一点。我一直在尝试查看我遗失/做错的事情,但找不到问题所在。

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

主班

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);
    }
}


绘画课

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的那些数组,一切都很好。

09-25 16:59