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?
-
2Move the code from the `main` method to a class which you can configure and resinstaniate – MadProgrammer May 04 '17 at 02:06
-
The broad answer is that it depends on what you do with those variables from `main`; it isn't like they've outright *disappeared* unless you're overwriting them... – Makoto May 04 '17 at 02:06
-
Possible duplicates [Restart Swing Application](http://stackoverflow.com/questions/9390481/restart-swing-application) – Fady Saad May 04 '17 at 02:09
3 Answers
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.

- 586
- 4
- 13
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.
You have to lauch your program before exit it.
Runtime rs = Runtime. getRuntime(); try { rs. exec("java -jar your_restartable_program.jar"); }

- 15
- 5