Is it possible to detect when someone presses Enter while typing in a JTextField in java? Without having to create a button and set it as the default.
A JTextField
被设计为使用ActionListener
就像一个JButton
是。请参阅addActionListener()
的方法JTextField
.
例如:
Action action = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("some action");
}
};
JTextField textField = new JTextField(10);
textField.addActionListener( action );
Now the event is fired when the Enter key is used.
此外,另一个好处是,即使您不想将按钮设为默认按钮,也可以与按钮共享侦听器。
JButton button = new JButton("Do Something");
button.addActionListener( action );
请注意,此示例使用Action
,它实现了ActionListener
因为Action
是一个具有附加功能的较新 API。例如,您可以禁用Action
这将禁用文本字段和按钮的事件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)