Java









Java

This page contains snippets of Java code that I find useful in my programs.  All code authored by me is public domain and may be used freely in any programs

Here's some code that will watch the keyboard and intercept all keystrokes.  I used it in my MP3 Jukebox software.


import java.awt.*;

public class KeyFrame extends Frame {
  public KeyFrame() {
    WindowWatcher lWindowWatcher = new WindowWatcher();
    addWindowListener(lWindowWatcher);
    KeyWatcher lKeyWatcher = new KeyWatcher();
    addKeyListener(lKeyWatcher);
  }

  public synchronized void show() {
    super.show();
  }

  static public void main(String args[]) {
    (new KeyFrame()).show();
  }

  public void addNotify() {
    super.addNotify();
  }

  class WindowWatcher extends java.awt.event.WindowAdapter {
    public void windowClosing(java.awt.event.WindowEvent event) {
      Object object = event.getSource();
      if (object == KeyFrame.this)
        KeyFrame_WindowClosing(event);
    }
  }

  void KeyFrame_WindowClosing(java.awt.event.WindowEvent event) {
    hide(); // hide the Frame
    dispose(); // free the system resources
    System.exit(0); // close the application
  }

  class KeyWatcher extends java.awt.event.KeyAdapter {
    public void keyPressed(java.awt.event.KeyEvent event) {
      Object object = event.getSource();
      if (object == KeyFrame.this)
        KeyFrame_KeyPress(event);
    }
  }

  void KeyFrame_KeyPress(java.awt.event.KeyEvent event) {
    // to do: code goes here.
    System.out.println("Button Key Press :" + event.getKeyText(event.getKeyCode()));
  }
}