JavaFX对话框控件-Dialog
- 常用属性
- title
- initOwner
- dialogPane
- resultConverter
- 实现方式
- 与Alert大部分功能类似
- 可以自定义弹出框内容,比较灵活
- 与
DialogPane
布局配合使用,自定义具体内容
参考DialogPane
常用属性
title
弹出框标题,标题太长会把超长部分截取,后面加上
……
dialog.setTitle("标题");
initOwner
设置弹框的所有者,用于确定对话框的位置和模式
dialog.initOwner(stage);
dialogPane
获取 Alert 的内部 DialogPane,允许进一步定制对话框的布局和内容,其中最重要的是
expandableContent
dialog.setDialogPane(dialogPane);
resultConverter
点击按钮返回结果组装
dialog.setResultConverter(btnType -> {
if (ButtonType.OK.equals(btnType)) {
return null;
}
return null;
});
实现方式
public static Parent demo1(Window owner) {
FlowPane flowPane = new FlowPane();
flowPane.setHgap(10);
flowPane.setVgap(10);
flowPane.setOrientation(Orientation.VERTICAL);
Button button1 = new Button("demo1");
button1.setOnMouseClicked((event) -> {
if (MouseButton.PRIMARY.equals(event.getButton())) {
createDialog(owner);
}
});
flowPane.getChildren().add(button1);
return flowPane;
}
public static void createDialog(Window owner) {
DialogPane dialogPane = new DialogPane();
dialogPane.setHeaderText("请输入用户密码:");
dialogPane.setGraphic(new ImageView("icon.png"));
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
Label labelUname = new Label("用户名:");
grid.add(labelUname, 0, 0);
TextField txtUname = new TextField();
txtUname.setPromptText("请输入用户名");
grid.add(txtUname, 1, 0);
Label labelPwd = new Label("密 码:");
grid.add(labelPwd, 0, 1);
PasswordField txtPwd = new PasswordField();
txtPwd.setPromptText("请输入密码");
grid.add(txtPwd, 1, 1);
dialogPane.setContent(grid);
// 设置按钮
dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
TextArea textArea = new TextArea("展开显示详细内容");
textArea.setEditable(true);
textArea.setWrapText(true);
textArea.setMaxWidth(Double.MAX_VALUE);
textArea.setMaxHeight(Double.MAX_VALUE);
dialogPane.setExpandableContent(textArea);
dialogPane.setExpanded(false);
Dialog<UserLoginDTO> dialog = new Dialog<UserLoginDTO>();
dialog.setTitle("标题信息");
dialog.setWidth(400);
dialog.setHeight(300);
dialog.initOwner(owner);
dialog.setDialogPane(dialogPane);
dialog.setResultConverter(btnType -> {
if (ButtonType.OK.equals(btnType)) {
String username = txtUname.getText();
String password = txtPwd.getText();
if (username.isEmpty() || password.isEmpty()) {
return null;
} else {
UserLoginDTO userLoginDTO = new UserLoginDTO();
userLoginDTO.setUserName(username);
userLoginDTO.setPassword(password);
return userLoginDTO;
}
}
return null;
});
Optional<UserLoginDTO> optional = dialog.showAndWait();
optional.ifPresent((val) -> {
System.out.println("uname->" + val.getUserName());
System.out.println("pwd->" + val.getPassword());
});
}
public static class UserLoginDTO {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}