如何将对象放入面板?

How to put Object into a panel?

所以我有一个对象列表,具有随机的高度和重量。我还将这些对象的随机数放入一个变量中。

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

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

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

我的集团class:

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);   
}

我还有第三个 class,我将其称为 GUI class :

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

在上面的 class 中,我需要做我想做的事。

我没有在这里写我想做什么,因为我仍然不知道该怎么做。我是否应该为每个循环创建一个并获取块列表以及我希望将它们打印在面板上的每个块,并在块之间更改 x 和 y(fillRect 的)?我真的迷路了,我昨天想了想还是没有头绪..

亲切

I'm lost lol I do not understand everything in there since its with the click and so on

嗯,咔哒声确实和绘画概念无关。

绘画的概念是将要绘画的对象存储在ArrayList中。然后在 paintComponent() 方法中遍历 ArrayList 以绘制每个对象。

在我的示例中,您有一个方法 addRectangle(...),它一次添加一个 Rectangle 对象。您可以在不使用鼠标的情况下通过调用此方法来手动添加一个 Rectangle。这允许您添加不同 size/location/color.

的矩形

例如你只需将代码改成如下:

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. 您需要一种方法来将要绘制的对象添加到 class
  2. 然后您需要在 paintComponent() 方法中绘制这些对象。您不能按照当前的方式对绘画进行硬编码。

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