Frage

Hello I'm currently working in my java file. I'd like to add an event on JFormattedTextField when I press the enter key. This is my code

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.text.MaskFormatter;
    import java.awt.*;
    import java.text.ParseException;

    public class Test extends JFrame implements ActionListener
    {
        JFormattedTextField phoneField;
        Test()
        {
            setTitle("JFormatted Text");
    setLayout(null);
    MaskFormatter mask = null;
    try {
        mask = new MaskFormatter("##########");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    phoneField = new JFormattedTextField(mask);
    phoneField.setBounds(20, 20, 150, 30);
    phoneField.addActionListener(this);
    setVisible(true);
    setSize(200, 200);
    getContentPane().add(phoneField);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}

    public static void main(String[] args)
    {
        new Test();
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()== phoneField)
        {
            System.out.println("The numbers you enter are "+phoneField.getText());
        }
    }
    }

it works but their the user needs to enter 10 digits.

War es hilfreich?

Lösung 3

You could add a keyListener instead.

phonefield.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent evt) {
    if(evt.getKeyCode() == evt.VK_ENTER){
        System.out.println("The numbers you enter are "+phoneField.getText());
    }
    }
});

If this isn't your problem, you should expand a little and clarify.

EDIT: As comments and other answers pointed out, you should go for an ActionListener instead. Reasoning can be found below.

Andere Tipps

Add an ActionListener to the field. It is better than using the (low level) KeyListener and will conform to whatever that OS accepts as 'end of entry'.

Don't use KeyListener instead use DocumentListener.

It has the following methods which captures the changes in the JTextField

JTextField textField = new JTextField();
        textField.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void removeUpdate(DocumentEvent arg0) {
                // Gives notification that a portion of the document has been removed.

            }

            @Override
            public void insertUpdate(DocumentEvent arg0) {
                // Gives notification that there was an insert into the document.

            }

            @Override
            public void changedUpdate(DocumentEvent arg0) {
            // Gives notification that an attribute or set of attributes changed.

            }
        });
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top