alex suhaiö
alex suhaiö

Reputation: 139

Timeline loop don't start after event

i am learing more about javaFx and especially of Timeline, but i go already a problem. After i press the "start" button, the timeline loop dont start. I dont get any error, so i dont know why the timeline loop never start.

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 *
 */
public class StartServer extends Application {

    Stage window;

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        TextField txtPort = new TextField();
        Label lblPort = new Label("Number");
        Button startServer = new Button("Start");

        startServer.setOnAction(e-> startServer(Integer.parseInt(txtPort.getText())));

        GridPane gridPane = new GridPane();
        gridPane.add(lblPort,0,0);
        gridPane.add(txtPort,1,0);
        gridPane.add(startServer,0,1,2,1);
        gridPane.setHgap(10);
        gridPane.setVgap(10);
      // startServer(8888);

        Scene scene = new Scene(gridPane, 200,100);
        window.setScene(scene);
        window.show();
    }

    private void startServer(int port){
        System.out.println("Timelineloop");

            Timeline time = new Timeline( new KeyFrame(      Duration.millis(2500),k->{
                System.out.println("Timelineloop");

            }));
            time.setCycleCount(Timeline.INDEFINITE);
            time.play();
        window.close();
    }
}

Upvotes: 1

Views: 185

Answers (1)

jewelsea
jewelsea

Reputation: 159341

Immediately after you call play() on your timeline you are calling close() on your stage. Closing the last stage in a JavaFX application will shut down the JavaFX system and, if there are no other non-daemon threads in the system (as in this case), will shut down the JVM, exiting your program.

You can modify this behavior either by not closing the last stage in your JavaFX application or by calling Platform.setImplicitExit(false) before you close the last stage and later calling Platform.exit() when JavaFX is no longer needed.

The application life-cycle behavior is further described in the Application javadoc.

One note on your example: to get the Timeline to run, comment out window.close() and ensure you enter an integer value in the text field before pressing the start button (or your Integer.parseInt call will throw an exception).

Upvotes: 2

Related Questions