1

Как это сделать? Хотелось бы при получении определенного события разворачивать свернутое окно. Есть класс Main, в котором:

public void start(Stage primaryStage) {
    setPrimaryStage(primaryStage);
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(Main.class.getResource("design.fxml"));
    try {
        rootLayout = (Pane) loader.load();
            Scene scene = new Scene(rootLayout);
            primaryStage.setScene(scene);
            primaryStage.show();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

private void setPrimaryStage(Stage pStage) {
    Main.pStage = pStage;
}

public static Stage getPrimaryStage() {
    return pStage;
}

В контроллере есть метод, который, как хотелось бы, разварачивал окно, которое свернуто или находится за другими окнами:

Task task = new Task<Void>() {
    @Override 
    public Void call() throws InterruptedException {
    try {
            Main.getPrimaryStage().toFront();
        }
        catch (Exception e) {
            System.out.println("ERROR: "+e.getMessage());
        }
        while(!flag)
        { .....}
});

Но при вызове этого метода по событию возникает ошибка:

This operation is permitted on the event thread only; currentThread = Thread-14

2
  • 1
    Platform.runLater( () -> {Main.getPrimaryStage().toFront();} );
    – Andrey M
    23 ноя 2017 в 14:29
  • Andrey M - спасибо огромное, помогло! 23 ноя 2017 в 14:39

1 ответ 1

1

Альтернативный вариант, дать контролеру primaryStage, чтобы не привязывать его к классу, инициализировавшему его.

В контроллере завести переменную Stage primaryStage и сеттер к нему.

В классе, который инициализирует сцену можно получить контроллер из fxml файла так:

Controller controller = rootLayout.getController();

и потом передать ему сцену через сеттер:

controller.setPrimaryStage(primaryStage);

public void start(Stage primaryStage) {
    setPrimaryStage(primaryStage);
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(Main.class.getResource("design.fxml"));
    try {
        rootLayout = (Pane) loader.load();
        Controller controller = rootLayout.getController();
        controller.setPrimaryStage(primaryStage);
        Scene scene = new Scene(rootLayout);
        primaryStage.setScene(scene);
        primaryStage.show();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

private void setPrimaryStage(Stage pStage) {
    Main.pStage = pStage;
}

public static Stage getPrimaryStage() {
    return pStage;
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.