Java by API/java.awt.event/KeyEvent

Материал из Java эксперт
Версия от 14:17, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

KeyEvent: getKeyChar()

 
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
public class MainClass {
  public static void main(String args[]) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField nameTextField = new JTextField();
    frame.add(nameTextField, BorderLayout.NORTH);
    KeyListener keyListener = new KeyListener() {
      public void keyPressed(KeyEvent keyEvent) {
        printIt("Pressed", keyEvent);
      }
      public void keyReleased(KeyEvent keyEvent) {
        printIt("Released", keyEvent);
      }
      public void keyTyped(KeyEvent keyEvent) {
        printIt("Typed", keyEvent);
      }
      private void printIt(String title, KeyEvent keyEvent) {
        int keyCode = keyEvent.getKeyCode();
        String keyText = KeyEvent.getKeyText(keyCode);
        System.out.println(title + " : " + keyText + " / " + keyEvent.getKeyChar());
      }
    };
    nameTextField.addKeyListener(keyListener);

    frame.setSize(250, 100);
    frame.setVisible(true);
  }
}





KeyEvent: getKeyCode()

 
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
public class MainClass {
  public static void main(String args[]) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField nameTextField = new JTextField();
    frame.add(nameTextField, BorderLayout.NORTH);
    KeyListener keyListener = new KeyListener() {
      public void keyPressed(KeyEvent keyEvent) {
        printIt("Pressed", keyEvent);
      }
      public void keyReleased(KeyEvent keyEvent) {
        printIt("Released", keyEvent);
      }
      public void keyTyped(KeyEvent keyEvent) {
        printIt("Typed", keyEvent);
      }
      private void printIt(String title, KeyEvent keyEvent) {
        int keyCode = keyEvent.getKeyCode();
        String keyText = KeyEvent.getKeyText(keyCode);
        System.out.println(title + " : " + keyText + " / " + keyEvent.getKeyChar());
      }
    };
    nameTextField.addKeyListener(keyListener);

    frame.setSize(250, 100);
    frame.setVisible(true);
  }
}





KeyEvent: getKeyLocation()

 
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * KeyEventDemo
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main extends JFrame implements KeyListener, ActionListener {
  JTextArea displayArea;
  JTextField typingArea;
  static final String newline = System.getProperty("line.separator");
  public static void main(String[] args) {
    // Create and set up the window.
    Main frame = new Main();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Set up the content pane.
    frame.addComponentsToPane();
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  private void addComponentsToPane() {
    JButton button = new JButton("Clear");
    button.addActionListener(this);
    typingArea = new JTextField(20);
    typingArea.addKeyListener(this);
    // Uncomment this if you wish to turn off focus
    // traversal. The focus subsystem consumes
    // focus traversal keys, such as Tab and Shift Tab.
    // If you uncomment the following line of code, this
    // disables focus traversal and the Tab events will
    // become available to the key event listener.
    // typingArea.setFocusTraversalKeysEnabled(false);
    displayArea = new JTextArea();
    displayArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(displayArea);
    scrollPane.setPreferredSize(new Dimension(375, 125));
    getContentPane().add(typingArea, BorderLayout.PAGE_START);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(button, BorderLayout.PAGE_END);
  }

  /** Handle the key typed event from the text field. */
  public void keyTyped(KeyEvent e) {
    displayInfo(e, "KEY TYPED: ");
  }
  /** Handle the key pressed event from the text field. */
  public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
  }
  /** Handle the key released event from the text field. */
  public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
  }
  /** Handle the button click. */
  public void actionPerformed(ActionEvent e) {
    // Clear the text components.
    displayArea.setText("");
    typingArea.setText("");
    // Return the focus to the typing area.
    typingArea.requestFocusInWindow();
  }
  /*
   * We have to jump through some hoops to avoid trying to print non-printing
   * characters such as Shift. (Not only do they not print, but if you put them
   * in a String, the characters afterward won"t show up in the text area.)
   */
  private void displayInfo(KeyEvent e, String keyStatus) {
    // You should only rely on the key char if the event
    // is a key typed event.
    int id = e.getID();
    String keyString;
    if (id == KeyEvent.KEY_TYPED) {
      char c = e.getKeyChar();
      keyString = "key character = "" + c + """;
    } else {
      int keyCode = e.getKeyCode();
      keyString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode)
          + ")";
    }
    int modifiersEx = e.getModifiersEx();
    String modString = "extended modifiers = " + modifiersEx;
    String tmpString = KeyEvent.getModifiersExText(modifiersEx);
    if (tmpString.length() > 0) {
      modString += " (" + tmpString + ")";
    } else {
      modString += " (no extended modifiers)";
    }
    String actionString = "action key? ";
    if (e.isActionKey()) {
      actionString += "YES";
    } else {
      actionString += "NO";
    }
    String locationString = "key location: ";
    int location = e.getKeyLocation();
    if (location == KeyEvent.KEY_LOCATION_STANDARD) {
      locationString += "standard";
    } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
      locationString += "left";
    } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
      locationString += "right";
    } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
      locationString += "numpad";
    } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
      locationString += "unknown";
    }
    displayArea.append(keyStatus + newline + "    " + keyString + newline
        + "    " + modString + newline + "    " + actionString + newline
        + "    " + locationString + newline);
    displayArea.setCaretPosition(displayArea.getDocument().getLength());
  }
}





