我正在使用 swing 组件创建一个测验程序。我想编写一个代码,我将声明所有设计,例如背景颜色,并将其用于我创建的所有框架,这样我的代码将更简单、更短。
我已经尝试一一声明了。
contentPane1.setBackground(Color.PINK);
contentPane2.setBackground(Color.PINK);
contentPane3.setBackground(Color.PINK);
contentPane4.setBackground(Color.PINK);
contentPane5.setBackground(Color.PINK);
我必须创建 10 个框架,使用这种代码将会非常长。我不知道该怎么做,我只是一个初学者。谢谢:)
最佳答案
您可以使用内容 Pane 的 Stream
并使用 forEach
调用 setBackground
;
Stream.of(contentPane1, contentPane2, contentPane3, contentPane4, contentPane5)
.forEach(p -> p.setBackground(Color.PINK));
使用数组可能会更好(十个);也许就像
JPanel[] panels = new JPanel[] { contentPane1, contentPane2, contentPane3,
contentPane4, contentPane5, contentPane6, contentPane7,
contentPane8, contentPane9, contentPane10
};
Arrays.stream(panels).forEach(p -> p.setBackground(Color.PINK));
关于java - 如何使这段代码更简单、更短,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55320449/