界面切换就是scene的改变,程序运行启动类会初始化一个stage,它会在程序的整个生命周期存在,scene是场景信息,界面的元素通过场景来呈现。然后把scene交给stage显示出来。
1. 封装界面地址枚举类
@AllArgsConstructor
@Getter
public enum PageIndexEnum {
LOGIN_PAGE("登录页", "login.fxml", 500, 300),
MAIN_PAGE("主界面", "main.fxml", 1000, 700);
private String pageName;
private String pageFile;
private Integer width;
private Integer height;
}
2. 界面切换工具类
public class StageUtil {
private static Stage primaryStage;
public static void set(Stage state) {
primaryStage = state;
}
public static Stage get() {
return primaryStage;
}
public static void forward(PageIndexEnum pageIndexEnum) {
try {
Parent mainPage = FXMLLoader.load(Objects.requireNonNull(ClassLoader.getSystemClassLoader().getResource(pageIndexEnum.getPageFile())));
Stage primaryStage = StageUtil.get();
primaryStage.getIcons().add(new Image("https://img1.baidu.com/it/u=1855883715,2143013249&fm=253&fmt=auto&app=138&f=PNG?w=278&h=277"));
primaryStage.setScene(new Scene(mainPage, pageIndexEnum.getWidth(), pageIndexEnum.getHeight()));
} catch (Exception e) {}
}
}
3. 启动类
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
PageIndexEnum page = PageIndexEnum.MAIN_PAGE;
Parent root = FXMLLoader.load(Objects.requireNonNull(getClass().getClassLoader().getResource(page.getPageFile())));
primaryStage.setTitle("狗语IM聊天系统");
primaryStage.getIcons().add(new Image("https://img1.baidu.com/it/u=1855883715,2143013249&fm=253&fmt=auto&app=138&f=PNG?w=278&h=277"));
primaryStage.setScene(new Scene(root, page.getWidth(), page.getHeight()));
primaryStage.show();
StageUtil.set(primaryStage);
}
public static void main(String[] args) {
launch(args);
}
}