使用 Java 将多个图像添加到 GPanel
Adding multiple images to GPanel with Java
我正在 java 中为学校制作二十一点游戏,但我似乎无法弄清楚如何将前四张牌添加到 GPanel。卡片数组被打乱,数组中的字符串与图像的文件名相匹配。我可以加载阵列中的第一张卡,但不能加载其他三张。任何帮助都会很棒。
public void paintComponent(Graphics g) {
//System.out.println(gameInProgress);
if(gameInProgress == true) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Image image = null;
int i;
currentPosition = 0;
for (i = 0; i < 4; i++) {
image = Toolkit.getDefaultToolkit().getImage("images/"+deck[currentPosition - i]+".png");
currentPosition++;
}
g2.drawImage(image, 115, 5, 80, (int) 106.67, this);
g2.finalize();
}
}
您的代码中存在 3 个主要问题。
第一个问题是由 [currentPosition - i]
引起的,因为结果总是等于 0,所以数组索引 0 处的 image/card 将是唯一被绘制的。
第二个问题是您只绘制了一张图像,因为 g2.drawImage 仅在 for 循环之后被调用,而不是它应该在 for 循环内部,以便绘制所有 4 images/cards。
第三个问题是你总是在同一个地方画图,所以即使你画了所有 4 张图你也只会看到最后一张,因为它覆盖了之前的图。
试试这个,它应该打印所有 4 个图像(假设您有一个 435x112 面板):
public void paintComponent(Graphics g) {
//System.out.println(gameInProgress);
if(gameInProgress == true) {
super.paintComponent(g);
//Add a couple new variables
int x = 115;
Graphics2D g2 = (Graphics2D) g;
Image image = null;
int i;
for (i = 0; i < 4; i++) {
image = Toolkit.getDefaultToolkit().getImage("images/"+deck[i]+".png");
//New location of g2.drawImage
//The X positions should change each time
g2.drawImage(image, x, 5, 80, 107, this);
//Change the X location of the next image
x = x + 80;
}
//Moved g2.drawImage from here to above the bracket
g2.finalize();
}
}
我正在 java 中为学校制作二十一点游戏,但我似乎无法弄清楚如何将前四张牌添加到 GPanel。卡片数组被打乱,数组中的字符串与图像的文件名相匹配。我可以加载阵列中的第一张卡,但不能加载其他三张。任何帮助都会很棒。
public void paintComponent(Graphics g) {
//System.out.println(gameInProgress);
if(gameInProgress == true) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Image image = null;
int i;
currentPosition = 0;
for (i = 0; i < 4; i++) {
image = Toolkit.getDefaultToolkit().getImage("images/"+deck[currentPosition - i]+".png");
currentPosition++;
}
g2.drawImage(image, 115, 5, 80, (int) 106.67, this);
g2.finalize();
}
}
您的代码中存在 3 个主要问题。
第一个问题是由 [currentPosition - i]
引起的,因为结果总是等于 0,所以数组索引 0 处的 image/card 将是唯一被绘制的。
第二个问题是您只绘制了一张图像,因为 g2.drawImage 仅在 for 循环之后被调用,而不是它应该在 for 循环内部,以便绘制所有 4 images/cards。
第三个问题是你总是在同一个地方画图,所以即使你画了所有 4 张图你也只会看到最后一张,因为它覆盖了之前的图。
试试这个,它应该打印所有 4 个图像(假设您有一个 435x112 面板):
public void paintComponent(Graphics g) {
//System.out.println(gameInProgress);
if(gameInProgress == true) {
super.paintComponent(g);
//Add a couple new variables
int x = 115;
Graphics2D g2 = (Graphics2D) g;
Image image = null;
int i;
for (i = 0; i < 4; i++) {
image = Toolkit.getDefaultToolkit().getImage("images/"+deck[i]+".png");
//New location of g2.drawImage
//The X positions should change each time
g2.drawImage(image, x, 5, 80, 107, this);
//Change the X location of the next image
x = x + 80;
}
//Moved g2.drawImage from here to above the bracket
g2.finalize();
}
}