如何将对象放入面板?

时间:2018-11-28 14:53:16

标签: java swing arraylist panel

所以我有一个对象列表,其高度和重量随机。我也有一个随机数的那些对象到一个变量。

我想做的是将所有这些对象打印到正确的面板中(我有2个面板)。

首先,我的GUI和对象类(块)是2个单独的类。进入GUI,我正在这样做:

    private JPanel initPanelBloc() {
    panelBloc = new JPanel();
    bloc = new Bloc(false);
    panelBloc.add(bloc);
    return panelBloc;
    }

我的Bloc类:

public class Bloc extends JPanel{
private int hauteur, largeur, nombreBloc;
private boolean premierPassage = true;
private ArrayList<Bloc> listeBlocRestant;
private Random rand = new Random();

public Bloc(boolean premierPassage) {
    this.hauteur = 10 + rand.nextInt(50 - 10);
    this.largeur = 10 + rand.nextInt(50 - 10);      
    listeBlocRestant = new ArrayList<Bloc>();
    if(premierPassage == true) {
        this.nombreBloc = 5 + rand.nextInt(30 - 5);
        insererBlocList();
    }
}

public ArrayList<Bloc> insererBlocList(){
    premierPassage = false;
    for(int i=0; i<nombreBloc; i++) {       
        Bloc bloc = new Bloc(false);
        listeBlocRestant.add(bloc);
    }
    return listeBlocRestant;
}

public void paintComponent(Graphics2D g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.fillRect(10, 20, this.largeur, this.hauteur);   
}

我还有一个第三类,我称之为GUI类:

    public Optimisation() {
    this.aff = new InterfaceGraphique();
}

在上一课中,我需要做我想做的事。

我没有写我想做的事情,因为我仍然不知道该怎么做。我是否应该为每个循环创建一个,并获取块列表以及要让它们在面板上打印的每个块,并在块之间更改x和y(fillRect的值)?我真的迷路了,昨天我试图考虑一下,但仍然没有头绪。

私下

1 个答案:

答案 0 :(得分:0)

  

我迷路了大声笑,我不了解那里的一切,因为点击等等。

嗯,点击确实与绘画概念无关。

绘画概念是将要绘画的对象存储在ArrayList中。然后,在paintComponent()方法中,循环访问ArrayList以绘制每个对象。

在我的示例中,您有一个方法addRectangle(...),该方法一次添加一个Rectangle对象。您可以通过调用此方法而不使用鼠标来手动添加Rectangle。这样,您可以添加其他大小/位置/颜色的矩形。

例如,您只需按以下方式更改代码:

private static void createAndShowGUI()
{
    DrawingArea drawingArea = new DrawingArea();
    drawingArea.addRectangle(new Rectangle(10, 10, 200, 100), Color.RED);
    drawingArea.addRectangle(new Rectangle(210, 110, 20, 100), Color.BLUE);

现在,当您运行代码时,将出现红色矩形。

关键点是:

  1. 您需要一种将想要绘制的对象添加到班级的方法
  2. 然后,您需要在paintComponent()方法中绘制这些对象。您无法按照当前的方式对绘画进行硬编码。

在您的代码中,您的Bloc对象将需要包含绘制区块所需的信息。