java - 如何使这段代码更简单、更短,Java

标签 java swing

我正在使用 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/

相关文章:

java - Hibernate Restrictions.isEmpty() 不工作

java - JDesktopPane ContainerListener 和 JInternalFrame 图标化事件

java - 如何将我的 JLabel 与其下方的 JLabel 行对齐

java - 在 Java 中创建 JButton

java - 在eclipse中编译java程序

java - 获取 CruiseControl.Net 以显示 Java 输出

java - "Linking"Java 中的 JComponent?

java - 使用 Swing GUI 在一个类中执行程序

java - 错误 :(24, 46) 错误 : diamond operator is not supported in -source 1. 6(使用 -source 7 或更高版本启用钻石运算符)

java - 我想在 Android Studio 中制作一个总统评论应用程序,其中包含每位总统的照片,但我不断收到 OutOfMemoryError