Search code examples
javaswingjtextfield

Adding a character while user enters value


How can I create a method that automaticly adds a character when the user fills in a certain amount of characters.

Let's say I have to enter a code that is 12 characters long.
enter image description here

Each time I pass the fourth character a dash must be added. (4-5,8-9) in total 2 dashes.

enter image description here

I am a bit new to Java so I don't know where to start.

Thanks in advance.


Solution

  • Use a JFormattedTextField for which you can define an input mask

    JFormattedTextField textField = new JFormattedTextField();
    textField.setFormatterFactory(new DefaultFormatterFactory(new MaskFormatter("HHHH-HHHH-HHHH")));
    

    edit add a working example

    public class SimpleInputMask {
    
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("MaskFormatteExample");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel();
            JLabel label = new JLabel("input: ");
            panel.add(label);
    
            // define the text field with an input mask
            JFormattedTextField textField = new JFormattedTextField();
            textField.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
            try {
                String inputMask = "HHHH-HHHH-HHHH";
                textField.setFormatterFactory(new DefaultFormatterFactory(new MaskFormatter(inputMask)));
            } catch (ParseException ex) {
                // will be raised if the inputMask cannot be parsed
                // add your own exception handling here
            }
    
            panel.add(textField);
    
            frame.add(panel);
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }