我正在创建一个RandomWalk计划。大多数程序都在按预期工作,但是有一个主要问题。
当绘制PolyLine时,它会继续被强制回原点(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);
}
}
答案 0 :(得分:1)
您想使用g.drawPolyline(xPoints, yPoints, i);
而不是g.drawPolyline(xPoints, yPoints, xPoints.length);
。
这是因为如果您使用xPoints.length
,即使您尚未初始化xPoints
和{{}},也要告诉它使用您的整个yPoints
和xPoints[j]
数组所有yPoints[j]
都{1}}(因此它们都是j > i
)。如果您使用0
作为长度,它将只读取那些数组,直到索引i
,并且一切都很好。