how to achieve double widows by javafx
To achieve double windows in JavaFX, you can follow these steps:
-
Create a new JavaFX project in your preferred IDE.
-
In the main class, extend the
javafx.application.Applicationclass and override thestart()method.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class DoubleWindows extends Application {
@Override
public void start(Stage primaryStage) {
// Create the first window
StackPane root1 = new StackPane();
Button button1 = new Button("Open Second Window");
root1.getChildren().add(button1);
Scene scene1 = new Scene(root1, 300, 200);
primaryStage.setTitle("First Window");
primaryStage.setScene(scene1);
primaryStage.show();
// Create the second window
Stage secondaryStage = new Stage();
StackPane root2 = new StackPane();
Button button2 = new Button("Close Second Window");
root2.getChildren().add(button2);
Scene scene2 = new Scene(root2, 300, 200);
secondaryStage.setTitle("Second Window");
secondaryStage.setScene(scene2);
secondaryStage.show();
// Handle button actions
button1.setOnAction(e -> secondaryStage.show());
button2.setOnAction(e -> secondaryStage.close());
}
public static void main(String[] args) {
launch(args);
}
}
-
In the
start()method, create two instances of theStageclass. These will represent your windows. -
Create the necessary UI components for each window and add them to their respective root layout (e.g.,
StackPane). -
Create
Sceneobjects for both windows, specifying the root layout and the desired width and height. -
Set the title of each window using
stage.setTitle("Window Title"). -
Set the scene of each window using
stage.setScene(scene). -
Show both windows using
stage.show(). -
Handle button actions to control the visibility of the second window. In the example above, clicking the "Open Second Window" button on the first window will show the second window, and clicking the "Close Second Window" button on the second window will close it.
-
Run the application and you should see two windows displayed
原文地址: https://www.cveoy.top/t/topic/h8tc 著作权归作者所有。请勿转载和采集!