KeyEvent: getKeyText(int keyCode)

 

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * KeyEventDemo
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main extends JFrame implements KeyListener, ActionListener {
  JTextArea displayArea;
  JTextField typingArea;
  static final String newline = System.getProperty("line.separator");
  public static void main(String[] args) {
    // Create and set up the window.
    Main frame = new Main();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Set up the content pane.
    frame.addComponentsToPane();
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  private void addComponentsToPane() {
    JButton button = new JButton("Clear");
    button.addActionListener(this);
    typingArea = new JTextField(20);
    typingArea.addKeyListener(this);
    // Uncomment this if you wish to turn off focus
    // traversal. The focus subsystem consumes
    // focus traversal keys, such as Tab and Shift Tab.
    // If you uncomment the following line of code, this
    // disables focus traversal and the Tab events will
    // become available to the key event listener.
    // typingArea.setFocusTraversalKeysEnabled(false);
    displayArea = new JTextArea();
    displayArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(displayArea);
    scrollPane.setPreferredSize(new Dimension(375, 125));
    getContentPane().add(typingArea, BorderLayout.PAGE_START);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(button, BorderLayout.PAGE_END);
  }

  /** Handle the key typed event from the text field. */
  public void keyTyped(KeyEvent e) {
    displayInfo(e, "KEY TYPED: ");
  }
  /** Handle the key pressed event from the text field. */
  public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
  }
  /** Handle the key released event from the text field. */
  public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
  }
  /** Handle the button click. */
  public void actionPerformed(ActionEvent e) {
    // Clear the text components.
    displayArea.setText("");
    typingArea.setText("");
    // Return the focus to the typing area.
    typingArea.requestFocusInWindow();
  }
  /*
   * We have to jump through some hoops to avoid trying to print non-printing
   * characters such as Shift. (Not only do they not print, but if you put them
   * in a String, the characters afterward won"t show up in the text area.)
   */
  private void displayInfo(KeyEvent e, String keyStatus) {
    // You should only rely on the key char if the event
    // is a key typed event.
    int id = e.getID();
    String keyString;
    if (id == KeyEvent.KEY_TYPED) {
      char c = e.getKeyChar();
      keyString = "key character = "" + c + """;
    } else {
      int keyCode = e.getKeyCode();
      keyString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode)
          + ")";
    }
    int modifiersEx = e.getModifiersEx();
    String modString = "extended modifiers = " + modifiersEx;
    String tmpString = KeyEvent.getModifiersExText(modifiersEx);
    if (tmpString.length() > 0) {
      modString += " (" + tmpString + ")";
    } else {
      modString += " (no extended modifiers)";
    }
    String actionString = "action key? ";
    if (e.isActionKey()) {
      actionString += "YES";
    } else {
      actionString += "NO";
    }
    String locationString = "key location: ";
    int location = e.getKeyLocation();
    if (location == KeyEvent.KEY_LOCATION_STANDARD) {
      locationString += "standard";
    } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
      locationString += "left";
    } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
      locationString += "right";
    } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
      locationString += "numpad";
    } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
      locationString += "unknown";
    }
    displayArea.append(keyStatus + newline + "    " + keyString + newline
        + "    " + modString + newline + "    " + actionString + newline
        + "    " + locationString + newline);
    displayArea.setCaretPosition(displayArea.getDocument().getLength());
  }
}





