// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.awt.GridLayout;

import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class MaxText extends JFrame {
    private static final int MAXLEN = 5;
    private JTextField[] tf = new JTextField[3];
    public MaxText() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(new GridLayout(tf.length, 1));
        for(int i = 0; i < tf.length; i++) {
            tf[i] = new JTextField();
            tf[i].getDocument().addDocumentListener(new DocumentListener() {
                public void changedUpdate(DocumentEvent evt) {
                }
                public void insertUpdate(DocumentEvent evt) {
                    if(evt.getDocument().getEndPosition().getOffset() - 1 >= MAXLEN) {
                        for(int j = 0; j < tf.length; j++) {
                            if(tf[j].getDocument() == evt.getDocument()) {
                                tf[(j + 1) % tf.length].requestFocus();
                            }
                        }
                    }
                }
                public void removeUpdate(DocumentEvent evt) {
                }
            });
            getContentPane().add(tf[i]);
        }
        pack();
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new MaxText();
                f.setVisible(true);
            }
        });
    }
}
