Search code examples
javaswingjtextfield

JTextField get values based on condition


Am using JTextField for get average.It means the average must be start with 0 to 100.so the textfield allow to access the 0 to 100 only.If I give 101 means the value don't added in the textfield.how to set the condition for this problem?


Solution

  • You have to use KeyListener where you can do the validation.

    For example

    final JTextField myTextField = new JTextField();
    myTextField.addKeyListener(new KeyListener() {
          public void keyPressed(KeyEvent keyEvent) {
    
          }
    
          public void keyReleased(KeyEvent keyEvent) {
    // Here write the comparison logic
                     if (Integer.parseInt(myTextField.getText()) > 100){
                         myTextField.setText(""); // Make it blank
                     }
          }
    
          public void keyTyped(KeyEvent keyEvent) {
          }
        });
    

    You can use KeyAdapter as well. Hope this helps.