Use other class methods and fields inside another

时间:2017-08-13 13:41:07

标签: java oop classloader

I have a conceptual question.( some questions ! ) Let explain it with a real project. I have a Login swing form,it has the main method and application starts from here.

  java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Login().setVisible(true);
        }
    }); // this method is inside main Method

The Login Form contains some TextFields and Buttons,And also some methods. ( For example when I press the Enter Button some authenticatation and action perform ) After press Enter Button, if authenticate success it goes to another form named MainTabbedForm. Now the question is about Object Oriented Programming and class loading. I want to access the Login Form form the MainTabbedForm. For example I want to dispose the Login Form after authentications successfully, And wanna do it in the MainTabbedForm constructor. I write a method inside the Login class to connect the Login to the MainTabbedForm. In this way :

public void disappearForm(MainTabbedForm form) {
this.form=form; // I already has defined a MainTabbedForm field in top of the Login class
this.dispose(); // Dispose the Login class
}

And use it in the constructor of the MainTabbedForm, Before using just declare a Login Form as a field in MainTabbedForm;

public MainTabbedForm(Login login) { 
   this.login=login;
   login.disappearForm(this)
}

But it gives me NullPointException because the Login has not initialize. And if i make a new class of Login, of course it is a new class and will not DO the thing i want, because is a new instance and not the first created Login in main method. Now I have a question, How can i connect these two class to each other? Of course I can make a static method to do my job ! But i do not want to do that in this way. I think because of this class loading and art of programming the frameworks and design patterns like OSGi and MVC and others has created, to mange loading and accessing services and objects and other things more dynamically, am i right? Now the reply to these answers are really appreciate !

1 个答案:

答案 0 :(得分:0)

Login你可以做到:

MainTabbedForm mtf = MainTabbedForm(); //create 
//set the required information using setters 
//for example set userName which is defined in Login to MainTabbedForm
mtf.setUserName(this.userName); 
//....
this.dispose(); //when no longer needed