Eveli
Eveli

Reputation: 498

Adding multiple items in a Panel At Once

just a short :)

I have

        panel8.add(label4).setVisible(true);
        panel8.add(panel4).setVisible(true);
        panel8.add(button1).setVisible(true);
        panel8.add(panel7).setVisible(true);

But I want to have something like this:

    panel8.add(label4, panel4, button1, panel7).setVisible(true);

How is the correct syntax? Or isn't it possible?

Thanks in advance.

Upvotes: 0

Views: 270

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347314

The short answer is, no, you can't do that, it's not how the API is designed.

You could create a utility method which could do it though, maybe something like...

public JComponent addTo(JComponent parent, JComponent... children) {
    if (children != null && children.length > 0) {
        for (JComponent child : children) {
            parent.add(child);
        }
    }
    return parent;
}

which you might be able to use something like...

addTo(Panel8, 
    GamulatorMain.Label4, 
    GamulatorMain.Panel4, 
    GamulatorMain.Button1, 
    GamulatorMain.Panel7).setVisible(true);

as an example

Upvotes: 2

dovetalk
dovetalk

Reputation: 1991

Some observations from your code:

  1. You're seem to be accessing global, static variables, that's a no-no
  2. Your variables start with an upper-case, that's non-standard in Java
  3. Please don't use numbers for multiple panels (panel4, panel8, ...). Instead name them according to what they are (e.g. buttonPanel, outputPanel...)

Instead, you'd be better off creating a custom class for the Panel8 container, e.g:

public class MyPanel extends Panel {
    public MyPanel() {
        //...instantiate label4
        add(label4);
        //...instantiate panel4
        add(panel4);
        //...instantiate button1
        add(button1);
        //...instantiate panel7
        add(panel7);
    }
}

Upvotes: 2

Related Questions