【问题标题】:Store dynamic screen with multiple stages多阶段存储动态画面
【发布时间】:2016-04-12 23:15:21
【问题描述】:
我有 2 个不同的屏幕,在第一个屏幕中用户可以加载图像,另一个只是一个按钮(舞台是不可见的,因此舞台必须与屏幕 1 不同)用于返回第一阶段。问题是当我从屏幕 2 回到屏幕 1 时,我不知道如何保持图像加载(当我进入阶段 2 时我隐藏了阶段 1)。这是我目前在两个屏幕中使用的方法。
@FXML
private void goToScreen1(ActionEvent event) throws Exception{
Stage stage = (Stage) showStage.getScene().getWindow();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/sample.fxml"));
Parent root = fxmlLoader.load();
Stage primaryStage = new Stage();
primaryStage.setResizable(true);
primaryStage.setOpacity(0.0);
primaryStage.show();
primaryStage.setX(0);
primaryStage.setY(0);
primaryStage.setHeight(primScreenBounds.getHeight());
primaryStage.setWidth(primScreenBounds.getWidth() / 2);
}
【问题讨论】:
标签:
image
javafx
screen
stage
【解决方案1】:
您必须存储对舞台内容的引用,因此您不必重新实例化它。
一种可能是将其存储在 mainController 中并向您的 subController 提供 EventHandler,以切换阶段
public interface ScreenController {
void setOnSwitchStage(EventHandler<ActionEvent> handler);
}
public class Screen1Controller implements Initializable, ScreenController {
@FXML
private Button btnSwitchScreen
public Screen1Controller() {
}
@Override
public void initialize(URL location, ResourceBundle resources) {
}
@Override
public void setOnSwitchStage(EventHandler<ActionEvent> handler) {
btnSwitchScreen.setOnAction(handler);
}
}
public class YourApp extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Stage secondaryStage = new Stage();
initScreen(primaryStage, secondaryStage, "screen1.fxml");
initScreen(secondaryStage, primaryStage, "screen2.fxml");
primaryStage.show();
}
private void initScreen(Stage parentStage, Stage nextStage, String resource) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource(resource));
Scene scene = new Scene(loader.load());
parentStage.setScene(scene);
ScreenController screenController = loader.getController();
screenController.setOnSwitchStage(evt -> {
nextStage.show();
parentStage.hide();
});
}
public static void main(String[] args) {
launch(args);
}
}
【解决方案2】:
如果primaryStage 是“用户可以加载图像”的地方:
static Stage primaryStage;
@FXML
private void goToScreen1(ActionEvent event) throws Exception{
Stage stage = (Stage) showStage.getScene().getWindow();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/sample.fxml"));
Parent root = fxmlLoader.load();
if(primaryStage==null)
primaryStage = new Stage();
primaryStage.setResizable(true);
primaryStage.setOpacity(0.0);
primaryStage.show();
primaryStage.setX(0);
primaryStage.setY(0);
primaryStage.setHeight(primScreenBounds.getHeight());
primaryStage.setWidth(primScreenBounds.getWidth() / 2);
}