Java - JTextField - Call function when user press “space bar”

走远了吗. 提交于 2019-12-04 05:51:04

问题


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 ;)


回答1:


"The users are used to type "space bar" to finish an operation like payment in a cashier."

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);
    }
}

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);
    }
}

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.



来源:https://stackoverflow.com/questions/25447485/java-jtextfield-call-function-when-user-press-space-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!