Gavin Coll
Gavin Coll

Reputation: 19

How to rewrite main class as a Public Void method to be called from another class

I have written my program around the main MonopolyGame.java game class - however - I am adding features such as splash screens etc; and I would like to call each of these from a separate class (RunFile.java) . How do I rewrite the following part of my main class so that it can be called from the RunFile.java. When I try to do this I get the following error:

The method MonopolyGame() is undefined for the type MonopolyGame

MonopolyGame.java

public class MonopolyGame extends JFrame{

// PRIVATE STATIC/DECLARATIONS ARE HERE

public static void main(String[] args) throws Exception {

{
    //THIS IS WHERE I USED TO CALL THE SPLASH SCREEN

 // SplashScreen s = new SplashScreen(8000);
 // s.Splash();

        EventQueue.invokeLater(new Runnable() {

        public void run() {

            try {
                MonopolyGame window = new MonopolyGame();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    });


}}


  /**
  * Create the application.
  */
public MonopolyGame() 
{

    try {
        initialize();
          for(int i = 0; i < 41 ; i++)
          {
              properties[i]=new Props();
          }
          setProperties();
    }
    catch (InterruptedException e) 
    {
        e.printStackTrace();
    }
}



public void initialize()  throws InterruptedException {
    //REST OF PROGRAM

RunFile.java

public class RunFile{

public static void main(String[] args)
{
SplashScreen s = new SplashScreen(8000);
s.Splash();

MonopolyGame m = new MonopolyGame();
m.MonopolyGame();
}
}

Upvotes: 0

Views: 176

Answers (2)

Paul Back
Paul Back

Reputation: 1319

You don't need to rewrite the MonopolyGame() class, you can simply reflect the MonopolyGame() main method in your RunFile class.

public class RunFile {
    public static void main(String[] args) {
        Class<?> aClass = Class.forName(MonopolyGame.class.getName());
        Method meth = aClass.getMethod("main", String[].class);
        meth.invoke(null, (Object) args);
    }
}

Upvotes: 0

Daniel Bickler
Daniel Bickler

Reputation: 1140

All you need to do is remove m.MonopolyGame(). Since it has the same name as the class, it is a Constructor and so when you do MonopolyGame m = new MonopolyGame(); it is running the logic inside of there so you don't need to do it again.

If you do want to call it separately, you should change the name of the method to something besides the classname (and add a return type such as void)

Upvotes: 1

Related Questions