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

2019/6/18

Getting image name of an object from a different class

CP7 CP7

2019/6/18

#
So I have a deck in the middle and 14 card objects in total on the screen. In the deck class, I want it so when a card object is clicked, it gets the image name of the object. All the card objects were initially created, so I can't get a reference to a card object. So in sum, i need to know if (Greenfoot.mouseClicked(somehow reference a card object)); and that is in the Deck class
danpost danpost

2019/6/18

#
There is probably an easier why, but from what you describe, I believe you would get the reference this way:
if (Greenfoot.mouseClicked(null))
{
    Object obj = Greenfoot.getMouseInfo().getActor();
    if (obj != null && (obj instanceof Card))
    {
        Card card = (Card)obj;
        ... // work on 'card' here
    }
}
danpost danpost

2019/6/18

#
CP7 wrote...
The card objects are from the Card class
I kind of figured and have already edited my code above.
CP7 CP7

2019/6/18

#
Would you mind explaining what (Card)obj does?
CP7 CP7

2019/6/18

#
It worked. Thank you so much!
danpost danpost

2019/6/18

#
CP7 wrote...
Would you mind explaining what (Card)obj does?
At line 3, obj is declared to be of type Object (the base type for all class instances). It cannot be Card there because we do not know that the object clicked on was a Card object yet. Once we determine that it was an instance of Card, we can then assign that reference to a variable of type Card. We cannot just assign any object to a variable that is to hold a Card reference, so we must first inform the system that it is indeed a Card object before assigning it to the variable card. This is called type-casting. If the only thing you needed from the card was its image, then type-casting to Actor would be sufficient:
Actor card = (Actor)obj;
however, if you require the use of any method or field value from the Card class itself, that would not suffice.
CP7 CP7

2019/6/18

#
Thank you!
You need to login to post a reply.