import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ApplicationModalSampleApp2
{

    public static void main( String[] args )
    {
        System.err.println( Runtime.version().toString() );
        Application.launch( MainFx.class, args );
    }

    public static class MainFx extends Application
    {

        @Override
        public void start( final Stage primaryStage ) throws Exception
        {
            final Button button = new Button( "Start modal" );
            button.setOnAction( e -> showModal( primaryStage ) );
            final BorderPane root = new BorderPane( button );
            final Scene aScene = new Scene( root, 800, 600 );
            primaryStage.setScene( aScene );
            primaryStage.show();
        }

        private void showModal( final Stage mainStage )
        {
            final Stage sampleModalStage = new Stage();
            sampleModalStage.initOwner( mainStage );
            final Button closeMainStageButton = new Button( "Close main stage and show new dialog" );
            closeMainStageButton.setOnAction( e -> closeMainStageAndOpenModalWithWait( mainStage ) );
            final Button closeModalButton = new Button( "Close modal stage and show new dialog" );
            closeModalButton.setOnAction( e -> closeMainStageAndOpenModalWithWait( sampleModalStage ) );
            sampleModalStage
                .setScene( new Scene( new VBox( 5d, closeMainStageButton, closeModalButton ), 400, 400 ) );
            sampleModalStage.showAndWait();
        }

        private void closeMainStageAndOpenModalWithWait( final Stage aStage )
        {
            // this call exits secondary loop of first modal
            aStage.hide();

            final Stage sampleModalStage2 = new Stage();
            sampleModalStage2.setScene(
                new Scene( new VBox( 5d, new TextField( "sampleText" ), new TextField( "sampleText2" ) ), 400,
                    400 ) );
            sampleModalStage2.setResizable( true );
            // this call creates secondary loop of based on already exit secondary loop
            sampleModalStage2.showAndWait();
        }

    }
} 