KeyEvent: isActionKey()

 

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * KeyEventDemo
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main extends JFrame implements KeyListener, ActionListener {
  JTextArea displayArea;
  JTextField typingArea;
  static final String newline = System.getProperty("line.separator");
  public static void main(String[] args) {
    // Create and set up the window.
    Main frame = new Main();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Set up the content pane.
    frame.addComponentsToPane();
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  private void addComponentsToPane() {
    JButton button = new JButton("Clear");
    button.addActionListener(this);
    typingArea = new JTextField(20);
    typingArea.addKeyListener(this);
    // Uncomment this if you wish to turn off focus
    // traversal. The focus subsystem consumes
    // focus traversal keys, such as Tab and Shift Tab.
    // If you uncomment the following line of code, this
    // disables focus traversal and the Tab events will
    // become available to the key event listener.
    // typingArea.setFocusTraversalKeysEnabled(false);
    displayArea = new JTextArea();
    displayArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(displayArea);
    scrollPane.setPreferredSize(new Dimension(375, 125));
    getContentPane().add(typingArea, BorderLayout.PAGE_START);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(button, BorderLayout.PAGE_END);
  }

  /** Handle the key typed event from the text field. */
  public void keyTyped(KeyEvent e) {
    displayInfo(e, "KEY TYPED: ");
  }
  /** Handle the key pressed event from the text field. */
  public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
  }
  /** Handle the key released event from the text field. */
  public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
  }
  /** Handle the button click. */
  public void actionPerformed(ActionEvent e) {
    // Clear the text components.
    displayArea.setText("");
    typingArea.setText("");
    // Return the focus to the typing area.
    typingArea.requestFocusInWindow();
  }
  /*
   * We have to jump through some hoops to avoid trying to print non-printing
   * characters such as Shift. (Not only do they not print, but if you put them
   * in a String, the characters afterward won"t show up in the text area.)
   */
  private void displayInfo(KeyEvent e, String keyStatus) {
    // You should only rely on the key char if the event
    // is a key typed event.
    int id = e.getID();
    String keyString;
    if (id == KeyEvent.KEY_TYPED) {
      char c = e.getKeyChar();
      keyString = "key character = "" + c + """;
    } else {
      int keyCode = e.getKeyCode();
      keyString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode)
          + ")";
    }
    int modifiersEx = e.getModifiersEx();
    String modString = "extended modifiers = " + modifiersEx;
    String tmpString = KeyEvent.getModifiersExText(modifiersEx);
    if (tmpString.length() > 0) {
      modString += " (" + tmpString + ")";
    } else {
      modString += " (no extended modifiers)";
    }
    String actionString = "action key? ";
    if (e.isActionKey()) {
      actionString += "YES";
    } else {
      actionString += "NO";
    }
    String locationString = "key location: ";
    int location = e.getKeyLocation();
    if (location == KeyEvent.KEY_LOCATION_STANDARD) {
      locationString += "standard";
    } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
      locationString += "left";
    } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
      locationString += "right";
    } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
      locationString += "numpad";
    } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
      locationString += "unknown";
    }
    displayArea.append(keyStatus + newline + "    " + keyString + newline
        + "    " + modString + newline + "    " + actionString + newline
        + "    " + locationString + newline);
    displayArea.setCaretPosition(displayArea.getDocument().getLength());
  }
}





