Java 图像显示赢得';依赖变量名时不起作用

Java 图像显示赢得';依赖变量名时不起作用,java,image,swing,Java,Image,Swing,我正在用Java开发一个小游戏,我需要显示一个图像。此映像位于我磁盘上的一个sprite文件夹中。基本上,我有这样的结构: public class mainClass extends JFrame { private int imageType; // The type of the image public mainClass() { windowContent = new WindowContent(gameBoard, nextPiece); th

我正在用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

int
是一种基本类型,因此通过更改主类中
imageType
的值,您不会更改
windowContent
中的
imageType
。您需要直接在WindowContent上设置imageType。代码是否引发任何异常?我注意到你正在阅读“srprites”文件夹,你是想键入“sprites”,还是收到了任何FileNotFoundExceptions?是的,是sprites,是我的错别字。关于异常,它都是在完整的程序中处理的,我只想简短一点,我在做这个时遇到了一个非常奇怪的问题。我添加了一个标准setter方法
public void setImageType(int newType)…
并且我无法编译:错误:无法解析方法setImageType(int)。这里有封装或公开问题吗?应该没有问题。我看你接受了答案。您找到问题所在了吗?是的,我忘了添加解决方案:我正在使用
JPanel windowContent=new…
instate of
windowContent windowContent=new…
强制转换我的windowContent对象。现在一切正常。谢谢