用ActionListener处理在JTextField里按Enter事件

常常有这样的需求,填完一些JTextField后,直接按Enter键就执行动作,而不需要再按一下按钮。本来以为在加一个Keytyped事件的侦听器,然后读取输入的字符就可以确定了,但是试了几次都没有成功。后来查了一下JDK API,看到这样的话:

How the text field consumes VK_ENTER events depends on whether the text field has any action listeners. If so, then VK_ENTER results in the listeners getting an ActionEvent, and the VK_ENTER event is consumed. This is compatible with how AWT text fields handle VK_ENTER events. If the text field has no action listeners, then as of v 1.3 the VK_ENTER event is not consumed. Instead, the bindings of ancestor components are processed, which enables the default button feature of JFC/Swing to work.

看来是要用ActionLinstener, 如没有用的话,就会传给上层组件。

你可能感兴趣的:(jdk,swing)