Home » Java » Java – can't resolve an object initiated in a public method?

Java – can't resolve an object initiated in a public method?

Posted by: admin October 26, 2017 Leave a comment

Questions:

So, I’m just starting out with java and I was working on a new GUI. I made a method that makes my JFrame, sets its default location, close operation, background colour etc.
I made a separate method for this to keep it out of the main code for the sake of tidiness. I already know how to solve this method if I just put all of those things in the main method.
This is the code:

public class Main {

    public static void makeWindow(){

        JFrame mainWindow = new JFrame();
        mainWindow.setVisible(true);
        mainWindow.setPreferredSize(new Dimension(400,400));
        mainWindow.pack();
        mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainWindow.setLocationRelativeTo(null);

    }

    public static void main(String args[]){

        makeWindow();

        JPanel mainPanel = new JPanel();
        mainWindow.add(mainPanel);

    }
}

I get an error in my main method saying that “mainWindow” can’t be resolved. Why is this? is it because I made the mainWindow object in the other method? Is there a way to resolve this issue without putting everything from the makeWindow() method into the main method?

Thanks.

Answers: