我在 javaFx 项目的 Main 方法中向
primaryStage
添加了一个场景。同样在同一个主类中,舞台已准备好:然后,通过单击与该场景相关的 fxml 代码中的按钮,舞台上的现有场景将被更改。primaryStage.setMaximized(true);
请帮我解决问题。这是面临问题的代码。
这是我的项目的起始主类
The problem is that the stage is automatic minimized when the scene changes. I hope to keep the default size of the stage maximized.
这是贯穿主类的MainScene.fxml代码
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws IOException {
Parent parent = FXMLLoader.load(getClass().getResource("MainScene.fxml"));
Scene scene = new Scene(parent);
primaryStage.setScene(scene);
primaryStage.setMaximized(true);
primaryStage.show();
}
}
这是该 MainScene.fxml 文件的控制器类。
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Text?>
<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/21" xmlns:fx="http://javafx.com/fxml/1" fx:controller="MainSceneConn">
<children>
<Text layoutX="289.0" layoutY="196.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Form" />
<Button fx:id="button" layoutX="236.0" layoutY="213.0" mnemonicParsing="false" onAction="#loadNewScene" prefHeight="25.0" prefWidth="134.0" text="New Scene" />
</children>
</AnchorPane>
这是包含通过该控制器类的场景的 fxml 文件
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class MainSceneConn {
public Button button;
public void loadNewScene(ActionEvent actionEvent) throws IOException {
Stage stage = (Stage) button.getScene().getWindow();
stage.setMaximized(true);//this line is not work :(
Parent parent = FXMLLoader.load(getClass().getResource("secondScene.fxml"));
Scene scene = new Scene(parent);
stage.setScene(scene);
}
}
在我的主要方法之外,再次在
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane xmlns="http://javafx.com/javafx"
xmlns:fx="http://javafx.com/fxml"
prefHeight="400.0" prefWidth="600.0">
</AnchorPane>
控制器类
MainScene.fxml
中准备为 但它没有什么不同。您可以更改现有场景的根,而不是创建新场景,然后窗口的最大化状态将保持不变。
stage.setMaximized(true);