Search code examples
javaclasscompressionkeyevent

Java: Grabbing a key event without a KeyListener or using any other custom classes


This is a bit of an odd question, but it is worth an ask: Is there any way to generically grab a key event in Java without the use of a key listener, key bindings, key dispatcher, etc? The goal here is to not utilize any overloaded classes (ex. new KeyListener() { ... }).

I am trying to see how small I can make a simple game, and using overloaded classes takes up quite a bit of space relative to the normal code because they require an entire class file of their own when they are packaged into a jar.


Solution

    1. There is no way.

    2. You can use anonymous (or named) inner classes if you want to avoid separate source files. In fact, anonymous inner classes are extremely common to use for simple listeners or adapters. You can also implement KeyListener in your main logic class, although that's a bit unusual, but it depends on your situation.

      void example () {
      
          JComponent component = ...;
      
          component.addKeyListener(new KeyAdapter() {
              @Override public void keyPressed (KeyEvent e) {
                  // do stuff
              }
          });
      
      }
      

      See Anonymous Class Tutorial.

    3. JARs are compressed, you're talking on the order of hundreds of bytes here.