简体   繁体   English

Java:您实际上如何使用KeyListener?

[英]Java: How do you actually use KeyListener?

I've been searching everywhere for how to take input from the keyboard. 我一直在到处寻找如何从键盘输入信息。 I can find a ton of resources for how to modify what keylistener does on key press, I can find how to add it to a swing text line, and plenty of other miscellaneous things about it. 我可以找到大量有关如何修改按键侦听器在按键上所做的工作的资源,可以找到如何将其添加到挥杆文本行中的方法,以及许多其他相关内容。 But I can't find out how to actually put it in a file and use it. 但是我不知道如何将其实际放入文件中并使用它。

For now I just want to have a main class whose main function just has an endless loop, and everytime you press a key it prints "Key _ has been pressed". 现在,我只想拥有一个主类,其主函数仅有一个无限循环,并且每当您按下一个键时,它都会显示“键_已被按下”。 How do I do this? 我该怎么做呢?

I've made a MyKeyListener that extends KeyAdapter that includes the system.out.print of the string under keyPressed (I assume this is workable). 我已经制作了一个MyKeyListener,它扩展了KeyAdapter,其中包括在keyPressed下的字符串的system.out.print(我认为这是可行的)。 But what do I put in the main class to actually use it? 但是我要在主类中使用什么呢? Including it and initializing isn't enough. 仅仅包含它并进行初始化是不够的。

Here is my key listener file : ` 这是我的关键侦听器文件:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class GKeyListener extends KeyAdapter {

public void keyPressed(KeyEvent e){
    System.out.println("Key Pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e){
    System.out.println("Key Released: " + e.getKeyChar());
}
public void keyTyped(KeyEvent e){
    System.out.println("Key Typed: " + e.getKeyChar());
}

Here is a main file im working with and don't know where to go from: import java.awt.KeyEventDispatcher; 这是一个主要文件,我正在使用它,并且不知道从哪里可以找到:import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; 导入java.awt.KeyboardFocusManager; import java.awt.event.KeyEvent; 导入java.awt.event.KeyEvent;

public class tempMain {
public static void main(String[]  args){
    while(true){
        GKeyListener listen =new GKeyListener();
        //addKeyListener(listen);
    }
}

The KeyListener is a class of the Java AWT GUI framework. KeyListener是Java AWT GUI框架的一类。 It is part of the AWT event handling system, eg used to capture key events of text input components (such as TextArea, TextField etc.). 它是AWT事件处理系统的一部分,例如,用于捕获文本输入组件(例如TextArea,TextField等)的关键事件。

Without a component, it doesn't make much sense to use the KeyListener. 没有组件,使用KeyListener就没有多大意义。

If you want to do some experiments, you can capture key input without a text input component, using the KeyboardFocusManager . 如果要进行一些实验,则可以使用KeyboardFocusManager捕获不带文本输入组件的键输入。 This example shows both, binding a KeyListener to a text component and using the global KeyboardFocusManager . 此示例同时显示了将KeyListener绑定到文本组件和使用全局KeyboardFocusManager

public class KeyExample extends JFrame {
    public KeyExample() {
        JTextField jTextField = new JTextField(20);
        jTextField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                System.out.println("KeyListener: " + e.getKeyChar());
            }
        });
        add(jTextField);
        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
            @Override
            public boolean dispatchKeyEvent(KeyEvent e) {
                System.out.println("KeyEventDispatcher: " + e.getKeyChar());
                return false;
            }
        });
        new KeyExample().setVisible(true);
    }
}

You should use the KeyboardFocusManager only in rare situations. 仅在极少数情况下才应使用KeyboardFocusManager Normally, handling events using the KeyListener should be enough. 通常,使用KeyListener处理事件就足够了。

What this code does: 该代码的作用:

public class tempMain {
public static void main(String[]  args){
    while(true){
        GKeyListener listen =new GKeyListener();
        //addKeyListener(listen);
    }
}

is repeatedly create a KeyListener, thousands of times ! 数千次重复创建KeyListener! It does nothing with the KeyListener of use, and again creates thousands of KeyListeners when only one is necessary. 它与使用的KeyListener无关,并且在仅需要一个KeyListener时又创建了数千个KeyListener。 Instead you should consider the following: 相反,您应该考虑以下几点:

  • Create a GUI first. 首先创建一个GUI。 KeyListeners don't work and don't make sense without a Swing or AWT GUI. 如果没有Swing或AWT GUI,KeyListener将无法正常工作。 Prefer use of Swing over AWT. 与AWT相比,优先使用Swing。
  • Add the Single KeyListener to a component of the GUI that has focus. Single KeyListener添加到具有焦点的GUI的组件中。
  • Seriously consider using Key Bindings in place of a KeyListener for greater flexibility and code reusability. 认真考虑使用键绑定代替KeyListener以获得更大的灵活性和代码可重用性。

Edit 编辑
You state in comment, 您发表评论,

but without adding a text field I'm not sure how to actually call the listener to actually exist and be working 但没有添加文本字段,我不确定如何实际调用侦听器以实际存在并正常工作

  • For the record, you should never use a KeyListener with a JTextComponent such as a JTextField as there are much better and safer ways to trap input in these components. 为了记录在案,您永远不要将KeyListener与JTextComponent(例如JTextField)一起使用,因为存在更好和更安全的方法来将输入捕获在这些组件中。
  • It sounds as if you want a general OS-wide key listener. 听起来好像您想要一个通用的操作系统范围的按键侦听器。 If so, you're barking up the wrong tree as Java does not easily support this. 如果是这样,那么您就树错了树,因为Java不容易支持这一点。
  • For this sort of functionality you need to tie into the OS with either JNA or JNI. 对于这种功能,您需要使用JNA或JNI绑定到操作系统。
  • Or use a 3rd party library that gives your app this functionality 或使用为您的应用提供此功能的第三方库
  • Or tie into a utility program such as AutoIt to give your app this functionality. 或者绑定到诸如AutoIt之类的实用程序中,以为您的应用程序提供此功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM