Question

Beginner question . . . I want to run a boolean test on a GImage object, but I don't know how. For example, if my GImage is displaying "image1.jpg" file, I want to do 'a'. But if it is displaying anything else, I want to do 'b'. The images are being selected randomly by a different part of my program. The only way I can see to do this is to just create a placeholder String variable that I modify anytime that I change the GImage (and then I can just perform the test on the placeholder variable), but I'm sure is not the best way to do what I want. For example, the following would work, but because my actual program has a lot of relevant GImage objects and possible images, this approach would be very unwieldy:

GImage image1 = new GImage("bar.jpg", 0, 0);
int var1 = 0;
GImage image2 = new GImage("sunset.jpg", 100, 0);
int var2 = 1;
GImage image3 = new GImage("bar.jpg", 200, 0);
int var3 = 0;
if (var1 == 0) {
    // returns true
}
if (var2 == 0) {
    // returns false
}
if (var3 == 0) {
    // returns true
}

I am just learning to program, so there may be an obvious solution, but I can't seem to find it. If there was a method that returned the filename displayed by a GImage, that would seem accomplish what I need, but I couldn't find such a method. Thanks for your help.

Was it helpful?

Solution

You could wrap the image in your own class, which contains appropriate attributes.

Quick and dirty:

class MyImage
{
    private String resourceName;
    private GImage gImage;

    public MyImage(String resourceName,int x, int y){
        this.resourceName = resourceName;
        this.gImage = new GImage(resourceName,x,y)
    }

    public String getResourceName()
    {
        return resourceName;
    }

    //.
    //.
    //.
}


public static final String RES_IMG_SUNSET = "sunset.jpg";

//.
//.
//.

MyImage image1 = new MyImage("bar.jpg", 0, 0);
MyImage image2 = new MyImage(RES_IMG_SUNSET, 100, 0);
MyImage image3 = new MyImage("bar.jpg", 200, 0);

if(image2.getResourceName().equals(RES_IMG_SUNSET))
{
}

You might want to have some sort of unique resource names, so you could use normalized, canonical filenames or URI's. Another way would be to define a global constant for these names, as in above example. Of course, GImage must support that format.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top