概述
//import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.*;
//import java.awt.image.BufferedImage;
import java.awt.*;
import java.io.IOException;
public class SwingRandom extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 1L;
public SwingRandom()
{
add(new NewPanel());
}
public static void main(String[] args) throws IOException
{
SwingRandom frame = new SwingRandom();
frame.setTitle("2Random");
frame.setSize(1292, 812);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// 输出图片
// BufferedImage image = new BufferedImage(frame.getWidth(),
// frame.getHeight(), BufferedImage.TYPE_INT_RGB);
// Graphics2D g2 = image.createGraphics();
// frame.paint(g2);
// ImageIO.write(image, "png", new java.io.File("d:\Rnd.png"));
}
}
class NewPanel extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 1L;
NewPanel()
{
jb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
});
jb.setFocusPainted(false);
this.add(jb);
jb.setBackground(Color.yellow);
}
JButton jb = new JButton("按下重绘");
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
final int GIRD = 295000; //步数
final int STEP = 1; //步距
int[] xpoint = new int[GIRD];int[] ypoint = new int[GIRD];
xpoint[0] = 1292 / 2;
ypoint[0] = 812 / 2;
for (int i = 1; i < GIRD; i++)
{
int rnd = (int) (Math.random() * 4);
switch (rnd)
{
case 0:
xpoint[i] = xpoint[i - 1] + STEP;
ypoint[i] = ypoint[i - 1];
break;
case 1:
ypoint[i] = ypoint[i - 1] + STEP;
xpoint[i] = xpoint[i - 1];
break;
case 2:
xpoint[i] = xpoint[i - 1] - STEP;
ypoint[i] = ypoint[i - 1];
break;
case 3:
ypoint[i] = ypoint[i - 1] - STEP;
xpoint[i] = xpoint[i - 1];
break;
}
if (xpoint[i] <= 5 || xpoint[i] > 1292 - 20 || ypoint[i] <= 5
|| ypoint[i] > 812 - 100)
{
i = 0;
}
}
g.setColor(Color.blue);
g.drawPolyline(xpoint, ypoint, GIRD);
}
}
----------运行效果----------
295000步,步距1
----------190000步,步距2----------
----------20000步,步距5----------
注意:试验的时候尽量保证GIRD * STEP * STEP < 500000
最后
以上就是幽默钢笔为你收集整理的Swing下的二维随机游走轨道模拟的全部内容,希望文章能够帮你解决Swing下的二维随机游走轨道模拟所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复