java.awt.event.KeyEvent类的使用及代码示例

x33g5p2x  于2022-01-23 转载在 其他  
字(15.1k)|赞(0)|评价(0)|浏览(303)

本文整理了Java中java.awt.event.KeyEvent类的一些代码示例,展示了KeyEvent类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。KeyEvent类的具体详情如下:
包路径:java.awt.event.KeyEvent
类名称:KeyEvent

KeyEvent介绍

[英]An event which indicates that a keystroke occurred in a component.

This low-level event is generated by a component object (such as a text field) when a key is pressed, released, or typed. The event is passed to every KeyListener or KeyAdapter object which registered to receive such events using the component's addKeyListener method. (KeyAdapter objects implement the KeyListener interface.) Each such listener object gets this KeyEvent when the event occurs.

"Key typed" events are higher-level and generally do not depend on the platform or keyboard layout. They are generated when a Unicode character is entered, and are the preferred way to find out about character input. In the simplest case, a key typed event is produced by a single key press (e.g., 'a'). Often, however, characters are produced by series of key presses (e.g., 'shift' + 'a'), and the mapping from key pressed events to key typed events may be many-to-one or many-to-many. Key releases are not usually necessary to generate a key typed event, but there are some cases where the key typed event is not generated until a key is released (e.g., entering ASCII sequences via the Alt-Numpad method in Windows). No key typed events are generated for keys that don't generate Unicode characters (e.g., action keys, modifier keys, etc.). The getKeyChar method always returns a valid Unicode character or CHAR_UNDEFINED. For key pressed and key released events, the getKeyCode method returns the event's keyCode. For key typed events, the getKeyCode method always returns VK_UNDEFINED.

"Key pressed" and "key released" events are lower-level and depend on the platform and keyboard layout. They are generated whenever a key is pressed or released, and are the only way to find out about keys that don't generate character input (e.g., action keys, modifier keys, etc.). The key being pressed or released is indicated by the getKeyCode method, which returns a virtual key code.

Virtual key codes are used to report which keyboard key has been pressed, rather than a character generated by the combination of one or more keystrokes (such as "A", which comes from shift and "a").

For example, pressing the Shift key will cause a KEY_PRESSED event with a VK_SHIFT keyCode, while pressing the 'a' key will result in a VK_A keyCode. After the 'a' key is released, a KEY_RELEASED event will be fired with VK_A. Separately, a KEY_TYPED event with a keyChar value of 'A' is generated.

Notes:

  • Key combinations which do not result in Unicode characters, such as action keys like F1 and the HELP key, do not generate KEY_TYPED events.
  • Not all keyboards or systems are capable of generating all virtual key codes. No attempt is made in Java to generate these keys artificially.
  • Virtual key codes do not identify a physical key: they depend on the platform and keyboard layout. For example, the key that generates VK_Q when using a U.S. keyboard layout will generate VK_A when using a French keyboard layout.
  • Not all characters have a keycode associated with them. For example, there is no keycode for the question mark because there is no keyboard for which it appears on the primary layer.
  • In order to support the platform-independent handling of action keys, the Java platform uses a few additional virtual key constants for functions that would otherwise have to be recognized by interpreting virtual key codes and modifiers. For example, for Japanese Windows keyboards, VK_ALL_CANDIDATES is returned instead of VK_CONVERT with the ALT modifier.

WARNING: Aside from those keys that are defined by the Java language (VK_ENTER, VK_BACK_SPACE, and VK_TAB), do not rely on the values of the VK_ constants. Sun reserves the right to change these values as needed to accomodate a wider range of keyboards in the future.

Restrictions

