如何使这段代码更加简单和简短,Java

如何使这段代码更加简单和简短,Java,java,swing,Java,Swing,我正在使用swing组件创建一个测验程序。我想做一个代码,我将宣布所有的设计,如背景色,我将使用它的所有框架,我创造了这样我的代码将更简单,更短 我已经试着一个接一个地申报了 contentPane1.setBackground(Color.PINK); contentPane2.setBackground(Color.PINK); contentPane3.setBackground(Color.PINK); contentPane4.setBackground(Color.PINK); co

我正在使用swing组件创建一个测验程序。我想做一个代码,我将宣布所有的设计,如背景色,我将使用它的所有框架,我创造了这样我的代码将更简单,更短

我已经试着一个接一个地申报了

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

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

您可以使用内容窗格的
,并使用
forEach
等调用
setBackground

Stream.of(contentPane1, contentPane2, contentPane3, contentPane4, contentPane5)
        .forEach(p -> p.setBackground(Color.PINK));
使用数组可能更好(对于10个);也许像

JPanel[] panels = new JPanel[] { contentPane1, contentPane2, contentPane3, 
        contentPane4, contentPane5, contentPane6, contentPane7, 
        contentPane8, contentPane9, contentPane10
};
Arrays.stream(panels).forEach(p -> p.setBackground(Color.PINK));

请参见假设他们使用的是Java 11,他们可以很好地执行(..).forEach(..)列表,从而消除创建流或数组的需要。