一次声明多个 swing 元素

Declare multiplie swing elements at once

我正在开发一个小游戏,一个 Java IT 项目-类。

至add/declare(???) Java swing元素我用过这种写法:

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


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

为了代码不会变得更长(更)混乱,我继续这样写:

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.
 */

我的问题是:

有没有更短的方法来同时 add/declare(???) 多个 Java 摆动元素?

//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

或者 Whosebug 中是否已经有一个我没有找到的半问题?

编辑

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

此处Link问题

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.

不适用于 Jbuttons 和 JLabels。

如果你想在一个程序中多次做同样的事情(或类似的事情),答案是使用某种循环。在这里,您可以声明 JButton 元素的数组(或列表),并循环遍历它以初始化其元素:

final int NUM_BUTTONS = 6;
JButton[] buttons = new JButton[NUM_BUTTONS];
for (int i = 0; i < NUM_BUTTONS; i++) {
  buttons[i] = new JButton();
}

// refer to A as buttons[0], C as buttons[2], etc

您可以在声明变量后使变量彼此相等。

String one, two, three;
one = two = three = "";

所以,我认为你可以做到

JLabel A,B,C,D,E,F;
A = B = C = D = E = F = new JLabel();

如果您使用的是 Java 8,您可以使用:

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

来自本书Java se 8 for the really impatient


那么你可以使用:

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

视情况而定,如果您的所有对象都是 JLabel 或相同的对象类型,您可以尝试:

  • JLabel 的数组,例如:

    JLabel[] labels = new JLabel[size of your array];
    

    然后在 for 循环之后访问它:

    for (int i = 0; i < labels.length; i++) {
        labels[i] = new JLabel("I'm label: " + i);
    }
    
  • 一个 List 个标签:

    ArrayList <JLabel> labelsList = new ArrayList <JLabel>();
    

    那么你可以:

    for (int i = 0; i < 10; i++) { //I take 10 as an arbitrary number just to do it in a loop, it could be inside a loop or not
        labelsList.add(new JLabel("I'm label-list: " + i));
    }
    

稍后您可以像这样添加它们:

pane.add(labels[i]); //Array
pane.add(labelsList.get(i)); //List

上面的代码应该在一个循环中,或者更改i 以获得要添加的元素的显式索引。