我试图使用数组列表绘制多个圆圈而不重叠,所以我使用CheckDistance函数检查下一个要绘制的形状的x和y但是它显示了stackoverflow的错误
我必须将它们保存在数组中才能检索每个形状以对其执行某些其他功能。
这是我的代码:
public class Algo
{
public static void main(String[] args)
{
new Algo();
}
public Algo()
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex)
{
ex.printStackTrace();
}
JFrame frame = new JFrame("Airport");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CountriesPane());
frame.pack();
frame.setSize(700, 700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class CountriesPane extends JPanel
{
private List<Country> Countries = new ArrayList<>(100);
public CountriesPane()
{
for (int index = 0; index < 50; index++)
{
Countries.add(new Country());
}
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for (Country Country : Countries)
{
Graphics2D g2d = (Graphics2D) g.create();
Country.paint(g2d);
g2d.dispose();
}
}
}
protected static final Random random = new Random();
public double x1;
public double y1;
public class Country
{
private int height = 20;
private int width = 20;
private double x2;
private double y2;
private double space = 10;
private Ellipse2D shape;
private String Name;
public Country()
{
CheckDistance(this);
shape = new Ellipse2D.Double(x2, y2, width, height);
}
public void paint(Graphics2D g2d)
{
g2d.setColor(Color.BLUE);
g2d.fill(shape);
}
}
public void CheckDistance (Country Co)
{
Co.x2 = random.nextInt() + Co.space;
Co.y2 = random.nextInt() + Co.space;
double distancex = Co.x2 - x1;
double distancey = Co.y2 - y1;
if (distancex <= Co.width || distancey <= Co.height)
{
CheckDistance(Co);
}
else
{
x1 = Co.x2;
y1 = Co.y2;
}
}
}
答案 0 :(得分:0)
这可能是无限循环(或太多循环)。
public void CheckDistance ( Country Co)
{
Co.x2 = random.nextInt() + Co.space;
Co.y2 = random.nextInt() + Co.space;
double distancex = Co.x2 - x1;
double distancey = Co.y2 - y1;
if (distancex <= Co.width || distancey <= Co.height)
{
CheckDistance(Co);
}
else
{
x1 = Co.x2;
y1 = Co.y2;
}
因为它可能永远是distancex&lt; = Co.width || distancey&lt; = Co.height取决于随机值。