daily pastebin goal
28%
SHARE
TWEET

Untitled

a guest Aug 12th, 2017 44 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package net.eonz.games.e2945;
  2.  
  3. import java.awt.event.KeyEvent;
  4. import java.awt.event.KeyListener;
  5. import java.util.ArrayList;
  6.  
  7. import javax.swing.JApplet;
  8.  
  9. public class KeyboardManager implements KeyListener {
  10.  
  11.     private static class KeyState {
  12.         private boolean state = false;
  13.         public final int keyCode;
  14.        
  15.         public KeyState(int keyCode) {
  16.             this.keyCode = keyCode;
  17.         }
  18.  
  19.         public void setState(boolean state) {
  20.             this.state = state;
  21.         }
  22.  
  23.         public boolean getState() {
  24.             return state;
  25.         }
  26.     }
  27.    
  28.     private final JApplet applet;
  29.     private final ArrayList<KeyState> states;
  30.    
  31.     public KeyboardManager(JApplet applet) {
  32.         this.applet = applet;
  33.         this.applet.addKeyListener(this);
  34.        
  35.         states = new ArrayList<KeyState>();
  36.     }
  37.  
  38.     public void monitor(int keyCode) {
  39.         states.add(new KeyState(keyCode));
  40.     }
  41.    
  42.     public boolean getState(int keyCode) {
  43.         for (KeyState s : states.toArray(new KeyState[0])) {
  44.             if (s.keyCode == keyCode) {
  45.                 return s.getState();
  46.             }
  47.         }
  48.        
  49.         monitor(keyCode);
  50.         System.out.println("[Warning] You should register key codes before you check for them. A monitor has been added. ( Key code: " + keyCode + " )");
  51.         return false;
  52.     }
  53.    
  54.     @Override
  55.     public void keyPressed(KeyEvent e) {
  56.         for (KeyState s : states.toArray(new KeyState[0])) {
  57.             if (s.keyCode == e.getKeyCode()) {
  58.                 s.setState(true);
  59.             }
  60.         }
  61.     }
  62.  
  63.     @Override
  64.     public void keyReleased(KeyEvent e) {
  65.         for (KeyState s : states.toArray(new KeyState[0])) {
  66.             if (s.keyCode == e.getKeyCode()) {
  67.                 s.setState(false);
  68.             }
  69.         }
  70.     }
  71.  
  72.     @Override
  73.     public void keyTyped(KeyEvent e) {
  74.        
  75.     }
  76.    
  77. }
RAW Paste Data
Top