Java如何使此代码更简单,更短

时间:2019-03-24 03:19:41

标签: java swing

我正在使用swing组件创建测验程序。我想编写一个代码,声明所有设计,例如背景色,并将其用于我创建的所有框架,这样我的代码将更简单,更短。

我已经试图一一声明。

contentPane1.setBackground(Color.PINK);
contentPane2.setBackground(Color.PINK);
contentPane3.setBackground(Color.PINK);
contentPane4.setBackground(Color.PINK);
contentPane5.setBackground(Color.PINK);

我必须创建10个帧,并且使用这种代码将非常长。我不知道该怎么做,我只是一个初学者。谢谢:)

1 个答案:

答案 0 :(得分:3)

您可以使用内容窗格中的Stream并用setBackground之类的方式调用forEach

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));
相关问题