Alert

Alert 类是 Dialog 类的子类,它提供了多种的对话框,这些对话框可以很容易地显示给用户以提示响应。有时候 Alert 类要比 Dialog 简单快捷一点。

消息对话框

Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("对话框标题");
alert.setHeaderText("对话框头部");
alert.setContentText("对话框内容!!!");
alert.showAndWait();

图片.png

如果不需要头部的话直接设置:alert.setHeaderText(null);

AlertType 类型

警告对话框

Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("对话框标题");
alert.setHeaderText("对话框头部");
alert.setContentText("对话框内容!!!");
alert.showAndWait();

图片.png

错误对话框

Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("对话框标题");
alert.setHeaderText("对话框头部");
alert.setContentText("对话框内容!!!");
alert.showAndWait();

图片.png

异常对话框

			Alert alert = new Alert(AlertType.ERROR);
			alert.setTitle("对话框标题");
			alert.setHeaderText("对话框头部");
			alert.setContentText("对话框内容!!!");
			
			Exception ex = new FileNotFoundException("Could not find file blabla.txt");
			 
			// Create expandable Exception.
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			ex.printStackTrace(pw);
			String exceptionText = sw.toString();
			 
			Label label = new Label("The exception stacktrace was:");
			 
			TextArea textArea = new TextArea(exceptionText);
			textArea.setEditable(false);
			textArea.setWrapText(true);
			 
			textArea.setMaxWidth(Double.MAX_VALUE);
			textArea.setMaxHeight(Double.MAX_VALUE);
			GridPane.setVgrow(textArea, Priority.ALWAYS);
			GridPane.setHgrow(textArea, Priority.ALWAYS);
			 
			GridPane expContent = new GridPane();
			expContent.setMaxWidth(Double.MAX_VALUE);
			expContent.add(label, 0, 0);
			expContent.add(textArea, 0, 1);
			 
			alert.getDialogPane().setExpandableContent(expContent);
			alert.showAndWait();

图片.png

确认对话框

			Alert alert = new Alert(AlertType.CONFIRMATION);
			alert.setTitle("对话框标题");
			alert.setHeaderText("对话框头部");
			alert.setContentText("对话框内容!!!");
			
			Optional<ButtonType> result = alert.showAndWait();
			if (result.get() == ButtonType.OK){
			    System.out.println("OK...");
			} else {
				System.out.println("Cancel...");
			}

图片.png

自定义对话框按钮

			Alert alert = new Alert(AlertType.CONFIRMATION);
			alert.setTitle("对话框标题");
			alert.setHeaderText("对话框头部");
			alert.setContentText("对话框内容!!!");
			
			ButtonType buttonTypeOk = new ButtonType("确认", ButtonData.OK_DONE);
			ButtonType buttonTypeTwo = new ButtonType("按钮1");
			ButtonType buttonTypeThree = new ButtonType("按钮2");
			ButtonType buttonTypeCancel = new ButtonType("返回", ButtonData.CANCEL_CLOSE);
			 
			alert.getButtonTypes().setAll(buttonTypeOk, buttonTypeTwo, buttonTypeThree, buttonTypeCancel);
			
			Optional<ButtonType> result = alert.showAndWait();
			if (result.get() == ButtonType.OK){
			    System.out.println("OK...");
			} else if(result.get() == ButtonType.CANCEL){
				System.out.println("Cancel...");
			} else {
				System.out.println("Other...");
			}

图片.png