【发布时间】:2017-12-07 18:37:13
【问题描述】:
我正在尝试将一个小 burger.jpg img 添加到我正在制作的游戏中。每当在 Switch 中传递 'f'(food) 时,都应添加汉堡。我在我的代码中实现这一点时遇到问题。
我最初只是填充一个橙色矩形g2.fillRect(),但我想用实际图像替换它。我试过缩放图像并添加它,但它没有显示出来。如果我在 for 循环的末尾替换g2.fillRect,它会使每个方块都变成一个汉堡,而不仅仅是'f'
我该怎么做?
private class Game extends JPanel {
BufferedImage img = null;
@Override
public void paintComponent(Graphics g2) {
super.paintComponent(g2);
try {
img = ImageIO.read(new File("src/burger.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
BufferedImage otherImage = new BufferedImage(50, 50,
BufferedImage.TYPE_INT_RGB);
Graphics g = otherImage.createGraphics();
int width = getWidth() / game.getBoardWidth();
int height = getHeight() / game.getBoardHeight();
char[] symbols = game.toString().toCharArray();
int x = 0;
int y = 0;
for (char c : symbols) {
switch (c) {
case 'Q':
g2.setColor(Color.BLACK);
break;
case 'H':
g2.setColor(Color.GREEN);
break;
case 'f':
//g2.setColor(Color.ORANGE);
g2.drawImage(img, x, y, width, height, null);
break;
case '-':
g2.setColor(Color.WHITE);
break;
case '\n':
y += height;
x = 0;
}
//g2.drawImage(img, x, y, width, height, null);
g2.fillRect(x, y, width, height);
x += width;
}
}
}
【问题讨论】:
标签: java image swing switch-statement paintcomponent