事实证明,不写注释我容易忘记写的是啥,所以注释写的比较多。
package javafx;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.util.Optional;
//JavaFX中stage的学习
public class Main2 extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Button button0 = new Button("窗口0");
Button button1 = new Button("窗口1");
//设置按钮的布局,XY相当于坐标轴一样
button0.setLayoutX(150);
button0.setLayoutY(150);
button1.setLayoutX(200);
button1.setLayoutY(200);
//AnchorPane为锚布局,可以设置子节点的位置
AnchorPane pane = new AnchorPane();
pane.getChildren().addAll(button0,button1);
button0.setOnAction(event -> {
Stage stage = new Stage();
stage.setHeight(400);
stage.setWidth(400);
stage.initOwner(primaryStage); //设置父窗口
//APPLICATION_MODAL全局模态,该窗口运行时,其他窗口不能进行操作
//WINDOW_MODAL为父窗口禁用,其他窗口可以使用
stage.initModality(Modality.WINDOW_MODAL);
stage.show();
});
button1.setOnAction(event -> {
Stage stage = new Stage();
stage.setHeight(400);
stage.setWidth(400);
stage.show();
});
Platform.setImplicitExit(false); //在这个方法中输入false系统会取消默认退出窗口事件
primaryStage.setOnCloseRequest(event -> { //建立关闭需求
event.consume(); //取消关闭窗口的动作
Alert alert = new Alert(Alert.AlertType.CONFIRMATION); //Alert警报,弹出一个窗口,问是否要退出程序
alert.setTitle("退出程序");
alert.setHeaderText(null);
alert.setContentText("真的要退出程序吗?");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
//Platform.exit(); //关闭程序
primaryStage.close();//关闭窗口,不退出程序,程序仍在运行
}
});
Scene scene = new Scene(pane,520,520);
//Title为设置窗口名称
primaryStage.setScene(scene);
primaryStage.setTitle("我能学好JavaFX");
//Icons为窗口图标,寝室停电了,一晚上没搞好,第二天就弄好了,还挺开心
primaryStage.getIcons().add(new Image("File:C:\\Users\\lyj\\Desktop\\学习作业\\壁纸\\A11.jpeg"));
//Resizable控制窗口大小,输入false则不能改变窗口大小,最大化按钮将不能点击
primaryStage.setResizable(false);
//StageStyle为设置窗口风格,共有四种:StageStyle.DECORATED(默认窗口风格)
//StageStyle.UNDECORATED(没有标题栏、图标,最大化和最小化)
//StageStyle.TRANSPARENT(这个是透明背景的窗口,也没有装饰)
//StageStyle.UTILITY(简单装饰)
//primaryStage.initStyle();
primaryStage.show();
}
}
运行结果:
点击窗口0/1:0设置为不能执行父窗口,1是可以的。
点击×:
当然,我还设置了窗口图标:
部分方法因为改动较多,所以不展示运行结果。