gpt4 book ai didi

java - 依赖变量名时图像显示不起作用

转载 作者:行者123 更新时间:2023-12-01 13:16:02 25 4
gpt4 key购买 nike

我正在用Java开发一个小游戏,我需要显示一个图像。该图像位于我磁盘上的 Sprite 文件夹中。基本上,我有这样的结构:

public class mainClass extends JFrame {
private int imageType; // The type of the image
public mainClass() {
windowContent = new WindowContent(gameBoard, nextPiece);
this.setContentPane(windowContent);
while(!gameOver) {
this.imageType = otherClass.getImageType(); // Short version
this.repaint();
}
}

class WindowContent extends JPanel {
private int imageType;
public WindowContent(int imgType) {
this.imageType = imgType;
}
public void paintComponent(Graphics g) {
try {
BufferedImage img = ImageIO.read("srprites/" + this.imageType + ".png");
g.drawImage(img, 200,200, null);
} catch .......
}
}
}

问题是第一张图片正常显示,但是当变量内容改变时什么也没有发生。第一张图像保持不变。我尝试了很多方法,例如移动 this.setContentPane(),但没有任何效果。有没有办法让它正确工作?谢谢。

最佳答案

WindowContent 中的imageType 仅在构造函数中分配。通过更改主类中 imageType 的值,您不会更改 WindowContent 中的 imageType。您需要直接在 WindowContent 上设置 imageType

而不是

  while(!gameOver) { 
this.imageType = otherClass.getImageType(); // Short version
this.repaint();
}

你需要做

  while(!gameOver) { 
windowContent.setImageType(otherClass.getImageType()); // Short version
this.repaint();
}

当然,将 setter 添加到 windowContent

关于java - 依赖变量名时图像显示不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22463308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com