KeyEvent.KEY_LOCATION_LEFT

 
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * KeyEventDemo
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main extends JFrame implements KeyListener, ActionListener {
  JTextArea displayArea;
  JTextField typingArea;
  static final String newline = System.getProperty("line.separator");
  public static void main(String[] args) {
    // Create and set up the window.
    Main frame = new Main();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Set up the content pane.
    frame.addComponentsToPane();
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  private void addComponentsToPane() {
    JButton button = new JButton("Clear");
    button.addActionListener(this);
    typingArea = new JTextField(20);
    typingArea.addKeyListener(this);
    // Uncomment this if you wish to turn off focus
    // traversal. The focus subsystem consumes
    // focus traversal keys, such as Tab and Shift Tab.
    // If you uncomment the following line of code, this
    // disables focus traversal and the Tab events will
    // become available to the key event listener.
    // typingArea.setFocusTraversalKeysEnabled(false);
    displayArea = new JTextArea();
    displayArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(displayArea);
    scrollPane.setPreferredSize(new Dimension(375, 125));
    getContentPane().add(typingArea, BorderLayout.PAGE_START);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(button, BorderLayout.PAGE_END);
  }

  /** Handle the key typed event from the text field. */
  public void keyTyped(KeyEvent e) {
    displayInfo(e, "KEY TYPED: ");
  }
  /** Handle the key pressed event from the text field. */
  public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
  }
  /** Handle the key released event from the text field. */
  public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
  }
  /** Handle the button click. */
  public void actionPerformed(ActionEvent e) {
    // Clear the text components.
    displayArea.setText("");
    typingArea.setText("");
    // Return the focus to the typing area.
    typingArea.requestFocusInWindow();
  }
  /*
   * We have to jump through some hoops to avoid trying to print non-printing
   * characters such as Shift. (Not only do they not print, but if you put them
   * in a String, the characters afterward won"t show up in the text area.)
   */
  private void displayInfo(KeyEvent e, String keyStatus) {
    // You should only rely on the key char if the event
    // is a key typed event.
    int id = e.getID();
    String keyString;
    if (id == KeyEvent.KEY_TYPED) {
      char c = e.getKeyChar();
      keyString = "key character = "" + c + """;
    } else {
      int keyCode = e.getKeyCode();
      keyString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode)
          + ")";
    }
    int modifiersEx = e.getModifiersEx();
    String modString = "extended modifiers = " + modifiersEx;
    String tmpString = KeyEvent.getModifiersExText(modifiersEx);
    if (tmpString.length() > 0) {
      modString += " (" + tmpString + ")";
    } else {
      modString += " (no extended modifiers)";
    }
    String actionString = "action key? ";
    if (e.isActionKey()) {
      actionString += "YES";
    } else {
      actionString += "NO";
    }
    String locationString = "key location: ";
    int location = e.getKeyLocation();
    if (location == KeyEvent.KEY_LOCATION_STANDARD) {
      locationString += "standard";
    } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
      locationString += "left";
    } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
      locationString += "right";
    } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
      locationString += "numpad";
    } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
      locationString += "unknown";
    }
    displayArea.append(keyStatus + newline + "    " + keyString + newline
        + "    " + modString + newline + "    " + actionString + newline
        + "    " + locationString + newline);
    displayArea.setCaretPosition(displayArea.getDocument().getLength());
  }
}





KeyEvent.KEY_LOCATION_NUMPAD

 
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * KeyEventDemo
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main extends JFrame implements KeyListener, ActionListener {
  JTextArea displayArea;
  JTextField typingArea;
  static final String newline = System.getProperty("line.separator");
  public static void main(String[] args) {
    // Create and set up the window.
    Main frame = new Main();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Set up the content pane.
    frame.addComponentsToPane();
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  private void addComponentsToPane() {
    JButton button = new JButton("Clear");
    button.addActionListener(this);
    typingArea = new JTextField(20);
    typingArea.addKeyListener(this);
    // Uncomment this if you wish to turn off focus
    // traversal. The focus subsystem consumes
    // focus traversal keys, such as Tab and Shift Tab.
    // If you uncomment the following line of code, this
    // disables focus traversal and the Tab events will
    // become available to the key event listener.
    // typingArea.setFocusTraversalKeysEnabled(false);
    displayArea = new JTextArea();
    displayArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(displayArea);
    scrollPane.setPreferredSize(new Dimension(375, 125));
    getContentPane().add(typingArea, BorderLayout.PAGE_START);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(button, BorderLayout.PAGE_END);
  }

  /** Handle the key typed event from the text field. */
  public void keyTyped(KeyEvent e) {
    displayInfo(e, "KEY TYPED: ");
  }
  /** Handle the key pressed event from the text field. */
  public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
  }
  /** Handle the key released event from the text field. */
  public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
  }
  /** Handle the button click. */
  public void actionPerformed(ActionEvent e) {
    // Clear the text components.
    displayArea.setText("");
    typingArea.setText("");
    // Return the focus to the typing area.
    typingArea.requestFocusInWindow();
  }
  /*
   * We have to jump through some hoops to avoid trying to print non-printing
   * characters such as Shift. (Not only do they not print, but if you put them
   * in a String, the characters afterward won"t show up in the text area.)
   */
  private void displayInfo(KeyEvent e, String keyStatus) {
    // You should only rely on the key char if the event
    // is a key typed event.
    int id = e.getID();
    String keyString;
    if (id == KeyEvent.KEY_TYPED) {
      char c = e.getKeyChar();
      keyString = "key character = "" + c + """;
    } else {
      int keyCode = e.getKeyCode();
      keyString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode)
          + ")";
    }
    int modifiersEx = e.getModifiersEx();
    String modString = "extended modifiers = " + modifiersEx;
    String tmpString = KeyEvent.getModifiersExText(modifiersEx);
    if (tmpString.length() > 0) {
      modString += " (" + tmpString + ")";
    } else {
      modString += " (no extended modifiers)";
    }
    String actionString = "action key? ";
    if (e.isActionKey()) {
      actionString += "YES";
    } else {
      actionString += "NO";
    }
    String locationString = "key location: ";
    int location = e.getKeyLocation();
    if (location == KeyEvent.KEY_LOCATION_STANDARD) {
      locationString += "standard";
    } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
      locationString += "left";
    } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
      locationString += "right";
    } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
      locationString += "numpad";
    } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
      locationString += "unknown";
    }
    displayArea.append(keyStatus + newline + "    " + keyString + newline
        + "    " + modString + newline + "    " + actionString + newline
        + "    " + locationString + newline);
    displayArea.setCaretPosition(displayArea.getDocument().getLength());
  }
}





