2

I seen many conflicting recommendations on the internet including here on how to handle input with awt and swing and several people have worked on my code and its a mess.

options

  • implement KeyListener or extend KeyAdapter
  • ^to the application's main class, use an anonymous class, use a private class or use an external input managing class.
  • to send the event object to each object that needs to know input, to send an array of keys pressed, or to make every class a listener and add it to the main class.

So I could have

public class Board extends JPanel implements KeyListener{
    public Board(){addKeyListener(this);}}

or

public Board(){addKeyListener( new KeyListener(){...});}

or

public class Board extends JPanel {
    private class PrivateListener implements KeyListener{...} 
    public Board(){addKeyListener(new PrivateListener());

or

public class PublicListener implements KeyAdapter{...}
public class Board extends JPanel {
    public Board(){addKeyListener(new PublicListener());

or

addKeyListener(this);
addKeyListener(obj1);
addKeyListener(obj2);

and implements KeyListener can be replaced with extends KeyAdapter but I won't do that because java only allows for one parent class.

then there is which I don't know how this got into my code

private boolean [] keys = new boolean[256];
public void keyPressed(KeyEvent e) {keys[e.getKeyCode()] = true;}
public void keyReleased(KeyEvent e) {keys[e.getKeyCode()] = false;}
public boolean isKeyDown(int k) {return keys[k];}

or

public void keyPressed(KeyEvent e) {
    obj1.keyPressed(e);
    obj2.keyPressed(e);
}

Truly, what is the best implementation of awt keyboard input?

Old Badman Grey
  • 598
  • 10
  • 18
  • *"implement KeyListener.."* You did not see anything about [Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) in those searches? – Andrew Thompson Oct 30 '13 at 03:43
  • BTW - is the code using AWT **components**? If so.. Why AWT rather than Swing? See this answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. If you need to support older AWT based APIs, see [Mixing Heavyweight and Lightweight Components](http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html). – Andrew Thompson Oct 30 '13 at 03:45
  • @AndrewThompson I was working on a 2d awt based game. In doing such I found many ways to do controls. The question remains the best way to do input with awt (also life sucks when it comes to hobbies) – Old Badman Grey Mar 31 '14 at 07:49

0 Answers0