[*Implementations of this Profile exhibit certain restrictions with respect to key events, specifically:

  • An implementation need not provide full support for the generation of key events. In such a case, it may partially support the generation of key events or not support them at all.

Regardless of this restriction, applications may still create KeyEvent objects and post them to the system event queue.
Note: An implementation that provides full support for key events must support a*](https://www.tabnine.com/code/java/classes/java.awt.event.KeyEvent#)*basic set of virtual key codes.

For more information, see Profile-specific properties.*
[中]指示组件中发生击键的事件。
当按下、释放或键入键时,此低级事件由组件对象(如文本字段)生成。事件将传递给每个KeyListenerKeyAdapter对象,这些对象使用组件的addKeyListener方法注册以接收此类事件。(KeyAdapter对象实现KeyListener接口。)当事件发生时,每个这样的侦听器对象都会得到这个KeyEvent
“按键式”事件是更高级别的事件,通常不依赖于平台或键盘布局。它们是在输入Unicode字符时生成的,是了解字符输入的首选方法。在最简单的情况下,按键类型的事件是由单个按键(例如“a”)产生的。但是,通常情况下,字符是由一系列按键(例如,“shift”+“a”)产生的,按键事件到按键类型事件的映射可能是多对一或多对多。生成键类型的事件通常不需要释放键,但在某些情况下,直到释放键后才会生成键类型的事件(例如,在Windows中通过Alt Numpad方法输入ASCII序列)。对于不生成Unicode字符的键(例如,动作键、修改键等),不会生成键类型的事件。getKeyChar方法始终返回有效的Unicode字符或未定义的字符。对于按键按下和按键释放事件,getKeyCode方法返回事件的keyCode。对于键类型的事件,getKeyCode方法始终返回VK_UNDEFINED。
“按键按下”和“按键释放”事件级别较低,取决于平台和键盘布局。每当按下或释放某个键时,它们都会生成,并且是查找不生成字符输入的键(例如,动作键、修改键等)的唯一方法。按下或释放的键由getKeyCode方法指示,该方法返回一个虚拟键代码。
虚拟键代码用于报告按下了哪个键盘键,而不是由一个或多个击键组合生成的字符(如“a”,来自shift和“a”)。
例如,按下Shift键将导致出现带有VK_Shift keyCode的按键按下事件,而按下“a”键将导致出现VK_a keyCode。释放“a”键后,将使用VK_a触发一个key_released事件。另外,将生成一个keyChar值为“a”的key_类型的事件。
笔记:
*不会产生Unicode字符的键组合(如F1和帮助键等操作键)不会生成键类型的事件。
*并非所有键盘或系统都能生成所有虚拟钥匙代码。Java中没有试图人工生成这些密钥。
*虚拟键代码不能识别物理键:它们取决于平台和键盘布局。例如,使用美国键盘布局时生成VK_Q的键将在使用法语键盘布局时生成VK_a。
*并非所有字符都有与其关联的键码。例如,问号没有键盘代码,因为它没有显示在主层上的键盘。
*为了支持独立于平台的操作键处理,Java平台为函数使用了一些额外的虚拟键常量,否则必须通过解释虚拟键代码和修饰符来识别这些函数。例如,对于日文Windows键盘,返回VK_ALL_候选项,而不是使用ALT修饰符进行VK_转换。
警告:除了Java语言定义的键(VK_ENTER、VK_BACK_SPACE和VK_TAB)之外,不要依赖于VK_常量的值。Sun保留根据需要更改这些值的权利,以适应未来更大范围的键盘。

Restrictions

[*Implementations of this Profile exhibit certain restrictions with respect to key events, specifically:

  • An implementation need not provide full support for the generation of key events. In such a case, it may partially support the generation of key events or not support them at all.

Regardless of this restriction, applications may still create KeyEvent objects and post them to the system event queue.
Note: An implementation that provides full support for key events must support a*](https://www.tabnine.com/code/java/classes/java.awt.event.KeyEvent#)basic set of virtual key codes.
有关更多信息,请参见Profile-specific properties

代码示例

代码示例来源:origin: stackoverflow.com

setFocusable(true);
requestFocusInWindow();
addKeyListener(new KeyAdapter() {
   int key = e.getKeyCode();
   System.out.println("TEST");
ArrowTest mainPanel = new ArrowTest();
JFrame frame = new JFrame("ArrowTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);

代码示例来源:origin: stackoverflow.com

JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.getContentPane().add(panel);
panel.addKeyListener(new KeyListener() {
    System.out.println("Pressed " + e.getKeyChar());
panel.setFocusable(true);
panel.requestFocusInWindow();
frame.setSize(new Dimension(300, 300));
frame.setVisible(true);

代码示例来源:origin: runelite/runelite

@Override
public void keyPressed(KeyEvent e)
{
  if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
  {
    e.consume();
  }
}

代码示例来源:origin: stackoverflow.com

/**
  * Override the behaviour so that TAB key transfers the focus
  * to the next focusable component.
  */
 @Override
 public void keyPressed(KeyEvent e) {
   if(e.getKeyCode() == KeyEvent.VK_TAB) {
     System.out.println(e.getModifiers());
     if(e.getModifiers() > 0) a.transferFocusBackward();
     else a.transferFocus(); 
     e.consume();
   }
 }

代码示例来源:origin: stackoverflow.com

JTextField textField = new JTextField(10);
textField.addKeyListener(new KeyAdapter() {
  public void keyTyped(KeyEvent e) {
   char c = e.getKeyChar();
   if ( ((c < '0') || (c > '9')) && (c != KeyEvent.VK_BACK_SPACE)) {
     e.consume();  // ignore event
   }
  }
});

代码示例来源:origin: stackoverflow.com

import java.awt.event.KeyAdapter;
 import java.awt.event.KeyEvent;
 import javax.swing.JFrame;
 import javax.swing.JTextField;
 public class Main {
   public static void main(String[] argv) throws Exception {
  JTextField textField = new JTextField();
  textField.addKeyListener(new Keychecker());
  JFrame jframe = new JFrame();
  jframe.add(textField);
  jframe.setSize(400, 350);
  jframe.setVisible(true);
   }
 }
 class Keychecker extends KeyAdapter {
   @Override
   public void keyPressed(KeyEvent event) {
  char ch = event.getKeyChar();
  System.out.println(event.getKeyChar());
  }
   }
 }

代码示例来源:origin: stackoverflow.com

};
public static void main( String[] args ) {
  JFrame frame = new JFrame();
  JTable table = new JTable(data,columnNames);
  TableColumn tc = tcm.getColumn(1);
  tc.setCellEditor(new SpinnerEditor());
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.add(table);
  frame.pack();
  frame.setVisible(true);
    editor = ((JSpinner.DefaultEditor)spinner.getEditor());
    textField = editor.getTextField();
    textField.addFocusListener( new FocusListener() {
      public void focusGained( FocusEvent fe ) {
        System.err.println("Got focus");
        textField.requestFocus();
    if ( eo instanceof KeyEvent ) {
      KeyEvent ke = (KeyEvent)eo;
      System.err.println("key event: "+ke.getKeyChar());
      textField.setText(String.valueOf(ke.getKeyChar()));

代码示例来源:origin: stackoverflow.com

JFrame ablak = new JFrame("Snake game");
ablak.setVisible(true);
ablak.setSize(new Dimension(600, 600));
ablak.setFocusable(true);
ablak.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ablak.addKeyListener(new KeyAdapter() {
  @Override
  public void keyPressed(KeyEvent e) {
   if (e.getKeyCode() == KeyEvent.VK_UP) {
     System.out.println("Hi from KeyListener");
JPanel contentPane = (JPanel) ablak.getContentPane();
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = contentPane.getInputMap(condition);
ActionMap actionMap = contentPane.getActionMap();
contentPane.setLayout(new FlowLayout());
contentPane.add(fooButton);
ablak.setVisible(true);

代码示例来源:origin: stackoverflow.com

setFocusable(true);
setLayout(new GridLayout(3, 3));
a.setEnabled(false);
add(a);
addKeyListener(new KeyAdapter() {
    if (e.getKeyCode() == KeyEvent.VK_A) {
      remove(a);
      JButton b = new JButton("B");
      add(b);
      add(a);
      revalidate();
      repaint();
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Test2());
frame.pack();
frame.setVisible(true);

代码示例来源:origin: stackoverflow.com

ui.add(text, BorderLayout.PAGE_START);
io = new JTextField(15);
Font font = io.getFont();
font = font.deriveFont(font.getSize() * 1.8f);
io.setFont(font);
io.setHorizontalAlignment(SwingConstants.TRAILING);
io.setFocusable(false);
text.add(io);
ui.add(buttons, BorderLayout.CENTER);
String[] keyValues = {
  "7", "8", "9", "/",
ui.setBorder(new EmptyBorder(5, 5, 5, 5));
Font f = b.getFont();
b.setFont(f.deriveFont(f.getSize() * 1.5f));
String s = KeyEvent.getKeyText(ke.getKeyCode());
JButton b = getButton(s);
if (b != null) {
  b.requestFocusInWindow();
  b.doClick();

代码示例来源:origin: stackoverflow.com

Container contentPane = getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
textArea.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
textArea.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);
JScrollPane scrollPane = new JScrollPane( textArea );
InputMap im = textArea.getInputMap();
KeyStroke tab = KeyStroke.getKeyStroke("TAB");
textArea.getActionMap().put(im.get(tab), new TabAction(true));
textArea.setText("Use Key Listener\n2\n3\n4\n5\n6\n7\n8\n9");
JScrollPane scrollPane = new JScrollPane( textArea );
scrollPane.getVerticalScrollBar().setFocusable(false);
textArea.addKeyListener(new KeyAdapter()
    if (e.getKeyCode() == KeyEvent.VK_TAB)
    if (e.getKeyCode() == KeyEvent.VK_TAB
    &&  e.isShiftDown())
textArea.setText("Add Traversal Keys\n2\n3\n4\n5\n6\n7\n8\n9");
JScrollPane scrollPane = new JScrollPane( textArea );
scrollPane.getVerticalScrollBar().setFocusable(false);
Set set = new HashSet( textArea.getFocusTraversalKeys(

代码示例来源:origin: stackoverflow.com

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main {
  public static void main(String[]args) {
    final JFrame frame = new JFrame();
    final JTextArea area = new JTextArea();
    area.setPreferredSize(new Dimension(200, 200));
    area.addKeyListener(new KeyAdapter(){
      @Override
      public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_ENTER) {
          area.setText("");
        }
      }
    });
    frame.add(area);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}

代码示例来源:origin: stackoverflow.com

public displayFullScreen() {
  setUndecorated(true);
  panel.setLayout(new FlowLayout(FlowLayout.CENTER));
  alarmMessage.setText("Alarm !");
  alarmMessage.setFont(new Font("Cambria",Font.BOLD,100));
  alarmMessage.setForeground(Color.CYAN);
  panel.add(alarmMessage);
  Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
  setBounds(0,0,screenSize.width,screenSize.height);
  panel.setBackground(Color.black);
  add(panel);
  addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent ke) {
      escapeHandler(ke);
  if(ke.getKeyCode() == ke.VK_ESCAPE) {
    displayFullScreen.this.dispose();

代码示例来源:origin: stackoverflow.com

setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
setTitle("Automato");
setLocationRelativeTo(null);
setLayout(new FlowLayout());
lbNumero.setFont(new Font("Arial", Font.PLAIN, 200));
lbNumero.setForeground(Color.red);
addKeyListener(this);
add(lbNumero);
setVisible(true);
int teclaPressionada = e.getKeyCode();

代码示例来源:origin: stackoverflow.com

JFrame frame = new JFrame();
JEditorPane editorPane = new JEditorPane();
editorPane.addKeyListener(new KeyAdapter() {
  @Override
  public void keyPressed(KeyEvent ev) {
    if (ev.getKeyCode() == KeyEvent.VK_C
        && (ev.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK) {
      JEditorPane editorPane = (JEditorPane) ev.getComponent();
frame.add(editorPane);
frame.pack();
frame.setVisible(true);

代码示例来源:origin: stackoverflow.com

setPreferredSize(new Dimension(500, 500));
setBackground(Color.black);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
testPanel.addKeyListener(new KeyAdapter() {
  @Override
  public void keyPressed(KeyEvent e) {
    super.keyPressed(e);
    switch(e.getKeyCode()) {
      case KeyEvent.VK_UP:
        System.out.println("Test");
add(testPanel);
testPanel.setFocusable(true);
testPanel.requestFocusInWindow();
pack();
setVisible(true);

代码示例来源:origin: stackoverflow.com

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
closeLabel.addKeyListener(this);
closeLabel.setFocusable(true);
add(closeLabel);
pack();
setVisible(true);
char key = input.getKeyChar();
if (key == 'x') System.exit(0);

代码示例来源:origin: skylot/jadx

@Override
  public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
      treeClickAction();
    }
  }
});

代码示例来源:origin: RaiMan/SikuliX2

private void myKeyTyped(KeyEvent e) {
 boolean shouldQuit = false;
 String allowed = " +-facrpostmnihqz"; // off e x
 if (e.CHAR_UNDEFINED != e.getKeyChar()) {
  if (e.getKeyChar() == VK_ESCAPE) {
   log.trace("action: quit request");
   shouldQuit = true;
  } else {
   String sKey = "" + e.getKeyChar();
   if (!allowed.contains(sKey)) {
    log.trace("keyTyped: %s", sKey);
    if (" ".equals("" + e.getKeyChar())) {
     if (masking) {
      maskingToggle = maskingToggle ? false : true;
    } else if ("x".equals("" + e.getKeyChar())) {
    } else if ("+".equals("" + e.getKeyChar())) {
    } else if ("-".equals("" + e.getKeyChar())) {
    } else if ("r".equals("" + e.getKeyChar())) {
    } else if ("p".equals("" + e.getKeyChar())) {
    } else if ("o".equals("" + e.getKeyChar())) {
    } else if ("s".equals("" + e.getKeyChar())) {

代码示例来源:origin: stackoverflow.com

import java.awt.event.*;
import java.awt.*;
import java.applet.*;

 public class KeyReader extends Applet{
  private static final long serialVersionUID = 1L;
  public void init(){
  TextField textBox = new TextField(" ");
  add(textBox);

  textBox.addKeyListener (new KeyAdapter() {
  public void keyPressed(KeyEvent e) {
  int keyCode = e.getKeyCode();
  System.out.println("You Pressed " + keyCode);
          }
        }
        );
      }

  }

相关文章