如何使用此标签制作循环,而不是创建40行代码"重复"它们
jLabel1.setIcon(new ImageIcon(getClass().getResource("/cards/"+cards.get(1)+".png")));
jLabel2.setIcon(new ImageIcon(getClass().getResource("/cards/"+cards.get(1)+".png")));
jLabel3.setIcon(new ImageIcon(getClass().getResource("/cards/"+cards.get(2)+".png")));
jLabel4.setIcon(new ImageIcon(getClass().getResource("/cards/"+cards.get(3)+".png")));
Run Code Online (Sandbox Code Playgroud)
你写了一个循环.所以设置i为0(int i=0),当它小于40(i<40)时,继续循环,每个循环加1到i(i++)
for (int i=0; i<40; i++)
{
}
Run Code Online (Sandbox Code Playgroud)
然后插入要循环的代码,使用更改i来索引要索引的任何内容
for (int i=0; i<40; i++)
{
//do something with i - which is increased by one every loop through
}
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您需要创建一堆标签,尽管如此
JLabel[] jLabels = new JLabel[40];
Run Code Online (Sandbox Code Playgroud)
然后,您可以索引循环内的每个标签
//Notice there are two uses of the i variable here
String imageLocation = "/cards/" + cards.get(i) + ".png";
ImageIcon icon = new ImageIcon(getClass().getResource(imageLocation));
jLabels[i].setIcon(icon);
Run Code Online (Sandbox Code Playgroud)
但是你需要有一个简单的循环(在上面的那个之前......或者在它之内)以便jLabels用new JLabel()对象填充数组.我已经为您提供了所需的所有工具.