我试图通过使用数组定义点然后在每个时间步上用一条线连接它来“绘制”以下“随机漫步”的路径。我已经尝试了几乎所有东西,但线条根本没有画入...屏幕是空白的。任何帮助将不胜感激!显然,以下内容使用了JFrame库。我的代码如下:
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JFrame;
public class RandomWalk extends JPanel {
public static void main(String args[]) {
//The number of steps the algorithm iterates over.
int num = 2000;
//The length of a line.
int range = 50;
//Arrays for points.
float[] ax = new float[num];
float[] ay = new float[num];
//Dimensions of the combined array.
for (int i = 0; i < num; i++) {
ax[i] = 768;
ay[i] = 1280;
}
//Generates frame.
JFrame frame = new JFrame();
//Sets frame resolution and other parameters.
frame.setSize(768,1280);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RandomWalk panel = new RandomWalk();
frame.add(panel);
frame.setVisible(true);
frame.setResizable(false);
}
public void paintComponent(Graphics g, int num, int range, int [] ax, int [] ay) {
//Shift all elements 1 place to the left.
for(int i = 1; i < num; i++) {
ax[i-1] = ax[i];
ay[i-1] = ay[i];
}
//Put a new value at the end of the array.
ax[num-1] += (int) ((Math.random() * -range) + range);
ay[num-1] += (int) ((Math.random() * -range) + range);
//Draw a line connecting the points
for(int i=1; i<num; i++) {
float val = (float) ((i)/num * 204.0 + 51);
//Sets line color black
g.setColor(new Color((int) 0));
g.drawLine(ax[i-1], ay[i-1], ax[i], ay[i]);
}
repaint();
}
}
答案 0 :(得分:0)
试试这个
public class RandomWalk extends JPanel
{
final int range = 50;//max space to move in width or height
final int num = 50;//number of line-1 to draw
final int[] ax = new int[num];
final int[] ay = new int[num];
public RandomWalk(final int width, final int height)
{
final Random rand = new Random();//better to use Random. Easier to debug since you can set a seed
// lets set first point in the middle
ax[0] = width / 2;
ay[0] = height / 2;
// generating random point
for (int i = 1; i < num; i++)
{
//make sure that we dont go outside the bound of the panel
ax[i] = (int) Math.max(0, Math.min(width, ax[i - 1] + ((rand.nextFloat() - .5f) * range)));
ay[i] = (int) Math.max(0, Math.min(height, ay[i - 1] + ((rand.nextFloat() - .5f) * range)));
}
}
public void paintComponent(Graphics g)
{
g.setColor(Color.black);
for (int i = 1; i < num; i++)
g.drawLine((int) ax[i - 1], (int) ay[i - 1], (int) ax[i], (int) ay[i]);
}
public static void main(String[] args)
{
// Generates frame.
JFrame frame = new JFrame();
// Sets frame resolution and other parameters.
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RandomWalk panel = new RandomWalk(frame.getWidth(), frame.getHeight());
frame.getContentPane().add(panel);
frame.setVisible(true);
frame.setResizable(false);
}
}