JavaFXML После завершения фонового процесса я хочу скрыть заставку и отобразить основную сцену - PullRequest
0 голосов
/ 01 ноября 2019

Отказ от ответственности - простите мою терминологию, на ней может не быть места.

Полностью функционирующее приложение, Я хочу улучшить функциональность потоков и производительность

при запуске,он будет отображать заставку в течение примерно 40 секунд, а затем отображает основной макет сцены. пока отображается заставка, он запустит процесс командной строки для записи вывода в текстовый файл. Этот процесс занимает 30 секунд.

Проблема - если процесс командной строки не завершенкогда управление передается на главную сцену, у главной сцены не будет ничего для чтения из файла .txt.

Я хочу, чтобы макет главной сцены отображался, как только процесс командной строки завершил запись вывода в файл,Не ждать 40 секунд и надеяться, что командный процесс завершен.

Основной класс Loader

открытый класс SplashLoader extends Application {

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("Splash.fxml"));
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.initStyle(StageStyle.UNDECORATED);
    stage.setResizable(false);
    stage.show();
}

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

}

SplashController открытый класс SplashController реализует Initializable {

static String ping = "";

@FXML AnchorPane ap;

//Loads the Speedtest.fxml into the rootpane to be displayed set to run 40 seconds after the splash screen has displayed
class ShowSpeedTestScreen extends Thread{
    @Override
    public void run(){
        try {
            Thread.sleep(30000);

            Platform.runLater(() -> {
                Stage stage = new Stage();
                Parent root = null; 
                try {  
                    root = FXMLLoader.load(getClass().getResource("SpeedTest.fxml"));
                } catch (IOException ex) {
                    System.out.println(ex.getMessage());
                }
                Scene scene = new Scene(root);
                stage.setScene(scene);
                stage.setResizable(false);
                stage.setTitle("It Help");
                stage.show();                   
                ap.getScene().getWindow().hide();
            });                
        } catch (InterruptedException ex) {}
    }
}

//On initialization of the splash screen
//Start network speedtest average 30 sec run time
//Create seperate thread to run in 40 seconds that sets the Speedtest.fxml layout to the stage via ShowSpeedTestScreen() class
//It is important that the runtime command has 30 seconds to finish its process else the speedtest will not be able to retrieve the download and upload speeds
@Override
public void initialize(URL url, ResourceBundle rb) {

    ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "mkdir C:\\Temp | fast -u > C:\\Temp\\speedtest.txt\"");
    try {Process process = builder.start();}
    catch (IOException ex) {}

    ping = checkPing();

    new ShowSpeedTestScreen().start();       
}    

}

Контроллер основного макета

Открытый класс SpeedTestController реализует Initializable {

//Nodes on the Layout from "SpeedTest.fxml"
@FXML
private Label lblDownloadNum;
@FXML
private Label lblPingNum;
@FXML
private Label lblTitle;
@FXML
private Label lblUploadNum;
@FXML
private Label lblmbps;
@FXML
private Label lblmbps2;
@FXML
private Label lblms;
@FXML
private AnchorPane rootPane;

AnchorPane netView;
String downloadSpeed = "";
String uploadSpeed = "";

@Override
public void initialize(URL url, ResourceBundle rb) {

    lblPingNum.setText(getPing());
    lblms.setVisible(true);

    downloadSpeed = checkDownloadSpeed();
    lblDownloadNum.setText(downloadSpeed);
    lblmbps.setVisible(true);

    uploadSpeed = checkUploadSpeed();
    lblUploadNum.setText(uploadSpeed);
    lblmbps2.setVisible(true);

    try {netView = FXMLLoader.load(getClass().getResource("NetworkView.fxml"));}
    catch(Exception ex){} 
}

//Parsing a txt file for the first line first word
//Set selected node to a content holder
private void setNode(Node node) {
    rootPane.getChildren().clear();
    rootPane.getChildren().add((Node) node);

    FadeTransition ft = new FadeTransition(Duration.millis(1500));
    ft.setNode(node);
    ft.setFromValue(0.1);
    ft.setToValue(1);
    ft.setCycleCount(1);
    ft.setAutoReverse(false);
    ft.play();
}

//Creates new Stage and scene to display second Gui Window
//Passes control to the NetworkViewController
@FXML
private void changeSceneButtonPushed(javafx.event.ActionEvent event) throws IOException {
    setNode(netView);
}

}

...