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

2014/1/6

How to use mouseClicked() with the World

1
2
danpost danpost

2014/1/6

#
You could post what the problem actually was so that other may learn from your experience.
JasonZhu JasonZhu

2014/1/6

#
  

    public MagneticField()
    {
        GreenfootImage img = new GreenfootImage(50,50);
        img.setColor(Color.CYAN);
        img.fillOval(0,0,50,50);
        setImage(img);
        age=0;
    }

    public void act()
    {
            addMagneticField();
    }  

public void addMagneticField()
    {
        MouseInfo mouse = Greenfoot.getMouseInfo();
        if(mouse==null)return;
        int x = mouse.getX();
        int y = mouse.getY();        
        if(Greenfoot.mouseClicked((Actor)getWorld())){
            getWorld().addObject(new MagneticField(),x,y);
        }
Basically, I wanted to add a MagneticField() at the location of the mouse when ever I clicked. My code at that point was inside the MagneticField class itself. I thought that the mouseClicked() method had to have an Actor parameter and thus, when I tried casting Actor to getWorld(), I recieved and error, but from bourne:
bourne wrote...
mouseClicked(java.lang.Object obj) True if the mouse has been clicked (pressed and released) on the given object.
No, it requires an Object. So it accepts Worlds as well
bourne wrote...
Where does add() get called from? And note at line 8, getWorld() could possibly return null. Also note mouseClicked can accept null - which case will return true if the mouse clicked anywhere in the scenario.
I leaned that any Object would pass in the parameter, including the World itself and "null"; null being a parameter that allows you to click on anything inside my Greenfoot window. In my case, it did not matter, so I changed my previous code of the addMagneticField() method to:
    

public void addMagneticField()
    {
        MouseInfo mouse = Greenfoot.getMouseInfo();
        if(mouse==null)return;
        int x = mouse.getX();
        int y = mouse.getY();        
        if(Greenfoot.mouseClicked(null)){
            getWorld().addObject(new MagneticField(),x,y);
        }
    }
However, no matter how I clicked anywhere in my window, nothing happened. So I did some testing and I added a MagneticField to the world manually and only then when I click that a MagneticField is added. At that point danpost informed me that:
danpost wrote...
If you do not have a MagneticField object in the world, then the act method is never executed and therefore your mouse clicks will be ignored.
In the end, my problem was the fact that I had my addMagneticField() method in the MagneticField class itself. I moved my code into my World and it worked fine. So, all in all, don't pull the same silly mistakes as I!
You need to login to post a reply.
1
2