简体   繁体   中英

Swing: text box focus lost event vs button clicked event

I have a Form with various textboxes(say around 10) .After the user fills value in each textbox, it is validated on focuslost event for the textbox.

public void focusLost(FocusEvent e)
    {

        JTextField tf = (JTextField)(e.getSource());
        String finalVal = tf.getText();
        try
        {
            validate(finalVal);
        }
        catch(NmfException ex)
        { 
            JOptionPane.showMessageDialog(parent, message, title,
                                    JOptionPane.ERROR_MESSAGE);//Error Message is passed
/* Error pop up is displayed when validation fails. Message text with an 'Ok' button is displayed and the code waits for ok to be clicked to execute rest of the code*/
            tf.setText(defaultVal);//Value is reset to default value
            return;
        }

    }

The form has a 'Add' button which gets the values from the UI(from the textbox) and sends it to the server.Ideally, since the values are validated at each textfield the value sent to the server should be valid inputs.

But my issue is, when an invalid input is given to a textfield(say -5 an invalid input) and 'Add' button is clicked at once. The focusLost event is triggered and the pop up is obtained,while the code waits for the 'OK' button in pop up to be pressed,the next event of button clicked is also called.So before the defaultVal can be set as textfield value,the Add button operation is done(there is no further validation in add operation) and invalid inputs are sent to the server.

How can ensure that Add operation is called only after the focusLost event operation is done.Please suggest a fix for the issue? What would be a best practice for such a scenario?

Set one Flag which should be check while click on 'Add'.

So if all validation should be true/OK then send to server.

if flag is false/invalid, while click on 'Add' then give user prompt with error message.

As per your scenario if any one try to add invalid value then focusLost event makes Flag -> false, and vice-versa.

Likewise need to design architecture of coding.

您还可以在文本字段上使用鼠标侦听器,并在mouseExited方法中进行验证

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM