This is my idea for a Button class and I wanted to know if it is a good idea. I saw some ideas how to create Buttons, but nobody never really came up with a solution like this (as far as I know). However, I also wanted to know if there are improvements that could be made and if there is a way that the Button class doesn't need to inherit from the Actor class. Please reply.
This is the code from the Button class:
This is the subclass where you basically just perform the "buttonClicked" method in an if-condition to execute the method you want, when the button is clicked. I tested it with the "addObject" method:
There was something missing:
At the moment you need to add the Button Object in the your World class, because if you first add a button object and then run your scenario the button will execute the method directly even when you didn't click the button. Additionally, sometimes when you click the button nothing happens. Maybe somebody can tell me how to fix this. (I use this Button class in another scenario where it works perfectly fine so...)
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 50 51 52 53 | import greenfoot.*; /** * It creates an object where you can click on. * * @author Claw76 * @version 30.01.2019 */ public class Button extends Actor { private GreenfootImage unclickedImg; private GreenfootImage clickedImg; private GreenfootImage standardUnclickedImg = new GreenfootImage( "unclickedbuttonstandard.png" ); private GreenfootImage standardClickedImg= new GreenfootImage( "clickedbuttonstandard.png" ); public Button() { setUnclickedImg(standardUnclickedImg); setClickedImg(standardClickedImg); setImage(unclickedImg); } public void act() { } public boolean buttonClicked() //returns "True if Button is clicked and "False" if not { boolean isClicked= false ; if (!Greenfoot.mousePressed( this )) { setImage(unclickedImg); Greenfoot.delay( 4 ); isClicked= false ; } else if (Greenfoot.mouseClicked( this )) { setImage(clickedImg); isClicked= true ; } return isClicked; } public void setUnclickedImg(GreenfootImage img) { unclickedImg = img; } public void setClickedImg(GreenfootImage img) { clickedImg = img; } } |
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 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Its just an Test object of the Button class. * * @author Claw76 * @version 30.01.2019 * */ public class TestButton extends Button { /** * Act - do whatever the TestButton wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if (buttonClicked()) { //write the methods you want to execute when the button is clicked here getWorld().addObject( new Button(), 300 , 300 ); Greenfoot.delay( 2 ); } } } |