Java - JTextField - 当用户按下“空格键”时调用函数。 [英] Java - JTextField - Call function when user press "space bar"
问题描述
我做了一些搜索,当用户按下空格键键时我没有找到如何调用函数,我有这样的代码:
I made some searches and I didn't find how to call a function when the user press the key "space bar", I have this code:
edtCodigos.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE){
callFunction();
}
}
)};
注意:我想避开空格,该键只用于调用函数
Note: I want to avoid the "space", the key will be used just to call the function
任何想法我该怎么做或代码样本都将不胜感激;)
Any ideas how can I do it or code samples will be appreciated ;)
推荐答案
用户习惯于输入空格键来完成收银员付款等操作。
"The users are used to type "space bar" to finish an operation like payment in a cashier."
就个人而言,我只会使用 ActionListener
,以便 Enter 键触发事件。它看起来更自然。
Personally, I would just use an ActionListener
so that the Enter key triggers the event. It just seems more natural.
import java.awt.event.*;
import javax.swing.*;
public class TestTextField {
public static void main(String[] args) {
final JTextField field = new JTextField(15);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("Enter Pressed: " + field.getText());
}
});
JOptionPane.showMessageDialog(null, field);
}
}
如果你想使用 Space ,您可以使用密钥绑定绑定字段的密钥
If you want to use Space, you can bind the key the field using Key Bindings
import java.awt.event.ActionEvent;
import javax.swing.*;
public class TestTextField {
public static void main(String[] args) {
final JTextField field = new JTextField(15);
InputMap imap = field.getInputMap(JComponent.WHEN_FOCUSED);
imap.put(KeyStroke.getKeyStroke("SPACE"), "spaceAction");
ActionMap amap = field.getActionMap();
amap.put("spaceAction", new AbstractAction(){
public void actionPerformed(ActionEvent e) {
System.out.println("Space Pressed: " + field.getText());
}
});
JOptionPane.showMessageDialog(null, field);
}
}
你甚至可以使用 DocumentListener ,用于侦听文本字段的基础文档中的更改,以及检查输入的最后一个字符是一个空格(但这似乎有点多 - 只是一些信息,你可以学习文本组件的工作: - )
You could even go as far as using a DocumentListener to listen for changes in the underlying document of the text field, and check the last character entered was a space (but this seems like a bit much - Just some info for you to learn the workings for text components :-)
选择你的味道。我喜欢第一个。
Pick your flavor. I like the first.
这篇关于Java - JTextField - 当用户按下“空格键”时调用函数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!