Search code examples
javaaccess-modifiers

Accessing objects made in main method from other classes


Hey I'm trying to access an object I've made in the main method from another class but when I reference it in the other class it is not recognised. After some research I think this has something to do with access modifiers but I have tried making the object public only for a comment to appear saying "remove invalid modifier". Any pointers?

Sorry about this being so basic but I'm only a beginner and I'm finding this stuff quite tough.

Sorry for not mentioning! I am writing in Java. This is what I have:

public static void main(String[] args) {

    Mainframe mainframe = new Mainframe();
    mainframe.initialiseMF();       
    LoginPanel lp = new LoginPanel();
    mainframe.add(lp);
}

public class Mainframe extends JFrame {

public Mainframe () {
    // Set size of mainframe
    setBounds(0, 0, 500, 500);

}

public void initialiseMF (){
    // Get the size of the screen
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

    // Determine the new location of the mainframe
    int w = getSize().width;
    int h = getSize().height;
    int x = (dim.width-w)/2;
    int y = (dim.height-h)/2;

    // Move the mainframe
    setLocation(x, y);
    setVisible(true);
}

}

I am trying to do this statement in another class :

Container content = mainframe.getContentPane();   

Solution

  • Remember, the mainframe object is local to the main() method which is static. You cannot access it outside the class.

    Probably this would be a bit cleaner.

    public class Mainframe extends JFrame{
         public Mainframe(){
              initialiseMF ();
         }
    
         public void initialiseMF (){
              //do ur inits here
         }
    
    }
    

    Then do this,

    public class TheOtherClass{
    
        private Mainframe mainFrame;
    
        public TheOtherClass(){
            mainFrame = MainFrame.mainFrame; //although I would not suggest this, it will avoid the Main.mainFrame call
        }
    
        public void otherMethodFromOtherClass(JFrame mainFrame){
            Container content = mainFrame.getConentPane();
        }
    }