I'm working on a game (still in very early works) and I'm currently working on a MenuButton object. The MenuButton has a specific detail of the game it is supposed to affect (for this example, the left moving key). It is created with a Text object I've made that stays in the middle of the button. When you click on the button, the Text object is updated to display "". The whole program pauses until you press a key. Then the Text and the MenuButton objects are updated to the key you pressed. In the example before, the left moving key will now be equal to the key you pressed.
I have it working so far, except for a glitch where when you click on the button, it will change to the last key you pressed, and not wait for you to press a new key. I don't know why this is happening, could someone help me?
Here's the code for the MenuButton object:
public class MenuButton extends Button { private Text myText; private GameStats stats; private String myKey; private int changes; public MenuButton(String key, GameStats stats, int changes) { myKey = key.toUpperCase(); //The text look better in uppercase than lower case this.stats = stats; //The GameStats object that will be affected myText = new Text(myKey, Color.black); //Makes a black Text that will display myKey this.changes = changes; //Which element of the game will be affected. } public void whenDragged(){} //Part of the ButtonInterface class, not needed for this particular button public void whenHovered(){} //Part of the ButtonInterface class, not needed for this particular button /** * Act - do whatever the MenuButton wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if (isClicked()) whenClicked(); moveText(); } public void addText() { getWorld().addObject(myText, getX() + 10, getY()); } public void moveText() { myText.setLocation(getX() + 10, getY()); } public void whenClicked() { setKey(""); //Sets myKey to "" so nothing appears. String differentKey = Greenfoot.getKey(); //Should be equal to null (unless pressing something else when you click this) while (differentKey == null) //Pauses everything else until the player presses another key { differentKey = Greenfoot.getKey(); Greenfoot.delay(1); } setKey(differentKey); //Set the key to the pressed key. changeStats(); } private void setKey(String key) { myKey = key.toUpperCase(); myText.setText(myKey); } private void changeStats() { //GameStats.LEFT = 1 //stats.left is the String representing the left moving key. It is public, and can be affected //Will be adding more to this, testing with the left key. switch (changes) { case GameStats.LEFT: stats.left = myKey.toLowerCase(); } } }