【发布时间】:2014-06-09 22:59:43
【问题描述】:
我是一名初级程序员,我想让我的代码更高效。我将如何从 PIECE1 - PIECE 8 最终整数中创建一个数组,以及从 image1 - image8 中创建一个数组。此外,我如何使用所述数组调用 g.drawImage 一次而不是 8 次。
public class GraphicalBoard extends Board {
final int PIECE1 = 1;
final int PIECE2 = 2;
final int PIECE3 = 3;
final int PIECE4 = 4;
final int PIECE5 = 5;
final int PIECE6 = 6;
final int PIECE7 = 7;
final int PIECE8 = 8;
final int NO_OF_PIECES = 8;
Image image1, image2, image3, image4, image5, image6, image7, image8;
final int SQUARE_SIZE = 200; // The length (in pixels) of the side of each
public GraphicalBoard() {
super();
loadResources();
}
private void loadResources() {
image1 = new ImageIcon("picOne.gif").getImage();
image2 = new ImageIcon("picTwo.gif").getImage();
image3 = new ImageIcon("picThree.gif").getImage();
image4 = new ImageIcon("picFour.gif").getImage();
image5 = new ImageIcon("picFive.gif").getImage();
image6 = new ImageIcon("picSix.gif").getImage();
image7 = new ImageIcon("picSeven.gif").getImage();
image8 = new ImageIcon("picEight.gif").getImage();
}
public void draw(Graphics g) {
// Draw the board with current pieces.
for (int row = 0; row < board.length; row++)
for (int column = 0; column < board[row].length; column++) {
// Find the x and y positions for each row and column.
int xPos = column * SQUARE_SIZE;
int yPos = row * SQUARE_SIZE;
if (board[row][column] == PIECE1)
g.drawImage(image1, xPos, yPos, null);
else if (board[row][column] == PIECE2)
g.drawImage(image2, xPos, yPos, null);
else if (board[row][column] == PIECE3)
g.drawImage(image3, xPos, yPos, null);
else if (board[row][column] == PIECE4)
g.drawImage(image4, xPos, yPos, null);
else if (board[row][column] == PIECE5)
g.drawImage(image5, xPos, yPos, null);
else if (board[row][column] == PIECE6)
g.drawImage(image6, xPos, yPos, null);
else if (board[row][column] == PIECE7)
g.drawImage(image7, xPos, yPos, null);
else if (board[row][column] == PIECE8)
g.drawImage(image8, xPos, yPos, null);
}
}
}
【问题讨论】: