简体   繁体   English

如何将侦听器添加到JTextField的上下左右箭头?

[英]How to add a listener to a JTextField for up, down left, right arrow?

I need to write an arrow listener for my JTextField. 我需要为我的JTextField写一个箭头侦听器。 if a try with: 如果尝试:

public void keyTyped(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                ......
            }
}
...

This is not good.( I think that JTextField is not responding to a special key listener.) 这不好。(我认为JTextField没有响应特殊的键侦听器。)

I know the accepted answer given above will work, but this is not the way it SHOULD be done in Swing. 我知道上面给出的可接受的答案会起作用,但是这不是应该在Swing中完成的方式。 KeyListeners should generally only be used in AWT applications because they don't support a more abstract API. 通常,KeyListeners只应在AWT应用程序中使用,因为它们不支持更抽象的API。

When using Swing you SHOULD be using Key Bindings. 使用Swing时,应该使用键绑定。 All Swing components use Key Bindings. 所有Swing组件都使用键绑定。 The Key Bindings blog entry gives some basics on how to use them and contains a link to the Swing tutorial on "How to Use Key Bindings" for more detailed information. 密钥绑定”博客条目提供了有关如何使用它们的一些基础知识,并包含指向Swing教程“如何使用密钥绑定”的链接,以获取更多详细信息。

You have to use keyPressed or keyReleased here. 您必须在此处使用keyPressed或keyReleased。 Quoting from SUN's API javadoc: 引用SUN的API javadoc:

"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 它们是在输入Unicode字符时生成的

Therefore, the keyTyped method will not be called for the arrow keys, as they do not generate Unicode characters. 因此,将不会为箭头键调用keyTyped方法,因为它们不会生成Unicode字符。

You can add your own KeyListener via addKeyListener method provided for every java.awt.Component . 您可以通过为每个java.awt.Component提供的addKeyListener方法添加自己的KeyListener In your Listener, use keyPressed . 在您的侦听器中,使用keyPressed

Arrow keys are action keys, you can verify this event via isActionKey : 箭头键是动作键,您可以通过isActionKey验证此事件:

Returns true if the key firing the event is an action key. 如果触发事件的键是操作键,则返回true。 Examples of action keys include Cut, Copy, Paste, Page Up, Caps Lock, the arrow and function keys . 操作键的示例包括剪切,复制,粘贴,向上翻页,大写锁定, 箭头 和功能 This information is valid only for key-pressed and key-released events . 此信息仅对按键和按键释放事件有效

See also: http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html 另请参阅: http : //java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html

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

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