Reputation: 141
When I tried to call a swing program's main function
in a JavaFX program, the swing program runs normally. But when I tried to close the swing program, the JavaFx program also terminate. What's the reason? How can I solve it?
This is the JavaFX program code :
private void initStartGameButton() {
startButton.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if(!isPosValid()){
return;
}
String[] args = {"" + axePositionX, "" + axePositionY, "" + boatPositionX, "" + boatPositionY};
Game.main(args);
}
});
}
This is the Swing program code:
// The entry point of the game.
// This class loads up a JFrame window and
// puts a GamePanel into it.
package com.neet.DiamondHunter.Main;
import javax.swing.JFrame;
public class Game {
public static String[] args;
public static void main(String[] args) {
//save the args list.
Game.args = args;
JFrame window = new JFrame("Diamond Hunter");
window.add(new GamePanel());
window.setResizable(false);
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Upvotes: 0
Views: 225
Reputation: 209663
Replace
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
with
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Note also that you are violating Swing's threading rules. The action handler's handle(...)
method is executed on the JavaFX Application Thread, and consequently you are executing Game.main(...)
on the same thread. As documented, a swing JFrame
can only be created and displayed on the AWT event dispatch thread. You should modify your swing application so that it properly follows Swing's threading rules:
public class Game {
public static String[] args;
public static void main(String[] args) {
//save the args list.
SwingUtilities.invokeLater(() -> {
Game.args = args;
JFrame window = new JFrame("Diamond Hunter");
window.add(new GamePanel());
window.setResizable(false);
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
});
}
}
Upvotes: 2
Reputation: 285405
This:
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Will cause the JVM to exit when the window closes. Per the JFrame API:
EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications.
Instead set the default close operation to something else, perhaps
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Per the API:
DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and dispose the frame after invoking any registered WindowListener objects.
This will help clean up and release some of the resources that Swing uses.
Upvotes: 1