Hey,
could someone please tell me how I call a method when the player clicks at a text in my world?
Thanks


1 2 3 4 5 6 7 | if (Greenfoot.mouseClicked( this )) { MouseInfo mouse=Greenfoot.getMouseInfo(); int mX=mouse.getX(), mY=mouse.getY(); // with text top at 80, bottom at 100, left at 350, and right at 450 if (mX>= 350 && mX<= 450 && mY>= 80 && mY<= 100 ) methodName(); } |
1 | if (Greenfoot.mouseClicked( this )) methodName(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | import greenfoot.*; import java.awt.Color; public class Button extends Actor { private boolean clicked; String buttonText = "" ; public Button() { this ( "" ); } public Button(String text) { setText(text); } public void setText(String text) { buttonText=text; GreenfootImage textImg= new GreenfootImage( " " +text+ " " , 24 , Color.black, new Color( 0 , 0 , 0 , 0 )); GreenfootImage image= new GreenfootImage(textImg.getWidth()+ 8 , textImg.getHeight()+ 8 ); image.setColor(Color.darkGray); image.fill(); image.setColor(Color.lightGray); image.fillRect( 3 , 3 , image.getWidth()- 6 , image.getHeight()- 6 ); image.setColor(Color.black); image.drawImage(textImg, (image.getWidth()-textImg.getWidth())/ 2 , (image.getHeight()-textImg.getHeight())/ 2 ); setImage(image); } public void act() { if (Greenfoot.mouseClicked( this )) clicked= true ; } public boolean gotClicked() { boolean wasClicked=clicked; clicked= false ; return wasClicked; } public String getText() { return buttonText; } } |
1 2 3 4 5 6 7 | // an instance Button field private Button textButton= null ; // creating the button Button textButton= new Button( "Click here to run method" ); addObject(textButton, 500 , 30 ); // in the act to catch button click if (textButton.getWorld() != null && textButton.gotClicked()) methodName(); |