An issue I’ve had in general app GUIs is finding a way to implement the menus and options in such a way that one could potentially abstract some or all of the actual menu details outside of the compiled code and into an XML or scripting format. In this case, I’m building a Java based game using Slick2D, a nicely done engine written on top of LWJGL and OpenGL.
My approach was to create a menu listener for each menu by implementing the InputListener interface. This class would then contain an ArrayList of MenuOptions, a class that implements my custom MenuAction interface (methods such as clickAction, hoverAction, etc). Using this approach allows menus and options to be defined externally and later created at runtime.
The MenuListener then implements the required methods, such as processing mouse clicks like so:
public void mouseClicked(int button, int x, int y, int clickCount) {
for(MenuOption option: menuOptions) {
if(option.isFocused(x, y)) {
acceptInput = option.clickAction();
return;
}
}
}
What happens here is simple. This listener processes clicks by checking if the click has fallen within the dimensions of the option, then the option’s clickAction is dispatched. Note that the return value is being saved to acceptInput. This variable is returned in the isAcceptingInput method. This allows menu options to return false and disable the listener.
Here is the clickAction implementation in the MenuOptionStart class. Clicking this menu option switches the game into the play state and disables the menu this option belongs to (the main menu).
public boolean clickAction() {
StateBasedGame game = (StateBasedGame) GameRegistry.GetObject("StateBasedGame");
game.enterState(GameStates.GAMEPLAY.hashCode());
return false;
}
This system is still pretty early and rough, but it has been working out decently for me. It also allows for menu item dimensions, images, ordering, and even visibility to be configured outside the code.