KeyEvent.KEY_LOCATION_RIGHT

 
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * KeyEventDemo
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main extends JFrame implements KeyListener, ActionListener {
  JTextArea displayArea;
  JTextField typingArea;
  static final String newline = System.getProperty("line.separator");
  public static void main(String[] args) {
    // Create and set up the window.
    Main frame = new Main();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Set up the content pane.
    frame.addComponentsToPane();
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  private void addComponentsToPane() {
    JButton button = new JButton("Clear");
    button.addActionListener(this);
    typingArea = new JTextField(20);
    typingArea.addKeyListener(this);
    // Uncomment this if you wish to turn off focus
    // traversal. The focus subsystem consumes
    // focus traversal keys, such as Tab and Shift Tab.
    // If you uncomment the following line of code, this
    // disables focus traversal and the Tab events will
    // become available to the key event listener.
    // typingArea.setFocusTraversalKeysEnabled(false);
    displayArea = new JTextArea();
    displayArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(displayArea);
    scrollPane.setPreferredSize(new Dimension(375, 125));
    getContentPane().add(typingArea, BorderLayout.PAGE_START);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(button, BorderLayout.PAGE_END);
  }

  /** Handle the key typed event from the text field. */
  public void keyTyped(KeyEvent e) {
    displayInfo(e, "KEY TYPED: ");
  }
  /** Handle the key pressed event from the text field. */
  public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
  }
  /** Handle the key released event from the text field. */
  public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
  }
  /** Handle the button click. */
  public void actionPerformed(ActionEvent e) {
    // Clear the text components.
    displayArea.setText("");
    typingArea.setText("");
    // Return the focus to the typing area.
    typingArea.requestFocusInWindow();
  }
  /*
   * We have to jump through some hoops to avoid trying to print non-printing
   * characters such as Shift. (Not only do they not print, but if you put them
   * in a String, the characters afterward won"t show up in the text area.)
   */
  private void displayInfo(KeyEvent e, String keyStatus) {
    // You should only rely on the key char if the event
    // is a key typed event.
    int id = e.getID();
    String keyString;
    if (id == KeyEvent.KEY_TYPED) {
      char c = e.getKeyChar();
      keyString = "key character = "" + c + """;
    } else {
      int keyCode = e.getKeyCode();
      keyString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode)
          + ")";
    }
    int modifiersEx = e.getModifiersEx();
    String modString = "extended modifiers = " + modifiersEx;
    String tmpString = KeyEvent.getModifiersExText(modifiersEx);
    if (tmpString.length() > 0) {
      modString += " (" + tmpString + ")";
    } else {
      modString += " (no extended modifiers)";
    }
    String actionString = "action key? ";
    if (e.isActionKey()) {
      actionString += "YES";
    } else {
      actionString += "NO";
    }
    String locationString = "key location: ";
    int location = e.getKeyLocation();
    if (location == KeyEvent.KEY_LOCATION_STANDARD) {
      locationString += "standard";
    } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
      locationString += "left";
    } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
      locationString += "right";
    } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
      locationString += "numpad";
    } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
      locationString += "unknown";
    }
    displayArea.append(keyStatus + newline + "    " + keyString + newline
        + "    " + modString + newline + "    " + actionString + newline
        + "    " + locationString + newline);
    displayArea.setCaretPosition(displayArea.getDocument().getLength());
  }
}





