Search code examples
javaapplettextfield

Specific input from user


I started making my own little applet with buttons and labels and text fields, but I want to when you enter a certain thing in the text field it does something. I tried if(fieldTextField.equals(mystringhere)) { but it doesn't work. Could you post an example of what I want?


Solution

  • You have to use a KeyListener, so that you can listen to keyboard and check your text everytime the user types something in your field:

    KeyListener kl = new KeyAdapter(){
        public void keyTyped(KeyEvent evt)){
            if(yourTextField.getText().equals(yourString){
                //do something here
            }
        }
    };
    yourTextField.addKeyListener(kl);
    

    Note that yourTextField must be an instance variable or a local final variable in order to be used in the KeyListener methods