A simple JavaFX router to switch between application scenes
Get latest release here
- 0.0.x - Support for Java 9
- master (1.0.x) - Support for Java 8
You can switch between your scenes from anywhere through a simple method, without worrying about annoying Stage settings.
Add FXRouter as project dependency and import it from its package:
import com.github.fxrouter.FXRouter;
Connect FXRouter to your application stage: call bind()
from your main class start()
method (if you use IntelliJ IDEA) or similar:
FXRouter.bind(this, primaryStage);
FXRouter.bind(this, primaryStage, "MyApplication", 800, 600);
Define your Application routes with a label identifier and its corresponding .fxml screen file:
FXRouter.when("login", "myloginscreen.fxml");
FXRouter.when("profile", "myprofilescreen.fxml");
// ... others
FXRouter.when("login", "myloginscreen.fxml", "My login screen", 1000, 500);
Switch routes from anywhere (controllers, services, etc):
FXRouter.goTo("login"); // switch to myloginscreen.fxml
Your application could need to pass some data to another route and then retrieve those data:
goTo()
accepts two parameters: a route identifier and a Object
:
FXRouter.goTo("profile", "johndoe22"); // switch to myprofilescreen.fxml passing an username
getData()
returns a Object
which can be cast to appropriate data type:
String username = (String) FXRouter.getData(); // retrieve johndoe22
A common JavaFX project starter:
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);
}
}
package sample;
import javafx.application.Application;
import javafx.stage.Stage;
import sample.FXRouter; // import FXRouter
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
FXRouter.bind(this, primaryStage, "Hello World", 300, 275); // bind FXRouter
FXRouter.when("firstPage", "sample.fxml"); // set "firstPage" route
FXRouter.goTo("firstPage"); // switch to "sample.fxml"
}
public static void main(String[] args) {
launch(args);
}
}
You can also set an animation type when you switch between routes:
FXRouter.setAnimationType("fade");
FXRouter.setAnimationType("fade", 1200);
AnimationType | Default duration |
---|---|
fade |
800 |