如何重启javafx应用程序?



下面是重新启动没有fxml的JavaFX应用程序的代码。

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class HelloFX extends Application
{
boolean state = true;
@Override
public void start( final Stage primaryStage )
{
System.out.println( "state is " + state );
playGame();
System.out.println( "state is " + state );
final Button restartButton = new Button( "Restart" );
restartButton.setOnAction( __ ->
{
System.out.println( "Restarting app!" );
primaryStage.close();
Platform.runLater( () -> new HelloFX().start( new Stage() ) );
} );
primaryStage.setScene( new Scene( new StackPane( restartButton ) ) );
primaryStage.show();
}
/**
* Simulate a game play by changing the global state.
*/
private void playGame()
{
state = false;
}
/**
* @param args ignored.
*/
public static void main( final String[] args )
{
launch( args );
}
}

但是,我想用fxml。

我不知道如何在fxml中应用这段代码。

我的代码。

Main.java

package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}

public static void main(String[] args) {
launch(args);
}
}

Controller.java

package sample;
public class Controller {
}

sample.fxml

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<GridPane alignment="center" hgap="10" vgap="10" xmlns:fx="http://javafx.com/fxml/1" 
xmlns="http://javafx.com/javafx/11.0.1" fx:controller="sample.Controller">
<children>
<Button mnemonicParsing="false" onAction="#restart" text="restart" />
</children>
</GridPane>

我想重新启动我的JavaFX应用程序。

我不知道如何在fxml中应用这段代码。

如何使用fxml重新启动JavaFX应用程序?

你可以试试:

public void restartApplication()
{
final File currentFile = new File(TheCurrentClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
/* is it a jar file? */
if(!currentJar.getName().endsWith(".jar"))
return;
/* Build command: java -jar application.jar */
final String command = "java -jar " + currentJar.getPath();
final ProcessBuilder builder = new ProcessBuilder(command);
builder.start();
System.exit(0);
}

这基本上通过java -jar命令

重新启动程序

最新更新