This site requires JavaScript, please enable it in your browser!
Greenfoot back
Newbie
Newbie wrote ...

2015/12/26

Selection of objects

Newbie Newbie

2015/12/26

#
Hey guys, I have yet another question: I got a class called "Profile.class". When being clicked on, it changes its image, a plain white square with a width of 14 Pixel, to the same image with a green cross on it. I also implemented a method, that changes the boolean named "selected" with the changing image. For my programme it is crucial that just one Object can be selected at a time or that it tells me otherwise. How can I manage to do this?
danpost danpost

2015/12/26

#
A class field to hold a reference to the selected object might be handy here. Add to the Profile class, the following field:
1
private Profile selection;
When an object of the class is clicked on, set the value of the field to reference to object clicked on:
1
if (Greenfoot.mouseClicked(this)) selection = this;
Finally, use the field in conjunction with your 'selected' boolean to determine the image of the actors of the class:
1
2
3
4
5
if (selected != (selection == this)) // change in selecting (selected or de-selected) of this actor
{
    selected = (selection == this); // update selecting of this actor
    setImage(selected ? crossImg : plainImg); // adjust image names as needed
}
Newbie Newbie

2015/12/27

#
Thank you for your help, but for some reason your suggestion didn't work: I probably made a mistake somewhere. But I found another way of solving my problem: I added the static variable selectionCounter to the code of Profile.class. 1 is added to it when an image of one of the objects changes to the one with the cross (when it's been clicked at), and 1 gets subtracted when an object changes its image the other way round. This works better for me, but thanks anyway!
danpost danpost

2015/12/27

#
Newbie wrote...
Thank you for your help, but for some reason your suggestion didn't work
I did not work because, although I did specify a class field, I forgot to include the "static" modifier to the field declaration line.
Newbie wrote...
I added the static variable selectionCounter to the code of Profile.class. 1 is added to it when an image of one of the objects changes to the one with the cross (when it's been clicked at), and 1 gets subtracted when an object changes its image the other way round. This works better for me, but thanks anyway!
Okay -- the way you ended up with allows that there are times when none of the Profile actors are selected (the way I provided, when corrected, only allows a situation where none is selected at the start; once one is selected, one will always be selected from then on).
You need to login to post a reply.