用不同的图像填充二维 JButton 数组
fill a 2-dimensional JButton Array with different images
我正在制作游戏中的一个小彩蛋,this is how it looks. If the player clicks a specific button 5 times, every button that is not black get's a different picture. So far I managed to make it look like this 其中每个按钮都有相同的图片。
图像和更改每个按钮图像的代码是这样的:
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
图像存储在看起来像 this 的文件夹中,其中 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 开始,你必须在末尾添加 1 i*5 + j + 1
我正在制作游戏中的一个小彩蛋,this is how it looks. If the player clicks a specific button 5 times, every button that is not black get's a different picture. So far I managed to make it look like this 其中每个按钮都有相同的图片。
图像和更改每个按钮图像的代码是这样的:
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
图像存储在看起来像 this 的文件夹中,其中 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 开始,你必须在末尾添加 1 i*5 + j + 1