0

I have the code below which creates a button and registers an event on it.When a button is clicked it writes a data into .csv file.The getFullName() etc methods return JTexField.getText(). When ALL of JTextFields I mean every single JTextFields are filled with user input then writeDataIntoFile() is called otherwise it returns a message "Empty fields left". The problem is If I fill only getFullName() - reference of JTextField, writeDataIntoFile() is getting called. Any suggestions how to fix this?

        JButton registBtn = new JButton("register");
        add(registBtn);

        registBtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent evt) {
                try { 
                    if (getFullName() != ("") && getRegNum() != ("") &&  //It doesnt matter if i use .equils()
                        getItemName() != ("") && getNote() != (""))
                    {
                           writeDataIntoFile();
           }
                    else  
                         { 
                           JOptionPane.showMessageDialog(null, "Empty fields left.Please fill");

                         }
                } catch (IOException ex) {
                    System.out.Println("E), ex);
                }   
            }
        });
Ashford Tulgaa
  • 35
  • 1
  • 12
  • 1
    I don't see a particular problem with joining multiple conditions together via `&&`. I see that kind of construct frequently. You do, however, have a problem with using `!=` for String comparisons. – John Bollinger Mar 15 '17 at 17:15
  • 1
    You could do something like this: `if (getFullName().length() + getRegNum().length() + getItemName().length() + getNote().length() != 0)` or this: `if (!getFullName().isEmpty() && !getRegNum().isEmpty() && !getItemName().isEmpty() && !getNote().isEmpty())` – Joe Mar 15 '17 at 17:17
  • 1
    Also, John has a good point. Be careful comparing strings with the == and != operators. You probably want to use the equals method. For example, getFulleName().equals(""). – Joe Mar 15 '17 at 17:20

0 Answers0