title: Designing a simple event-driven GUI
body: <p>I am creating a simple event-driven GUI for a video game I am making with LibGDX. It only needs to support buttons (rectangular) with a single act() function called when they are clicked. I would appreciate some advice on structuring because the solution I've thought of so far seems to be far from ideal.</p>
  
  <p>My current implementation involves all buttons extending a <code>Button</code> class. Each button has a <code>Rectangle</code> with its bounds and an abstract <code>act()</code> method.</p>
  
  <p>Each game screen (e.g. main menu, character select, pause menu, the in-game screen) has a <code>HashMap</code> of Buttons. When clicked, the game screen iterates through everything in the HashMap, and calls act() on any button that was clicked.</p>
  
  <p>The problem I'm having is that Buttons have to have their act() overridden from their superclass in order to perform their action, and that the Buttons aren't a member of the Screen class which contains all the game code. I am subclassing <code>Button</code> for each button in the game. My main menu alone has a ButtonPlay, ButtonMapDesigner, ButtonMute, ButtonQuit, etc. This is going to get messy fast, but I can't think of any better way to do it while keeping a separate <code>act()</code> method for each button.</p>
  
  <p>Since my mute button isn't a part of the main menu screen and can't access game logic, it's <code>act()</code> is nothing more than <code>mainMenuScreen.mute();</code>. So effectively, for every button in my game, I have to create a class class that does nothing more than <code>&lt;currentGameScreen&gt;.doThisAction();</code>, since the code to actually do stuff must be in the game screen class.</p>
  
  <p>I considered having a big if/then to check the coordinates of each click and call the appropriate action if necessary. For example,  </p>
  
  <pre><code>if (clickWithinTheseCoords)
     beginGame();
  else if(clickWithinTheseOtherCoords)
     muteGame();
  ...
  </code></pre>
  
  <p>However, I need to be able to add/remove buttons on the fly. When a unit is clicked from the game screen, a button to move it needs to appear, and then disappear when the unit is actually moved. With a HashMap, I can just <code>map.add("buttonMove", new ButtonMove())</code> and <code>map.remove("buttonMove")</code> in the code called when a unit is clicked or moved. With the if/else method, I won't need a separate class for every button, but I would need to keep track of whether each clickable area tested is visible and clickable by the user at this point in the game, which seems like an even bigger headache that what I have right now.</p>