我正在尝试开发一种Java代码,其中将以这种方式排列规则/不规则形状,以便我可以利用整页考虑。我想创建一个应用程序,它将尝试找到将自定义形状排列到给定区域的所有可能方法,以便尽可能地利用我的区域。我已经阅读了使用Random类生成概率。此外,我已经制作了小片段,我知道它不像我说的那样工作,但我想安排这些形状。任何算法或链接将不胜感激。
这是我的代码:
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class DrawGraph {
JPanel panel;
JFrame frame;
Random rand;
public DrawGraph()
{
frame = new JFrame("Graph");
rand = new Random();
panel = new JPanel(){
private static final long serialVersionUID = 1L;
protected void paintComponent(Graphics g2)
{
super.paintComponents(g2);
Graphics2D g = (Graphics2D) g2;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.black);
int i,j,x=0,y=0;
int width = panel.getWidth();
int height = panel.getHeight();
int intervalX = (int)Math.round(width*0.02);
int intervalY = (int)Math.round(height*0.02);
for(i=0,j=0;i<=width || j<=height;i+=intervalX,j+=intervalY)
{
g.drawLine(x, j, width, j);
g.drawLine(i,y,i,height);
}
g.setColor(Color.GREEN);
for(i=1;i<=5;i++)
generateShape(g);
}
};
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
}
public void generateShape(Graphics2D g)
{
//demo shape
int radius = rand.nextInt(200);
int originX,originY;
originX = rand.nextInt(300-10) + 10;
originY = rand.nextInt(300-10) + 10;
g.setStroke(new BasicStroke(5));
g.drawOval(originX, originY, radius, radius);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new DrawGraph();
}
}
这里输出: 我想尽可能多地使用余下的空间。