java - 一次声明多个 swing 元素

标签 java swing declare

我正在开发一个小游戏,一个面向 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/

相关文章:

java - 异构二叉搜索树

java - 并行度为 1 的串行和并行执行之间的区别

java - repaint() 不在线程中工作

TypeScript 定义对象结构供以后使用

java - 如何用普通矩形轮廓在java中绘制一个圆角矩形

java - Java 中数组的模式 - 方法

Java 通过单击按钮隐藏由类扩展的 JFrame

java - Swing RTF 编辑组件 - RTFEditorkit 的替代品?

javascript - 在 Angular 2/typescript 中声明 javascript 方法以避免属性 x 不存在错误

c - 声明相互使用的结构和函数引用