I am making a string array so user can type whatever they want.
the problem the code i have below user can enter &, alt, up, @, in string array.
I want user to enter letters and numbers only, and 1st char has to be letter. I couldnt find any method for it.

int z = 0;
String username[] = new String[3];

public void keyPressed(KeyEvent e)
    {
        int keys = e.getKeyCode();

        username[z] = KeyEvent.getKeyText(keys);
        e.consume();                  
    }

public void keyReleased(KeyEvent e)
{ 
    int keys = e.getKeyCode();

    z++;
    e.consume(); 
}

check whether z is 0, if so, and your 'keys' is not a letter (it might come in handy to use the getKeyChar() method instead of the getKeyCode() method)

so ... if this char is not a letter, don't add it to username, don't increase the value of z and call the consume method (don't call this method by default).

also, just using the keyReleased method will help, too. there's no reason to split the code up in several methods. further more, keyPressed might run more then once, making your code less efficiƫnt.

a bit the same for your second requirement.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.