KeyEvent.KEY_LOCATION_STANDARD

 
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * KeyEventDemo
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main extends JFrame implements KeyListener, ActionListener {
  JTextArea displayArea;
  JTextField typingArea;
  static final String newline = System.getProperty("line.separator");
  public static void main(String[] args) {
    // Create and set up the window.
    Main frame = new Main();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Set up the content pane.
    frame.addComponentsToPane();
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  private void addComponentsToPane() {
    JButton button = new JButton("Clear");
    button.addActionListener(this);
    typingArea = new JTextField(20);
    typingArea.addKeyListener(this);
    // Uncomment this if you wish to turn off focus
    // traversal. The focus subsystem consumes
    // focus traversal keys, such as Tab and Shift Tab.
    // If you uncomment the following line of code, this
    // disables focus traversal and the Tab events will
    // become available to the key event listener.
    // typingArea.setFocusTraversalKeysEnabled(false);
    displayArea = new JTextArea();
    displayArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(displayArea);
    scrollPane.setPreferredSize(new Dimension(375, 125));
    getContentPane().add(typingArea, BorderLayout.PAGE_START);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(button, BorderLayout.PAGE_END);
  }

  /** Handle the key typed event from the text field. */
  public void keyTyped(KeyEvent e) {
    displayInfo(e, "KEY TYPED: ");
  }
  /** Handle the key pressed event from the text field. */
  public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
  }
  /** Handle the key released event from the text field. */
  public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
  }
  /** Handle the button click. */
  public void actionPerformed(ActionEvent e) {
    // Clear the text components.
    displayArea.setText("");
    typingArea.setText("");
    // Return the focus to the typing area.
    typingArea.requestFocusInWindow();
  }
  /*
   * We have to jump through some hoops to avoid trying to print non-printing
   * characters such as Shift. (Not only do they not print, but if you put them
   * in a String, the characters afterward won"t show up in the text area.)
   */
  private void displayInfo(KeyEvent e, String keyStatus) {
    // You should only rely on the key char if the event
    // is a key typed event.
    int id = e.getID();
    String keyString;
    if (id == KeyEvent.KEY_TYPED) {
      char c = e.getKeyChar();
      keyString = "key character = "" + c + """;
    } else {
      int keyCode = e.getKeyCode();
      keyString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode)
          + ")";
    }
    int modifiersEx = e.getModifiersEx();
    String modString = "extended modifiers = " + modifiersEx;
    String tmpString = KeyEvent.getModifiersExText(modifiersEx);
    if (tmpString.length() > 0) {
      modString += " (" + tmpString + ")";
    } else {
      modString += " (no extended modifiers)";
    }
    String actionString = "action key? ";
    if (e.isActionKey()) {
      actionString += "YES";
    } else {
      actionString += "NO";
    }
    String locationString = "key location: ";
    int location = e.getKeyLocation();
    if (location == KeyEvent.KEY_LOCATION_STANDARD) {
      locationString += "standard";
    } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
      locationString += "left";
    } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
      locationString += "right";
    } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
      locationString += "numpad";
    } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
      locationString += "unknown";
    }
    displayArea.append(keyStatus + newline + "    " + keyString + newline
        + "    " + modString + newline + "    " + actionString + newline
        + "    " + locationString + newline);
    displayArea.setCaretPosition(displayArea.getDocument().getLength());
  }
}





