I'm stuck on one problem with my code below. I keep getting a compiler error in the main method when im trying to call the setFavoritePicture
method. It says non-static variable favPic cannot be referenced from a static context. I'm relatively new to java so any help with this would be appreciated! Many thanks!
public class House
{
String owner;
Picture pRef;
Picture [] picArray;
Picture favPic;
public void setFavoritePicture (Picture pRef)
{
Picture favPic = new Picture (FileChooser.pickAFile ());
pRef = favPic ;
}
public static void main (String [] args)
{
House PhDsHouse = new House ("Mad PH.D.");
PhDsHouse.setFavoritePicture (favPic);
}
}
favPic
is a non-static instance member of the House
class and you are trying to reference it from within your static main
method. You need to create an instance of Picture
and pass that in instead:
Picture pic = new Picture(FileChooser.pickAFile ());
PhDsHouse.setFavouritePicture(pic);
However, it seems there are slightly deeper issues with this code, as your setFavoritePicture
method doesn't actually set favPic
according to the passed parameter, it sets it according to FileChooser.pickAFile
and then assigns that value back to the passed parameter (which achieves nothing).
Maybe you wanted to do something like this instead:
public void setFavoritePicture (Picture pRef)
{
favPic = pRef;
}
Update: Regarding your comment:
I need to, within the 'setFavoritePicture' method, pick a picture, using 'FileChooser.pickAFile ()'. Thats the whole point of this method.
In that case, why do you need a parameter at all? Perhaps something like this?
public class House
{
String owner;
Picture [] picArray;
Picture favPic;
public void setFavoritePicture ()
{
Picture pic = new Picture (FileChooser.pickAFile ());
this.favPic = pic;
}
... /* Rest of your class here */
public static void main (String [] args)
{
House PhDsHouse = new House ("Mad PH.D.");
PhDsHouse.setFavoritePicture();
}
}
In the above code, you instantiate your House
and then call its setFavoritePicture
method. If all of the logic behind creating a new picture is handled by that method, including the call to FileChooser.pickAFile
, then you don't need to pass anything to it.
Having said that, it seems to me that the responsibility of setFavoritePicture
should be to set the object's favourite picture and that handling file selection and user input should be done elsewhere (such as in my earlier example in which pRef
is instantiated outside of the method and passed in).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.