就像是
String imageName = null;
if (guesses >= 1) imageName = "Head.jpg";
if (guesses >= 2) imageName = "Body.jpg";
if (guesses >= 3) imageName = "LeftArm.jpg";
if (guesses >= 4) imageName = "RightArm.jpg";
if (guesses >= 5) imageName = "LeftLeg.jpg";
if (guesses >= 6) imageName = "RightLeg.jpg";
ImageIcon icon = null;
if (imageName != null) {
icon = new ImageIcon(Path + File.seperator + imageName);
}
label.setIcon(icon);
显然,每个图像都需要相互添加......
更新
正如 PaulBellora 非常友好地指出的那样,前面的示例是满足 OP 要求的最简单的代码更改,但这并不意味着它是正确的
switch (guesses) {
case 1:
imageName = "Head.jpg";
break;
case 2:
imageName = "Body.jpg";
break;
case 3:
imageName = "LeftArm.jpg";
break;
case 4:
imageName = "RightArm.jpg";
break;
case 5:
imageName = "LeftLeg.jpg";
break;
case 6:
imageName = "RightLef.jpg";
break;
}
会是一个稍微好一点的方法。
通过一些巧妙的布局管理,你可以有六个标签,每个身体部位一个......
// Global references to the body parts
public static final ImageIcon RIGHT_LEG_ICON = new ImageIcon(Path + File.seperator + "RightLeg.jpg");
public static final ImageIcon LEFT_LEG_ICON = new ImageIcon(Path + File.seperator + "LeftLeg.jpg");
public static final ImageIcon RIGHT_ARM_ICON = new ImageIcon(Path + File.seperator + "RightArm.jpg");
public static final ImageIcon LEFT_ARM_ICON = new ImageIcon(Path + File.seperator + "LeftArm.jpg");
public static final ImageIcon BODY_ICON = new ImageIcon(Path + File.seperator + "Body.jpg");
public static final ImageIcon HEAD_ICON = new ImageIcon(Path + File.seperator + "Head.jpg");
// Used as fillers to allow the layout manager to maintain the layout
public static final ImageIcon BLANK_LEG_ICON = new ImageIcon(Path + File.seperator + "BlankLeg.jpg");
public static final ImageIcon BLANK_ARM_ICON = new ImageIcon(Path + File.seperator + "BlankArm.jpg");
public static final ImageIcon BLANK_BODY_ICON = new ImageIcon(Path + File.seperator + "BlankBody.jpg");
public static final ImageIcon BLANK_HEAD_ICON = new ImageIcon(Path + File.seperator + "BlanHead.jpg");
...
// Setup the initial state...(probably in the constructor or when the game rests)
rightLegLabel.setIcon(BLANK_LEG_ICON);
leftLegLabel.setIcon(BLANK_LEG_ICON);
rightArmLabel.setIcon(BLANK_ARM_ICON);
leftArmLabel.setIcon(BLANK_ARM_ICON);
bodyLabel.setIcon(BLANK_BODY_ICON);
headLabel.setIcon(BLANK_BODY_ICON);
...
// As the guesses change...
switch (guesses) {
case 6:
rightLegLabel.setIcon(RIGHT_LEG_ICON);
case 5:
leftLegLabel.setIcon(LEFT_LEG_ICON);
case 4:
rightArmLabel.setIcon(RIGHT_ARM_ICON);
case 3:
leftArmLabel.setIcon(LEFT_ARM_ICON);
case 2:
bodyLabel.setIcon(BODY_ICON);
case 1:
headLabel.setIcon(HEAD_ICON);
}