KeyEvent.KEY_TYPED

 
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*
 * KeyEventDemo
 */
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main extends JFrame implements KeyListener, ActionListener {
  JTextArea displayArea;
  JTextField typingArea;
  static final String newline = System.getProperty("line.separator");
  public static void main(String[] args) {
    // Create and set up the window.
    Main frame = new Main();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Set up the content pane.
    frame.addComponentsToPane();
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  private void addComponentsToPane() {
    JButton button = new JButton("Clear");
    button.addActionListener(this);
    typingArea = new JTextField(20);
    typingArea.addKeyListener(this);
    // Uncomment this if you wish to turn off focus
    // traversal. The focus subsystem consumes
    // focus traversal keys, such as Tab and Shift Tab.
    // If you uncomment the following line of code, this
    // disables focus traversal and the Tab events will
    // become available to the key event listener.
    // typingArea.setFocusTraversalKeysEnabled(false);
    displayArea = new JTextArea();
    displayArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(displayArea);
    scrollPane.setPreferredSize(new Dimension(375, 125));
    getContentPane().add(typingArea, BorderLayout.PAGE_START);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    getContentPane().add(button, BorderLayout.PAGE_END);
  }

  /** Handle the key typed event from the text field. */
  public void keyTyped(KeyEvent e) {
    displayInfo(e, "KEY TYPED: ");
  }
  /** Handle the key pressed event from the text field. */
  public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
  }
  /** Handle the key released event from the text field. */
  public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
  }
  /** Handle the button click. */
  public void actionPerformed(ActionEvent e) {
    // Clear the text components.
    displayArea.setText("");
    typingArea.setText("");
    // Return the focus to the typing area.
    typingArea.requestFocusInWindow();
  }
  /*
   * We have to jump through some hoops to avoid trying to print non-printing
   * characters such as Shift. (Not only do they not print, but if you put them
   * in a String, the characters afterward won"t show up in the text area.)
   */
  private void displayInfo(KeyEvent e, String keyStatus) {
    // You should only rely on the key char if the event
    // is a key typed event.
    int id = e.getID();
    String keyString;
    if (id == KeyEvent.KEY_TYPED) {
      char c = e.getKeyChar();
      keyString = "key character = "" + c + """;
    } else {
      int keyCode = e.getKeyCode();
      keyString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode)
          + ")";
    }
    int modifiersEx = e.getModifiersEx();
    String modString = "extended modifiers = " + modifiersEx;
    String tmpString = KeyEvent.getModifiersExText(modifiersEx);
    if (tmpString.length() > 0) {
      modString += " (" + tmpString + ")";
    } else {
      modString += " (no extended modifiers)";
    }
    String actionString = "action key? ";
    if (e.isActionKey()) {
      actionString += "YES";
    } else {
      actionString += "NO";
    }
    String locationString = "key location: ";
    int location = e.getKeyLocation();
    if (location == KeyEvent.KEY_LOCATION_STANDARD) {
      locationString += "standard";
    } else if (location == KeyEvent.KEY_LOCATION_LEFT) {
      locationString += "left";
    } else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
      locationString += "right";
    } else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
      locationString += "numpad";
    } else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
      locationString += "unknown";
    }
    displayArea.append(keyStatus + newline + "    " + keyString + newline
        + "    " + modString + newline + "    " + actionString + newline
        + "    " + locationString + newline);
    displayArea.setCaretPosition(displayArea.getDocument().getLength());
  }
}





KeyEvent.VK_B

 
import java.awt.Event;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.DefaultEditorKit;
public class MainClass extends JFrame {
  MainClass(String title) {
    super(title);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel jp = new JPanel();
    JLabel jl = new JLabel("Name:");
    jp.add(jl);
    JTextField jt = new JTextField(20);
    jp.add(jt);
    KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_B, Event.CTRL_MASK);
    jt.getInputMap().put(ks, DefaultEditorKit.beepAction);
    getContentPane().add(jp);
    pack();
    setVisible(true);
  }
  public static void main(String[] args) {
    new MainClass("Binding Demo2");
  }
}





KeyEvent.VK_DOWN

 
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel implements KeyListener {
  private Point startPoint = new Point(0, 0);
  private Point endPoint = new Point(0, 0);
  public Main() {
    addKeyListener(this);
  }
  public void keyPressed(KeyEvent evt) {
    int keyCode = evt.getKeyCode();
    int d;
    if (evt.isShiftDown())
      d = 5;
    else
      d = 1;
    if (keyCode == KeyEvent.VK_LEFT)
      add(-d, 0);
    else if (keyCode == KeyEvent.VK_RIGHT)
      add(d, 0);
    else if (keyCode == KeyEvent.VK_UP)
      add(0, -d);
    else if (keyCode == KeyEvent.VK_DOWN)
      add(0, d);
  }
  public void keyReleased(KeyEvent evt) {
  }
  public void keyTyped(KeyEvent evt) {
  }
  public boolean isFocusTraversable() {
    return true;
  }
  public void add(int dx, int dy) {
    endPoint.x += dx;
    endPoint.y += dy;
    Graphics g = getGraphics();
    g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
    g.dispose();
    startPoint.x = endPoint.x;
    startPoint.y = endPoint.y;
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("Sketch");
    frame.setSize(300, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    contentPane.add(new Main());
    frame.setVisible(true);
  }
}





KeyEvent.VK_LEFT

 
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel implements KeyListener {
  private Point startPoint = new Point(0, 0);
  private Point endPoint = new Point(0, 0);
  public Main() {
    addKeyListener(this);
  }
  public void keyPressed(KeyEvent evt) {
    int keyCode = evt.getKeyCode();
    int d;
    if (evt.isShiftDown())
      d = 5;
    else
      d = 1;
    if (keyCode == KeyEvent.VK_LEFT)
      add(-d, 0);
    else if (keyCode == KeyEvent.VK_RIGHT)
      add(d, 0);
    else if (keyCode == KeyEvent.VK_UP)
      add(0, -d);
    else if (keyCode == KeyEvent.VK_DOWN)
      add(0, d);
  }
  public void keyReleased(KeyEvent evt) {
  }
  public void keyTyped(KeyEvent evt) {
  }
  public boolean isFocusTraversable() {
    return true;
  }
  public void add(int dx, int dy) {
    endPoint.x += dx;
    endPoint.y += dy;
    Graphics g = getGraphics();
    g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
    g.dispose();
    startPoint.x = endPoint.x;
    startPoint.y = endPoint.y;
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("Sketch");
    frame.setSize(300, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    contentPane.add(new Main());
    frame.setVisible(true);
  }
}





KeyEvent.VK_N

 
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Label Focus Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new BorderLayout());
    JLabel label = new JLabel("Name: ");
    label.setDisplayedMnemonic(KeyEvent.VK_N);
    JTextField textField = new JTextField();
    label.setLabelFor(textField);
    panel.add(label, BorderLayout.WEST);
    panel.add(textField, BorderLayout.CENTER);
    frame.add(panel, BorderLayout.NORTH);
    frame.add(new JButton("Somewhere Else"), BorderLayout.SOUTH);
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}





