'How to restart a java program within the program

I'm working on a small Java game using Swing for school, and we need to implement a button that "starts a new game" when pressed. The problem is, the game takes multiple parameters from String[] args, so I can't just call the "main" function (where everything is instansiated) again from another class. Any way to do this?



Solution 1:[1]

You certainly can call main() from inside your application. But it's also certainly not what you want to do. Instead try moving the instantiation code into another function, most likely a constructor of some type of Game object. Then you can instantiate a new game from both main as well as some kind of restart function without any unintended consequences of calling main from inside your application.

Solution 2:[2]

You can use the following code to run a program. Unless your button and game are in the same package, be sure to import it (which will look like import packageName.className).

JButton newbutton = new JButton("New");
    newbutton.addActionListener(new ActionListener() {
        public void actionPerformed (ActionEvent e) {
            EventQueue.invokeLater(new Runnable() {
                 public void run() {
                      new className(); //run the class you want to here
                 }
            });
        }
    });

If you have any questions about this code, please comment below.

Solution 3:[3]

You have to lauch your program before exit it. Runtime rs = Runtime. getRuntime(); try { rs. exec("java -jar your_restartable_program.jar"); }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ktbiz
Solution 2
Solution 3 Feruz Sadirov