[英]JavaFX+MVC. Change center in BorderPane and NullPointerException
[英]JavaFX+MVC. How to hide/show multiple windows?
如何在我點擊“打開第二個窗口”時隱藏主窗口。 當我關閉第二個窗口時,會顯示主窗口? 我讀過這篇文章 ,但我不知道如何為我的任務實現它。 謝謝!
我有下一個代碼:
Main.java
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("First Stage");
try {
primaryStage.setResizable(false);
Parent root = FXMLLoader.load(getClass().getResource("MainView.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
MainWiew.fxml
<?import javafx.geometry.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane id="rootMain" prefHeight="418.0" prefWidth="691.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.view.MainController">
<top>
</top>
<center>
<AnchorPane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<children>
<VBox fillWidth="false" prefHeight="400.0" prefWidth="394.0" spacing="8.0">
<children>
<Button id="btnMainOne" fx:id="btnMainOne" mnemonicParsing="false" prefHeight="51.0" prefWidth="398.0" text="Open second window" textFill="#4460ff">
<font>
<Font name="Times New Roman Bold" size="20.0" />
</font>
</Button>
</children>
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</padding>
</VBox>
</children>
</AnchorPane>
</center>
</BorderPane>
MainController.java
import java.io.IOException;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class MainController {
@FXML
private Button btnMainOne;
@FXML
private void initialize() {
btnMainOne.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
try {
Stage stage = new Stage();
stage.setTitle("Second stage");
stage.setScene(new Scene(root, 450, 450));
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
您可以通過調用getScene().getWindow()
來獲取主窗口。 您可以在顯示新階段后調用hide()
來隱藏它,並且您可以在隱藏新階段時顯示主窗口的新階段注冊事件監聽器:
@FXML
private void initialize() {
btnMainOne.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
Stage primaryStage = (Stage)btnMainOne.getScene().getWindow();
try {
Stage stage = new Stage();
stage.setTitle("Second stage");
stage.setScene(new Scene(root, 450, 450));
stage.setOnHidden(e -> primaryStage.show());
stage.show();
primaryStage.hide();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.