Skip to content
Advertisement

I have a problem whith adding a Container in a JFrame

I am a student in informatics and beginning in Java, I want to create a project which will allow me to make a calculator.

I am encountering a problem which is the following: I want to add Container in my JFrame with add(contenu), but it gives me the following warning :

Exception in thread "main" java.lang.IllegalArgumentException: 
    adding container's parent to itself

I don’t understand why this problem appears.

Here are the class codes of my project:

class Main :

package com.company;

import javax.swing.*;

public class Main {

    public static void main(String[] args) {
    // write your code here
        Fenetre fen = new Fenetre();
        fen.setVisible(true);
    }
}

class Fenetre :

package com.company;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Fenetre extends JFrame {
    public JButton boutonsNombre[];
    private static int nChiffres = 10;

    public Fenetre() {
        setTitle("CALCULATRICE");
        setSize(1700, 900);
        Container contenu = getContentPane();
        contenu.setLayout(new FlowLayout());
        add(contenu);
        boutonsNombre = new JButton[nChiffres];
        for (int k = 0; k < nChiffres; k++) {
            boutonsNombre[k] = new JButton(String.valueOf(k+1));
            contenu.add(boutonsNombre[k]);
        }
    }
}

Have you any idea about why this problem appears?

Advertisement

Answer

As one of the comments already mentions you are trying to add the JFrame’s content pane to itself.

The following will work:

public Fenetre() {
        setTitle("CALCULATRICE");
        setSize(1700, 900);
        this.setLayout(new FlowLayout());
        boutonsNombre = new JButton[nChiffres];
        for (int k = 0; k < nChiffres; k++) {
            boutonsNombre[k] = new JButton(String.valueOf(k+1));
            this.add(boutonsNombre[k]);
        }
    }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement