Search code examples
javaswingactionlistenerjformattedtextfield

How to get text and respond to enter press on JFormattedTextField


I recently added a MaskFormatter to my JFormattedTextField class. Previously an ActionListener was responding to the code and getting the text using the .getText() method worked fine. With the new MaskFormatter getting the text returns " " and enter presses don't work (the ActionListener stopped responding to the box).

Here is the entire JFormattedTextField class:

package swing;

import game.Main;
import java.awt.Font;
import javax.swing.JFormattedTextField;
import javax.swing.text.MaskFormatter;
import window.Listener;

@SuppressWarnings("serial")
public class TextField extends JFormattedTextField
    {
    public TextField(int size, String text) 
       //TODO limit to number input and 3 character input only
    {
        super(createFormatter());

        Font font = new Font("AGENCY FB", Font.BOLD, 30);

        this.setFont(font);
        this.setColumns(size);
        this.setSize(100, 100);
        this.setText(text);
    }

    private static MaskFormatter createFormatter()
    {
        MaskFormatter formatter = null;
        try 
        {
            formatter = new MaskFormatter("###");
        } 
        catch (java.text.ParseException exc) 
        {
            System.err.println("formatter is bad: " + exc.getMessage());
            System.exit(-1);
        }
        return formatter;
    }
}

Solution

  • Type 3 digits and press Enter, it works for me.

    public class FieldAction extends JFrame {
    
        FieldAction() {
    
            MaskFormatter mask = null;
            try {
                mask = new MaskFormatter("###");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            final JFormattedTextField textField = new JFormattedTextField(mask);
            textField.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
    
                    System.out.println(textField.getText());
                }
            });
    
            add(textField, BorderLayout.CENTER);
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
            setVisible(true);
        }
    
        public static void main(String[] args) {
    
            new FieldAction();
        }
    }