2

I have a small issue with my updateButtonResults button. I have JOptionPane Message Dialogs that are programmed to pop up when the user updates the four fields First Name, Last Name, E-mail and Sign-up date. My problem is all 4 messages pop up, even if I only update one field. Example: I update a customers last name, the message dialogs will pop up in this order (First name, Last name, E-mail, Sign-up date).

Here is my code

//method for buttons on 'resultFrame'
public void BtnAction3() 
{                        
  updateButtonResults.addActionListener(
        new ActionListener()
        {
           //method for events that will be performed when updateButton is pressed
           public void actionPerformed(ActionEvent e) 
           {
              //instanciates variables to text in textfields
              String fname = fNameTextBoxResults.getText();
              String lname = lNameTextBoxResults.getText();
              String email = eMailTextBoxResults.getText();
              String signUpDate = signUpTextBoxResults.getText();

              try
              {
                 //statement that checks to make sure user enters only letters
                 if(fname.matches("[a-zA-Z]+"))
                 {
                    //updates 'Fname' field in db to text that user inputted in 'fname' textfield
                    rs2.updateString("Fname", fname);
                    JOptionPane.showMessageDialog(null, "Customer first name been updated!");
                 }

                 //statement that prompts user if they enter something other letters
                 else
                 {
                    JOptionPane.showMessageDialog(null, "Please enter first name in correct format!");
                    fNameTextBoxResults.setText("");
                 }

                 //statement that checks to make sure user enters only letters
                 if(lname.matches("[a-zA-Z]+"))
                 {   
                    //updates 'Lname' field in db to text that user inputted in 'lname' textfield                      
                    rs2.updateString("Lname", lname);
                    JOptionPane.showMessageDialog(null, "Customer last name been updated!");
                 }

                 //statement that prompts user if they enter something other letters
                 else
                 {
                    JOptionPane.showMessageDialog(null, "Please enter last name in correct format!");
                    lNameTextBoxResults.setText("");
                 }

                 //statement and actions if user enters a '.'
                 if(email.contains("."))
                 {  
                    //gets last period in "email"
                    int emailDotCheck = email.lastIndexOf(".");

                    //substring to period in variable "emailDotCheck"
                    String extensionCheck = email.substring(emailDotCheck);

                    //statement and actions if user doesn't enter email correctly           
                    if(!email.contains("@") || !extensionCheck.matches("\\.[a-z]{3}"))
                    {
                       JOptionPane.showMessageDialog(null, "Please enter email in correct format!");
                       eMailTextBoxResults.setText("");
                    }                   

                    //statement and actions if user enters email correctly
                    else
                    {
                       //updates 'E-mail' field in db to text that user inputted in 'email' textfield
                       rs2.updateString("E_mail", email);
                       JOptionPane.showMessageDialog(null, "Customer E-mail been updated!");
                    }
                 }

                 //action if user doesnt enter email correctly
                 else
                 {
                    JOptionPane.showMessageDialog(null, "Please enter email in correct format!");
                    eMailTextBoxResults.setText("");
                 }

                 //instance variables for 'signUpDate'
                 int month = 100;
                 int day = 100;
                 int year = 10000;

                 if(signUpDate.matches("\\d{2}/\\d{2}/\\d{4}"))
                 {
                    //instance variables
                    String monthStr = signUpDate.substring(0,2);
                    String dayStr = signUpDate.substring(3,5);
                    String yearStr = signUpDate.substring(6);

                    //parsing intstance variables to Integers
                    month = Integer.parseInt(monthStr);
                    day = Integer.parseInt(dayStr);
                    year = Integer.parseInt(yearStr);

                    //statement and actions if user doesn't follow correct format
                    if(month > 12 || day > 31 || year > 2100)
                    {
                       JOptionPane.showMessageDialog(null, "Please enter date in correct format! (dd/MM/yyyy)");
                       signUpTextBoxResults.setText("");
                    }

                    //statements and actions if user enters date correctly
                    else
                    {
                       //updates 'Sign-up date' field in db to text that user inputted in 'signUpDate' textfield
                       rs2.updateString("Sign_up_date", signUpDate);
                       JOptionPane.showMessageDialog(null, "Customer Sign-up date been updated!");
                    } 
                 }

                 //statement and actions if user doesn't follow correct format           
                 else 
                 {
                    JOptionPane.showMessageDialog(null, "Please enter date in correct format! (dd/MM/yyyy)");
                    signUpTextBoxResults.setText("");
                 }

                 //updates row in db
                 rs2.updateRow();
                 //JOptionPane.showMessageDialog(null, "Customer has been updated!");

              }

              catch(Exception ex)
              {

              }          
           }          
        });

I'm trying to learn to walk through my code, I have debugged it, but still couldn't figure the logic error out.

Thanks for any help

javaGeek
  • 304
  • 1
  • 4
  • 11
  • 2
    Well, the body of this listener has an `if(fname...` that will show a dialog in the `if` part and in the `else` part, so it displays one dialog no matter what. Then it has `if(lname...` that also shows a dialog in the `if` part and in the `else` part, so that also displays a dialog no matter what. Then you have two more `if`s that are the same way. They display dialogs no matter which path the code takes. If you want it not to display a dialog in some cases, you'll have to add logic to tell it not to display a dialog in those cases. – ajb Mar 18 '14 at 00:48
  • I don't think I can provide any more help without knowing (1) what kinds of components your `fNameTextBoxResults`, `lNameTextBoxResults`, are, and (2) under what conditions you want the dialog box to show up (text differs from the previous version? user has entered a key in a text field? something else?). – ajb Mar 18 '14 at 00:59
  • Yeah, I have dialogs showing up if the user updated the name correctly, in that case a dialog should show up saying that specific field has been updated. I also have a dialog popping up if the user enters into an updated field incorrectly, in that case i have the dialog popping up and saying please enter field in correct format. My problem is with all the dialogs in the "if" statements. – javaGeek Mar 18 '14 at 01:02
  • They are both JTextFields. The conditions are to only pop up when that specific textfield was updated. – javaGeek Mar 18 '14 at 01:04

2 Answers2

0

You have four text fields:

fNameTextBoxResults
lNameTextBoxResults
eMailTextBoxResults
signUpTextBoxResults

Rather than attempting to validate all of the input at once, let's try to make this code a little more modular. Separate all of the logic pertaining to a specific field and add it as an ActionListener to that field. Example:

 fNameTextBoxResults.addActionListener(
    new ActionListener()
    {
       public void actionPerformed(ActionEvent e) 
       {
             //statement that checks to make sure user enters only letters
             if(fname.matches("[a-zA-Z]+"))
             {
                //updates 'Fname' field in db to text that user inputted in 'fname' textfield
                rs2.updateString("Fname", fname);
                JOptionPane.showMessageDialog(null, "Customer first name been updated!");
             }

             //statement that prompts user if they enter something other letters
             else
             {
                JOptionPane.showMessageDialog(null, "Please enter first name in correct format!");
                fNameTextBoxResults.setText("");
             }
       }
    });

Rinse and repeat for the other three fields. If you have some finalizing type of action required, then you can do that with updateButtonResults. Otherwise, the button is unnecessary altogether.

Azar
  • 1,086
  • 12
  • 27
  • I thought it would all need to be under the "updateButtonResults" "ActionListener". Because when each if/else statement passes in the if statement, it updates my database to that specific field in my database. Does that make sense? – javaGeek Mar 18 '14 at 01:12
  • is it possible to do a nested ActionListener? – javaGeek Mar 18 '14 at 01:13
  • This totally changes the behavior of the UI, so calling it a way to "make the code more modular" is incorrect. Refactoring isn't supposed to change behavior. – ajb Mar 18 '14 at 01:15
  • @ajb Does it make sense to validate the input one box at a time, all at once? What if one box contains incorrect data? It still pushes a partial update! This way makes it clear to the user that what they enter is automatically updated, and it notifies them immediately when they make a mistake. – Azar Mar 18 '14 at 01:18
  • @javaGeek Look at the example I provided. It takes the data from `fNameTextBoxResults`, which I presume contains the first name of your customer. It then validates the data, as per your specifications. Then, it updates the `Fname` field in your db, or gives the error message. You create one of these for each field you need to validate, and it "updates [your] database to that specific field..." – Azar Mar 18 '14 at 01:24
  • What I am confused about is if I make "First name, Last name, E-mail, Sign-up date" all seperate ActionListeners, how will they update to my database with "updateButtonResults" no longer having that logic inside it? – javaGeek Mar 18 '14 at 01:25
  • @Azar Everybody has different opinions about what makes for the best user experience. And it will be different from one app to the next, and it may depend on who the intended users are. The question was about how to modify his code to produce the UI he wanted, not about whether we like his UI design choices. – ajb Mar 18 '14 at 01:26
  • @javaGeek The same way they would before, using `rs2.updateString("whatever", whatever);` – Azar Mar 18 '14 at 01:26
  • Maybe this is "blowing over my head", but will it update once I close the application? Because now I have it set it up to update the fields in my db when the update button is pushed... – javaGeek Mar 18 '14 at 01:27
  • @javaGeek Sorry, but I can't really say what's going to happen when your application is closed. Using the above setup, the db will be updated when a valid entry is given to a text field. You _can_ set it up to attempt to update all at once, but there's no real benefit to that, with the way you set it up. Both your code and mine have the ability to push a partial update, and that's what I was trying to preserve. If you want to update **only** when all four fields are validated, then that's a different story. – Azar Mar 18 '14 at 01:33
  • ok, so what user action will have to be carried out for the update to go to my db? Just correct format in textfields? no button press? – javaGeek Mar 18 '14 at 01:37
  • @javaGeek Yes, exactly. – Azar Mar 18 '14 at 01:39
  • @Azar do you know if there is a way to check and see if a textfield has been modified? – javaGeek Mar 18 '14 at 02:00
  • @javaGeek If you mean modified, but the user has not pressed enter, then: http://stackoverflow.com/questions/3953208/value-change-listener-to-jtextfield – Azar Mar 18 '14 at 02:02
0

Instead of using an anonymous class that extends ActionListener, you might want to define a named class that extends it, and defines a constructor by which you could pass in data such as the previous values of the text fields:

class MyActionListener extends ActionListener {  // lousy name, but ...
    public MyActionListener(String prevFirstName, String prevLastName, String prevEMail, String prevSignUp) {
        this.prevFirstName = prevFirstName; ... and so on
    }
    public void ActionPerformed(ActionEvent e) {
        ... what you already have, except that you can say things like
        if (!fname.equals(prevFirstName)) {
            ... now you can do your dialog and it won't show up unless the names
            ... are different
        }
        ...
    }
}

and then set it like this:

public void BtnAction3() 
{                        
  updateButtonResults.addActionListener(
        new MyActionListener(firstName, lastName, eMail, signUp));
}
ajb
  • 31,309
  • 3
  • 58
  • 84