Search code examples
javaoopclassfunction-callsmessage-passing

Java Object Oriented function calling between classes


I ma new in OOD and working on Academic project. I am facing a problem while programming it.

The scenario is that I have a main class in which I have made an object of "login" class and call its function.

Now in that "login" class function I create an object of jFrame class to show a login view, where user enters the login info and press login button.

Now I want that when user press login button I should pass that info to an authenticate function in my "login" class.

The problem is that how can I call that function (its a non-static function), and upon invalid info call a function of jFrame class to show error message.

And I want to do this function calling all over in my project.


Solution

  • Maybe you need to redesign your program a bit. The login class should not be creating a JFrame. Let the login class concentrate on authenticating users and its related functions. So something like this:

      public class Login{
    
          public boolean authenticate(String uname, String pword){
               return .......
          }
    
      }
    

    Whenever you need to use the functions of Login, you can instantiate it and call the function. You can create a JFrame for instance that prompts the user for username and password and in the action of the button:

             loginBtn.addActionListener(new ActionListener(){
                    public void actionPerformed(ActionEvent e){
    
                          Login login = new Login();
                          if(login.authenticate(txtUname.getText(), txtPWord.getText())){
                                  //display success on JFrame
                          }else{
                                  //display failure on JFrame
                          }
                    }
              });
    

    Where txtUname and txtPWord may be 2 JTextFields on you JFrame, and lginBtn may be a button on your JFrame.

    If you need to perform the same function somewhere else then you instantiate Login again and call the function.