在JavaFX中更改场景而不调整窗口大小 [英] Change Scene without resize window in JavaFX
问题描述
我正在尝试更改JavaFX上的场景,但不更改窗口大小。但是,当我设置 stage.setScene(scene2);
窗口大小减小时,我想保持两个场景最大化。我在 stage.setScene(scene2);
之后尝试 stage.setMaximized(true)
,但结果是相同。
I'm trying to change Scenes on JavaFX, but without change the window size. However, when I set stage.setScene(scene2);
the window size decreases, and I want to keep the both Scenes maximized. I've tried to stage.setMaximized(true)
after the stage.setScene(scene2);
but the result is the same.
如何解决?
我的代码:
package controller;
import java.io.IOException;
import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.util.Duration;
public class App extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("../view/fxml/Loading.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Project");
stage.setMaximized(true);
stage.show();
FadeTransition fadeIn = new FadeTransition(Duration.seconds(1), root);
fadeIn.setFromValue(0);
fadeIn.setToValue(1);
FadeTransition fadeOut = new FadeTransition(Duration.seconds(1), root);
fadeOut.setFromValue(1);
fadeOut.setToValue(0);
fadeIn.play();
fadeIn.setOnFinished((e) -> {
fadeOut.play();
});
fadeOut.setOnFinished((e) -> {
try {
Parent root2 = FXMLLoader.load(getClass().getResource("../view/fxml/Welcome.fxml"));
Scene scene2 = new Scene(root2);
stage.setScene(scene2);
} catch (IOException e1) {
e1.printStackTrace();
}
});
}
public static void main(String[] args) {
launch(args);
}
}
编译时:
When I compile:
然后fadeOut / fadeIn出现并且(这里我想保持最大化):
Then the fadeOut/fadeIn occurs and (It is here that I want to keep maximized):
推荐答案
这里更好的方法是更换现有场景的根,而不是创建一个新场景:
It's probably better here just to replace the root of the existing scene, than to create a new scene:
fadeOut.setOnFinished((e) -> {
try {
Parent root2 = FXMLLoader.load(getClass().getResource("../view/fxml/Welcome.fxml"));
scene.setRoot(root2);
} catch (IOException e1) {
e1.printStackTrace();
}
});
如果你真的需要更换场景,出于某种原因,你可以设置新场景的大小与现有场景相同:
If you really do need to replace the scene, for some reason, you can set the new scene's size to the same as the existing scene:
fadeOut.setOnFinished((e) -> {
try {
Parent root2 = FXMLLoader.load(getClass().getResource("../view/fxml/Welcome.fxml"));
Scene scene2 = new Scene(root2, scene.getWidth(), scene.getHeight());
stage.setScene(scene2);
} catch (IOException e1) {
e1.printStackTrace();
}
});
这篇关于在JavaFX中更改场景而不调整窗口大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!