Hi, I am trying to implement a GUI for my game entirely from scratch (no Swing except for the Canvas). So far I have implemented the rendering of 4 basic elements (Label, button, text field, and a selection element). I can’t figure out how to properly handle inputs though. I know I can use keyboard listeners, etc…, but I can’t find a good way to do it.
Check if the textfield is holding the focus/selected.
Basically you should have a “container”, that container has one focused element… when you select an element the last focused element is blurred and the new one is focused. you only send key input to the focused element.
Hold reference to focused element. Add listener on container. When receive input, container will pass it to that reference. You may need make an interface to make it easier.
How well would holding a queue of received input events work? Because my game is a bit separated, so I have contexts that are pushed onto the context stack and each context is updated by a call to a method with no arguments. This is the interface each context implements.
public abstract class GameContext {
public abstract void init();
public abstract void render(Graphics2D gr);
public abstract void tick();
public abstract boolean isTransparent();
}
For reference, here is a demo of my interface. I got input working based off of a suggestion from reddit. Comments, suggestions?
Now my problem is that I need to determine how to handle button events (and other events). Should I try to emulate the java callback system?
qcLP1Ptr4TQ
On screen buttons is just a matter of testing to see if a mouse click event occurred inside a rectangle. If buttons can overlap, you need to define a z-order of each button and activate the closest one only. Keyboard input may as well be done exactly how AWT/Swing does it. Make sure you understand the difference between keyPressed/keyReleased events and keyTyped events. They are defined in the same interface, but have very different purposes.
If you use event listeners do not confuse the callback method for the action it is supposed to trigger. Mixing game logic with UI logic creates a mess and means you have to rewrite lots of code if you want to keep the same functionality but map it to a different input or sequence of inputs.