非静态变量pRefix无法从静态上下文引用

时间:2013-05-04 18:33:25

标签: java variables compiler-errors

我正在尝试在方法setFavoritePicture (Picture pRef)中设置图片。 这个方法应该设置一个在main方法中调用的最喜欢的图片,但是我不断收到编译错误nonstatic variable pRef cannot be referenced from a static context。我对java比较新,所以你能提供给我的任何帮助都会非常感激

public class House
{
 String owner;
 Picture pRef;
 Picture [] picArray;
 Picture favPic;

 public void showArtCollection ()
  {

   ArtWall aWall = new ArtWall(600,600);
   aWall.copyPictureIntoWhere(favPic,250,100);
   aWall.copyPictureIntoWhere(picArray[0],51,330);
   aWall.copyPictureIntoWhere(picArray[1],151,330);
   aWall.copyPictureIntoWhere(picArray[2],351,280);
   aWall.show();

  }



 public House (String param)
 {

  this.owner = param;
  this.picArray = new Picture [3];
  this.favPic = new Picture (FileChooser.pickAFile ());
  this.picArray [0] = new Picture (FileChooser.pickAFile ());
  this.picArray [1] = new Picture (FileChooser.pickAFile ());
  this.picArray [2] = new Picture (FileChooser.pickAFile ());




 }

public void setFavoritePicture (Picture pRef)
{
 pRef = favPic;
}

public void setOneOtherPicture (int which,Picture pRef)
{

}


public void swapGivenOtherWithFavorite (int which)
 {
  Picture tempSaver;
  tempSaver = pRef;
  pRef = picArray [which];
  picArray [which] = tempSaver;
 }


public void addPicture (Picture pictureAdded)
{
 pRef = pictureAdded;


}

public void showPicture ()
{

 picArray [0].explore ();
 picArray [1].explore ();
 picArray [2].explore ();
 favPic.explore ();


}


public static void main (String [] args)
 {
  House PhDsHouse = new House ("Mad PH.D.");
  PhDsHouse.setFavoritePicture (pRef);
  PhDsHouse.swapGivenOtherWithFavorite (2);
  PhDsHouse.showArtCollection ();


 }

}

1 个答案:

答案 0 :(得分:1)

我看到的错误如下:

PhDsHouse.setFavoritePicture (pRef); pRef中定义main的位置?因此,您在该声明中收到错误。

我猜,您要创建新的Picture对象,然后使用PhDsHouse将其分配给setFavoritePicture。这是真的?如果是,您需要在Picture pRef = new Picture();之前执行setFavoritePicture之类的操作......那么您应该做得很好。

此外,以下功能对我来说非常可疑

public void setFavoritePicture (Picture pRef)
{
 pRef = favPic;
}

这应该是

 public void setFavoritePicture (Picture  favPic)
    {
     pRef = favPic;
    }

因为,我没有看到您的代码中已定义/初始化favPic的位置....否则,当您NULL pointer exceptions访问pRef时,您将获得favPicNULL,将分配给pRef