我正在开发一个小游戏,一个面向 IT 类(class)的 Java 项目。
要添加/声明(???)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.
*/
我的问题是:
是否有更短的方法来一次添加/声明(???)多个 Java swing 元素?
//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
或者 Stackoverflow 中可能已经有一个我没有找到的类似问题?
编辑
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。
最佳答案
如果您使用的是 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
关于java - 一次声明多个 swing 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43988344/