简体   繁体   English

Java Swing-KeyListener

[英]Java Swing - KeyListener

How can I know when the key typed change my text? 我怎么知道键入的键何时更改了我的文本? Or if the key is a char? 还是如果键是一个字符?

The interface KeyListener contain three methods: 接口KeyListener包含三种方法:

void keyTyped(KeyEvent) void keyTyped(KeyEvent)
void keyPressed(KeyEvent) void keyPressed(KeyEvent)
void keyReleased(KeyEvent) void keyReleased(KeyEvent)

So, if you get the char in the KeyEvent object like: 因此,如果您在KeyEvent对象中获得char,例如:

if ("a".equals(KeyEvent.getKeyChar()))
    System.out.println("It's a letter")

i guess you want to know wether typing a specific key actually prints a char or is some "invisible" control character or something: 我猜您想知道是否键入一个特定的键实际上会打印一个字符或某些“不可见”的控制字符或其他内容:

in this case you can check the typed key in the KeyEvent which gets passed into the implemented methods of the KeyListener: 在这种情况下,您可以在KeyEvent中检查键入的键,该键会传递到KeyListener的实现方法中:

this quick example should work, although i didnt test it. 这个快速的示例应该可以工作,尽管我没有对其进行测试。 It constructs a new String on the char returned by the KeyEvent, than invokes the length() method to chekc if the char created a readable character in the String. 它在KeyEvent返回的char上构造一个新的String,然后如果char在String中创建了可读字符,则调用length()方法进行检查。 kinda hacky but i hope you get the gist of it 有点hacky,但我希望你能理解

public void keyReleased(KeyEvent ke){
    if (new String(ke.getKeyChar()).length() == 0){
        // do something important...
    }
}

alternativley you can use ke.getKeyCode() and check vs the static fields in KeyEvent (VK_F12,VK_ENTER...) 您可以使用ke.getKeyCode()并检查KeyEvent中的静态字段(VK_F12,VK_ENTER ...)

check here: 在这里检查:

http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html

You need a document listener. 您需要一个文档监听器。 See the oracle docs for more information: How to Write a Document Listener 有关更多信息,请参见oracle文档: 如何编写文档监听器

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

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