gpt4 book ai didi

java - 为什么我的折线总是从原点 (0,0) 绘制?

转载 作者:行者123 更新时间:2023-11-30 07:20:12 25 4
gpt4 key购买 nike

我正在创建一个 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 之前的数组。 ,一切都很好。

关于java - 为什么我的折线总是从原点 (0,0) 绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37712497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com