简体   繁体   中英

Add JLayeredPane Swing to JPanel

I have a "Illegal Component Position" in my method, have you an idea why i have this ?

I execute this methode for placing a ImageIcon and also set Z axis for an ImageIcon.

    public void Placer(ImageIcon a, int x, int y, int z) {
    JPanel panel = (JPanel) this.getContentPane();

    JLayeredPane lp =  getLayeredPane();
    lp.setPreferredSize(new Dimension(100,100));

    panel.setLayout(null);
    JLabel image = new JLabel(a);
    panel.add(image);
    Dimension size = image.getPreferredSize();
    image.setBounds(x, y, size.width, size.height);
    lp.add(panel, new Integer(z));

}

When i call

        for (int y = 0,y1=0; y < 910; y += 35,y1++) {
        for (int x = 0,x1=0; x < 910; x += 35,x1++) {
            Placer(this.affichageBatiment[x1][y1], x, y, -5);
            Placer(this.affichageAgentEquipe1[x1][y1], x, y,-3);
            Placer(this.affichageAgentEquipe2[x1][y1],x,y,-2);

        }
    }

PS : all the 2d arrays are arrays of ImageIcon and i have this error

Exception in thread "main" java.lang.IllegalArgumentException: illegal component position
at java.awt.Container.addImpl(Container.java:1098)
at javax.swing.JLayeredPane.addImpl(JLayeredPane.java:231)
at java.awt.Container.add(Container.java:975)
at Fenetre.Placer(Fenetre.java:69)
at Fenetre.afficherTout(Fenetre.java:146)
at Fenetre.<init>(Fenetre.java:54)
at Tournoi.LancerTournoi(Tournoi.java:34)
at Main.main(Main.java:14)

The method you want to call in your last line of Placer -method is Component.add(Component comp, int index); With index being:

index - the position at which to insert the component, or -1 to append the component to the end

So, with lp.add(panel, -1); you get rid of the Exception .

I am not sure, why you call it with wrapper object Integer but please note that in effect you are calling Component.add(Component comp, Object constraints); because Integer is an Object . Here, the object is supposed to be

constraints - an object expressing layout constraints for this component

And because Integer is not a valid layout constraints object, the IllegalArgumentException is thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM