0

I am making a gift code app and i wanted to know if there was a way to make the TextField your typing in move to the next TextField when you reach a certain amount of characters. So if there were 4 textfields next to each other when i fill the first one with 4 characters instead of hitting tab it moves on to the next jtextfield and so on till it reaches the end

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Bill Nye
  • 831
  • 1
  • 10
  • 15
  • 2
    do you know how to detect when text area has 4 characters ? do you know how to focus a textarea programmatically ? then you can do it .can you show your codes ? – Madhawa Priyashantha Apr 10 '16 at 02:56
  • No i do not, and what code would you like? All it is is JTextField textField = new JTextField(3); And then i add it to the JPanel. – Bill Nye Apr 10 '16 at 02:58
  • 1
    here is 2 http://stackoverflow.com/questions/6723257/how-to-set-focus-on-jtextfield and http://stackoverflow.com/questions/30582795/how-to-get-the-number-of-character-in-a-jtextarea – Madhawa Priyashantha Apr 10 '16 at 02:59
  • I came up with a pretty bad solution but at least it works. – Bill Nye Apr 10 '16 at 03:38
  • This concept is demonstrated [here](http://stackoverflow.com/questions/25477999/jtextarea-filters-and-or-inputs-of-time-000000-java/25496932#25496932) – MadProgrammer Apr 10 '16 at 05:32

1 Answers1

2

What you're basically asking can be easily achieved by using a DocumentListener, for example...

public class MoveFocusForwardHandler implements DocumentListener {

    private int maxLength;

    public MoveFocusForwardHandler(int maxLength) {
        this.maxLength = maxLength;
    }

    public int getMaxLength() {
        return maxLength;
    }

    @Override
    public void insertUpdate(DocumentEvent e) {
        documentChanged(e);
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        documentChanged(e);
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        documentChanged(e);
    }

    protected void documentChanged(DocumentEvent e) {
        if (getMaxLength() > 0) {
            if (e.getDocument().getLength() >= getMaxLength()) {
                KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
            }
        }
    }

}

Which is demonstrated here

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366