fturizo fturizo - 3 months ago 17
Java Question

How do I create a Resize animation for JavaFX stage?

I've been trying to make a scaling transition for a JavaFX stage to replaces the current Scene (in this case a login frame) for an application's main window.

When this happens, since the new scene is bigger, the windows gets re-sized abruptly in a non-elegant manner.

Is there any way to set up a scaling or re-size transition to do this to the stage resizing?

Relevant code:

InputStream is = null;
try {
is = getClass().getResourceAsStream("/fxml/principal.fxml");
Region pagina = (Region) cargadorFXML.load(is);
cargadorFXML.<ContenedorPrincipal>getController().setEscenario(escenario);

final Scene escena = new Scene(pagina, 900, 650);

escena.setFill(Color.TRANSPARENT);
escenario.setScene(escena);
escenario.sizeToScene();
escenario.centerOnScreen();
escenario.show();
} catch (IOException ex) {
// log "Unable to load the main application driver"
log.error("No fue posible cargar el controlador principal de la aplicaciĆ³n.");
log.catching(ex);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {}
}
}

Answer

I really liked your idea so I managed to do a little something. I hope this will help you.

I used a Timer to change the stage width and height every 25ms in order to give the impression of an animation.

import java.util.Timer;
import java.util.TimerTask;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class SmoothResize extends Application {

    @Override
    public void start(final Stage stage) throws Exception {
        stage.setTitle("Area Chart Sample");
        Group root = new Group();
        Scene scene  = new Scene(root, 250, 250);
        stage.setResizable(false);

        Timer animTimer = new Timer();
        animTimer.scheduleAtFixedRate(new TimerTask() {
            int i=0;

            @Override
            public void run() {
                if (i<100) {
                    stage.setWidth(stage.getWidth()+3);
                    stage.setHeight(stage.getHeight()+3);
                } else {
                    this.cancel();
                }
                i++;
            }

        }, 2000, 25);

        stage.setScene(scene);
        stage.show();
    }

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