用不同的图像填充二维 JButton 数组



我正在制作游戏中的一个小复活节彩蛋,这就是它的样子。如果玩家单击特定按钮 5 次,则每个非黑色按钮都会获得不同的图片。到目前为止,我设法让它看起来像这样,每个按钮都有相同的图片。

图像和更改每个按钮的图像的代码是这样的:

BufferedImage img = ImageIO.read(new File("kronk/18.png"));
for (int i = 0; i < buttons.length; i++) { //Goes one time through the complete Array
for (int j = 0; j < buttons[i].length; j++) {
if(buttons[i][j].getBackground() != Color.black) {
buttons[i][j].setText("");
buttons[i][j].setIcon(new ImageIcon(img));
}
}
}

到目前为止,代码被硬编码为始终显示 18.png

图像存储在如下所示的文件夹中,其中 1.png 在按钮 1 上,2.png 转到 2,依此类推......

用相应的图像填充每个按钮的最佳方法是什么?

试试这个:

for (int i = 0; i < buttons.length; i++) { //Goes one time through the complete Array
for (int j = 0; j < buttons[i].length; j++) {
if(buttons[i][j].getBackground() != Color.black) {
BufferedImage img = ImageIO.read(new File("kronk/"+(i*5 + j + 1)+".png"));
buttons[i][j].setText("");
buttons[i][j].setIcon(new ImageIcon(img));
}
}
}

由于您有一个 5x5 数组i*5 + j因此将为您提供从 0 到 24 的枚举计数。但是,由于图片的枚举以 1 开头,因此您必须在末尾添加一个i*5 + j + 1

最新更新