Search code examples
javaswingdeclare

Declare multiplie swing elements at once


I am working on a little game, a Java project for IT-classes.

To add/declare(???) Java swing elements I've used this type of writing:

JLabel A = new JLabel();
JLabel B = new JLabel();
//More JLabels...


JButton A = new JButton();
JButton B = new JButton();
//More JButtons...

That the code does not become longer and (more) confusing, I continued with this type of writing:

JLabel A = new JLabel(), B = new JLabel()/*More JLabels...*/;

JButton A = new JButton(), B = new JButton()/*More JButton...*/;

/*Generaly more comments everywhere over the code for my teacher (and me)
 *and more for a better overview.
 */

My question is:

Is there a shorter way to add/declare(???) multiple Java swing elements at once?

//like this
JLabel A, B, C, D, E, F = new JLabel();
//or
new JLabel[A, B, C, D, E, F];//PLS don't ask what I'm doing in this line xD

or may is there already a semilar question in Stackoverflow that I've not found?

Edit

This question may already have an answer here: Initializing multiple variables to the same value in Java 6 answers

Here the Link to the question

Your question has been identified as a possible duplicate of another question. If the answers there do not address your problem, please edit to explain in detail the parts of your question that are unique.

Not worked with Jbuttons and JLabels.


Solution

  • If you are using Java 8 you can use :

    List<String> labels = ....;
    Stream<Button> stream = labels.stream().map(Button::new);
    List<Button> buttons = stream.collect(Collectors.toList());
    

    From the book Java se 8 for the really impatient


    Then you can use :

    JPanel p = new JPanel();
    buttons.forEach((t) -> p.add(t));//add your buttons to your panel