KeyEvent.VK_RIGHT

 
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel implements KeyListener {
  private Point startPoint = new Point(0, 0);
  private Point endPoint = new Point(0, 0);
  public Main() {
    addKeyListener(this);
  }
  public void keyPressed(KeyEvent evt) {
    int keyCode = evt.getKeyCode();
    int d;
    if (evt.isShiftDown())
      d = 5;
    else
      d = 1;
    if (keyCode == KeyEvent.VK_LEFT)
      add(-d, 0);
    else if (keyCode == KeyEvent.VK_RIGHT)
      add(d, 0);
    else if (keyCode == KeyEvent.VK_UP)
      add(0, -d);
    else if (keyCode == KeyEvent.VK_DOWN)
      add(0, d);
  }
  public void keyReleased(KeyEvent evt) {
  }
  public void keyTyped(KeyEvent evt) {
  }
  public boolean isFocusTraversable() {
    return true;
  }
  public void add(int dx, int dy) {
    endPoint.x += dx;
    endPoint.y += dy;
    Graphics g = getGraphics();
    g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
    g.dispose();
    startPoint.x = endPoint.x;
    startPoint.y = endPoint.y;
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("Sketch");
    frame.setSize(300, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    contentPane.add(new Main());
    frame.setVisible(true);
  }
}





KeyEvent.VK_U

 
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.KeyEvent;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Main {
  public static void main(String args[]) {
    JFrame f = new JFrame("LabelFor Sample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = f.getContentPane();
    JLabel label = new JLabel("Username");
    JTextField textField = new JTextField();
    label.setDisplayedMnemonic(KeyEvent.VK_U);
    label.setLabelFor(textField);
    Container box = Box.createHorizontalBox();
    box.add(label);
    box.add(textField);
    content.add(box, BorderLayout.NORTH);
    content.add(new JButton("Submit"), BorderLayout.SOUTH);
    f.setSize(300, 200);
    f.setVisible(true);
  }
}





KeyEvent.VK_UP

 
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel implements KeyListener {
  private Point startPoint = new Point(0, 0);
  private Point endPoint = new Point(0, 0);
  public Main() {
    addKeyListener(this);
  }
  public void keyPressed(KeyEvent evt) {
    int keyCode = evt.getKeyCode();
    int d;
    if (evt.isShiftDown())
      d = 5;
    else
      d = 1;
    if (keyCode == KeyEvent.VK_LEFT)
      add(-d, 0);
    else if (keyCode == KeyEvent.VK_RIGHT)
      add(d, 0);
    else if (keyCode == KeyEvent.VK_UP)
      add(0, -d);
    else if (keyCode == KeyEvent.VK_DOWN)
      add(0, d);
  }
  public void keyReleased(KeyEvent evt) {
  }
  public void keyTyped(KeyEvent evt) {
  }
  public boolean isFocusTraversable() {
    return true;
  }
  public void add(int dx, int dy) {
    endPoint.x += dx;
    endPoint.y += dy;
    Graphics g = getGraphics();
    g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
    g.dispose();
    startPoint.x = endPoint.x;
    startPoint.y = endPoint.y;
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("Sketch");
    frame.setSize(300, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();
    contentPane.add(new Main());
    frame.setVisible(true);
  }
}