第3部分的主题:

  1. 在表中反应选择的改变(TableView中)。
  2. 增加增加编辑删除按钮的功能。
  3. 创建自定义弹出对话框编辑人员。
  4. 验证用户输入

响应表的选择

显然,我们还没有使用应用程序的右边。想法是当用户选择表中的人员时,在右边显示人员的详情。

首先,让我们在PersonOverviewController添加一个新的方法,帮助我们使用单个人员的数据填写标签。

创建方法showPersonDetails(Person person)。遍历所有标签,并且使用setText(…)方法设置标签的文本为个人的详情。如果null作为参数传递,所有的标签应该被清空。

PersonOverviewController.java

  1. /**
  2. * Fills all text fields to show details about the person.
  3. * If the specified person is null, all text fields are cleared.
  4. *
  5. * @param person the person or null
  6. */
  7. private void showPersonDetails(Person person) {
  8. if (person != null) {
  9. // Fill the labels with info from the person object.
  10. firstNameLabel.setText(person.getFirstName());
  11. lastNameLabel.setText(person.getLastName());
  12. streetLabel.setText(person.getStreet());
  13. postalCodeLabel.setText(Integer.toString(person.getPostalCode()));
  14. cityLabel.setText(person.getCity());
  15.  
  16. // TODO: We need a way to convert the birthday into a String!
  17. // birthdayLabel.setText(...);
  18. } else {
  19. // Person is null, remove all the text.
  20. firstNameLabel.setText("");
  21. lastNameLabel.setText("");
  22. streetLabel.setText("");
  23. postalCodeLabel.setText("");
  24. cityLabel.setText("");
  25. birthdayLabel.setText("");
  26. }
  27. }

转换生日日期为字符串

你注意到我们没有设置birthday到标签中,因为它是LocalDate类型,不是String。我们首先需要格式化日期。

在几个地方上我们使用LocalDateString之间的转换。好的实践是创建一个带有static方法的帮助类。我们称它为DateUtil,并且把它放到单独的包中,称为ch.makery.address.util

DateUtil.java

  1. package ch.makery.address.util;
  2.  
  3. import java.time.LocalDate;
  4. import java.time.format.DateTimeFormatter;
  5. import java.time.format.DateTimeParseException;
  6.  
  7. /**
  8. * Helper functions for handling dates.
  9. *
  10. * @author Marco Jakob
  11. */
  12. public class DateUtil {
  13.  
  14. /** The date pattern that is used for conversion. Change as you wish. */
  15. private static final String DATE_PATTERN = "dd.MM.yyyy";
  16.  
  17. /** The date formatter. */
  18. private static final DateTimeFormatter DATE_FORMATTER =
  19. DateTimeFormatter.ofPattern(DATE_PATTERN);
  20.  
  21. /**
  22. * Returns the given date as a well formatted String. The above defined
  23. * {@link DateUtil#DATE_PATTERN} is used.
  24. *
  25. * @param date the date to be returned as a string
  26. * @return formatted string
  27. */
  28. public static String format(LocalDate date) {
  29. if (date == null) {
  30. return null;
  31. }
  32. return DATE_FORMATTER.format(date);
  33. }
  34.  
  35. /**
  36. * Converts a String in the format of the defined {@link DateUtil#DATE_PATTERN}
  37. * to a {@link LocalDate} object.
  38. *
  39. * Returns null if the String could not be converted.
  40. *
  41. * @param dateString the date as String
  42. * @return the date object or null if it could not be converted
  43. */
  44. public static LocalDate parse(String dateString) {
  45. try {
  46. return DATE_FORMATTER.parse(dateString, LocalDate::from);
  47. } catch (DateTimeParseException e) {
  48. return null;
  49. }
  50. }
  51.  
  52. /**
  53. * Checks the String whether it is a valid date.
  54. *
  55. * @param dateString
  56. * @return true if the String is a valid date
  57. */
  58. public static boolean validDate(String dateString) {
  59. // Try to parse the String.
  60. return DateUtil.parse(dateString) != null;
  61. }
  62. }

提示:你能通过改变DATE_PATTERN修改日期的格式。所有可能的格式参考 DateTimeFormatter.

使用DateUtil

现在,我们需要在PersonOverviewControllershowPersonDetails方法中使用我们新建的DateUtil。使用下面这样替代我们添加的TODO

  1. birthdayLabel.setText(DateUtil.format(person.getBirthday()));

监听表选择的改变

为了当用户在人员表中选择一个人时获得通知,我们需要监听改变

在JavaFX中有一个接口称为ChangeListener,带有一个方法changed()。该方法有三个参数:observableoldValuenewValue

我们使用*Java 8 lambda*表达式创建这样一个ChangeListener。让我们添加一些行到PersonOverviewControllerinitialize()方法中。现在看起来是这样的。

PersonOverviewController.java

  1. @FXML
  2. private void initialize() {
  3. // Initialize the person table with the two columns.
  4. firstNameColumn.setCellValueFactory(
  5. cellData -> cellData.getValue().firstNameProperty());
  6. lastNameColumn.setCellValueFactory(
  7. cellData -> cellData.getValue().lastNameProperty());
  8.  
  9. // Clear person details.
  10. showPersonDetails(null);
  11.  
  12. // Listen for selection changes and show the person details when changed.
  13. personTable.getSelectionModel().selectedItemProperty().addListener(
  14. (observable, oldValue, newValue) -> showPersonDetails(newValue));
  15. }

使用showPersonDetails(null),我们重设个人详情。

使用personTable.getSelectionModel...,我们获得人员表的selectedItemProperty,并且添加监听。不管什么时候用户选择表中的人员,都会执行我们的lambda表达式。我们获取新选择的人员,并且把它传递给showPersonDetails(...)方法。

现在试着运行你的应用程序,验证当你选择表中的人员时,关于该人员的详情是否正确的显示。

如果有些事情不能工作,你可以对比下PersonOverviewController.java中的PersonOverviewController


删除按钮

我们的用户接口已经包含一个删除按钮,但是没有任何功能。我们能在*SceneBuilder*中的按钮上选择动作。在我们控制器中的任何使用@FXML(或者它是公用的)注释的方法都可以被*Scene Builder*访问。因此,让我们在PersonOverviewController类的最后添加一个删除方法。

PersonOverviewController.java

  1. /**
  2. * Called when the user clicks on the delete button.
  3. */
  4. @FXML
  5. private void handleDeletePerson() {
  6. int selectedIndex = personTable.getSelectionModel().getSelectedIndex();
  7. personTable.getItems().remove(selectedIndex);
  8. }

现在,使用*SceneBuilder*打开PersonOverview.fxml文件,选择*Delete*按钮,打开*Code*组,在On Actin的下拉菜单中选择handleDeletePerson

错误处理

如果你现在运行应用程序,你应该能够从表中删除选择的人员。但是,当你没有在表中选择人员时点击删除按钮时会发生什么呢

这里有一个ArrayIndexOutOfBoundsException,因为它不能删除掉索引为-1人员项目。索引-1由getSelectedIndex()返回,它意味着你没有选择项目。

当然,忽略这种错误不是非常好。我们应该让用户知道在删除时必须选择一个人员。(更好的是我们应该禁用删除按钮,以便用户没有机会做错误的事情)。

我们添加一个弹出对话框通知用户,你将需要*添加一个库Dialogs

  1. 下载controlsfx-8.0.6_20.jar (你也能从ControlsFX Website中获取)。 重要:ControlsFX必须是8.0.6_20以上版本才能在JDK8U20以上版本工作。
  2. 在项目中创建一个lib子目录,添加controlsf jar文件到该目录下。
  3. 添加库到你的项目classpath中。在Eclipse中右击jar文件|选择Build Path| *Add to Build Path*。现在Eclipse知道这个库了。

handleDeletePerson()方法做一些修改后,不管什么时候用户没有选择表中的人员时按下删除按钮,我们能显示一个简单的对话框。

PersonOverviewController.java

  1. /**
  2. * Called when the user clicks on the delete button.
  3. */
  4. @FXML
  5. private void handleDeletePerson() {
  6. int selectedIndex = personTable.getSelectionModel().getSelectedIndex();
  7. if (selectedIndex >= 0) {
  8. personTable.getItems().remove(selectedIndex);
  9. } else {
  10. // Nothing selected.
  11. Dialogs.create()
  12. .title("No Selection")
  13. .masthead("No Person Selected")
  14. .message("Please select a person in the table.")
  15. .showWarning();
  16. }
  17. }

更多如何使用Dialog的示例,请阅读JavaFX 8 Dialogs.


新建和编辑对话框

新建和编辑的动作有点工作:我们需要一个自定义带表单的对话框(例如:新的Stage),询问用户关于人员的详情。

设计对话框

  1. 在*view*包中创建新的fxml文件,称为PersonEditDialog.fxml 

  2. 使用GridPanLabelTextFieldButton创建一个对话框,如下所示:

如果你不能完成工作,你能下载这个PersonEditDialog.fxml.

创建控制器

为对话框创建控制器PersonEditDialogController.java:

PersonEditDialogController.java

  1. package ch.makery.address.view;
  2.  
  3. import javafx.fxml.FXML;
  4. import javafx.scene.control.TextField;
  5. import javafx.stage.Stage;
  6.  
  7. import org.controlsfx.dialog.Dialogs;
  8.  
  9. import ch.makery.address.model.Person;
  10. import ch.makery.address.util.DateUtil;
  11.  
  12. /**
  13. * Dialog to edit details of a person.
  14. *
  15. * @author Marco Jakob
  16. */
  17. public class PersonEditDialogController {
  18.  
  19. @FXML
  20. private TextField firstNameField;
  21. @FXML
  22. private TextField lastNameField;
  23. @FXML
  24. private TextField streetField;
  25. @FXML
  26. private TextField postalCodeField;
  27. @FXML
  28. private TextField cityField;
  29. @FXML
  30. private TextField birthdayField;
  31.  
  32. private Stage dialogStage;
  33. private Person person;
  34. private boolean okClicked = false;
  35.  
  36. /**
  37. * Initializes the controller class. This method is automatically called
  38. * after the fxml file has been loaded.
  39. */
  40. @FXML
  41. private void initialize() {
  42. }
  43.  
  44. /**
  45. * Sets the stage of this dialog.
  46. *
  47. * @param dialogStage
  48. */
  49. public void setDialogStage(Stage dialogStage) {
  50. this.dialogStage = dialogStage;
  51. }
  52.  
  53. /**
  54. * Sets the person to be edited in the dialog.
  55. *
  56. * @param person
  57. */
  58. public void setPerson(Person person) {
  59. this.person = person;
  60.  
  61. firstNameField.setText(person.getFirstName());
  62. lastNameField.setText(person.getLastName());
  63. streetField.setText(person.getStreet());
  64. postalCodeField.setText(Integer.toString(person.getPostalCode()));
  65. cityField.setText(person.getCity());
  66. birthdayField.setText(DateUtil.format(person.getBirthday()));
  67. birthdayField.setPromptText("dd.mm.yyyy");
  68. }
  69.  
  70. /**
  71. * Returns true if the user clicked OK, false otherwise.
  72. *
  73. * @return
  74. */
  75. public boolean isOkClicked() {
  76. return okClicked;
  77. }
  78.  
  79. /**
  80. * Called when the user clicks ok.
  81. */
  82. @FXML
  83. private void handleOk() {
  84. if (isInputValid()) {
  85. person.setFirstName(firstNameField.getText());
  86. person.setLastName(lastNameField.getText());
  87. person.setStreet(streetField.getText());
  88. person.setPostalCode(Integer.parseInt(postalCodeField.getText()));
  89. person.setCity(cityField.getText());
  90. person.setBirthday(DateUtil.parse(birthdayField.getText()));
  91.  
  92. okClicked = true;
  93. dialogStage.close();
  94. }
  95. }
  96.  
  97. /**
  98. * Called when the user clicks cancel.
  99. */
  100. @FXML
  101. private void handleCancel() {
  102. dialogStage.close();
  103. }
  104.  
  105. /**
  106. * Validates the user input in the text fields.
  107. *
  108. * @return true if the input is valid
  109. */
  110. private boolean isInputValid() {
  111. String errorMessage = "";
  112.  
  113. if (firstNameField.getText() == null || firstNameField.getText().length() == 0) {
  114. errorMessage += "No valid first name!\n";
  115. }
  116. if (lastNameField.getText() == null || lastNameField.getText().length() == 0) {
  117. errorMessage += "No valid last name!\n";
  118. }
  119. if (streetField.getText() == null || streetField.getText().length() == 0) {
  120. errorMessage += "No valid street!\n";
  121. }
  122.  
  123. if (postalCodeField.getText() == null || postalCodeField.getText().length() == 0) {
  124. errorMessage += "No valid postal code!\n";
  125. } else {
  126. // try to parse the postal code into an int.
  127. try {
  128. Integer.parseInt(postalCodeField.getText());
  129. } catch (NumberFormatException e) {
  130. errorMessage += "No valid postal code (must be an integer)!\n";
  131. }
  132. }
  133.  
  134. if (cityField.getText() == null || cityField.getText().length() == 0) {
  135. errorMessage += "No valid city!\n";
  136. }
  137.  
  138. if (birthdayField.getText() == null || birthdayField.getText().length() == 0) {
  139. errorMessage += "No valid birthday!\n";
  140. } else {
  141. if (!DateUtil.validDate(birthdayField.getText())) {
  142. errorMessage += "No valid birthday. Use the format dd.mm.yyyy!\n";
  143. }
  144. }
  145.  
  146. if (errorMessage.length() == 0) {
  147. return true;
  148. } else {
  149. // Show the error message.
  150. Dialogs.create()
  151. .title("Invalid Fields")
  152. .masthead("Please correct invalid fields")
  153. .message(errorMessage)
  154. .showError();
  155. return false;
  156. }
  157. }
  158. }

关于该控制器的一些事情应该注意:

  1. setPerson(…)方法可以从其它类中调用,用来设置编辑的人员。
  2. 当用户点击OK按钮时,调用handleOK()方法。首先,通过调用isInputValid()方法做一些验证。只有验证成功,Person对象使用输入的数据填充。这些修改将直接应用到Person对象上,传递给setPerson(…)
  3. 布尔值okClicked被使用,以便调用者决定用户是否点击OK或者Cancel按钮。

连接视图和控制器

使用已经创建的视图(FXML)和控制器,需要连接到一起。

  1. 使用SceneBuilder打开PersonEditDialog.fxml文件
  2. 在左边的*Controller*组中选择PersonEditDialogController作为控制器类
  3. 设置所有TextFieldfx:id到相应的控制器字段上。
  4. 设置两个按钮的onAction到相应的处理方法上。

打开对话框

MainApp中添加一个方法加载和显示编辑人员的对话框。

MainApp.java

  1. /**
  2. * Opens a dialog to edit details for the specified person. If the user
  3. * clicks OK, the changes are saved into the provided person object and true
  4. * is returned.
  5. *
  6. * @param person the person object to be edited
  7. * @return true if the user clicked OK, false otherwise.
  8. */
  9. public boolean showPersonEditDialog(Person person) {
  10. try {
  11. // Load the fxml file and create a new stage for the popup dialog.
  12. FXMLLoader loader = new FXMLLoader();
  13. loader.setLocation(MainApp.class.getResource("view/PersonEditDialog.fxml"));
  14. AnchorPane page = (AnchorPane) loader.load();
  15.  
  16. // Create the dialog Stage.
  17. Stage dialogStage = new Stage();
  18. dialogStage.setTitle("Edit Person");
  19. dialogStage.initModality(Modality.WINDOW_MODAL);
  20. dialogStage.initOwner(primaryStage);
  21. Scene scene = new Scene(page);
  22. dialogStage.setScene(scene);
  23.  
  24. // Set the person into the controller.
  25. PersonEditDialogController controller = loader.getController();
  26. controller.setDialogStage(dialogStage);
  27. controller.setPerson(person);
  28.  
  29. // Show the dialog and wait until the user closes it
  30. dialogStage.showAndWait();
  31.  
  32. return controller.isOkClicked();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. return false;
  36. }
  37. }

添加下面的方法到PersonOverviewController中。当用户按下*New*或*Edit*按钮时,这些方法将从MainApp中调用showPersonEditDialog(...)

PersonOverviewController.java

  1. /**
  2. * Called when the user clicks the new button. Opens a dialog to edit
  3. * details for a new person.
  4. */
  5. @FXML
  6. private void handleNewPerson() {
  7. Person tempPerson = new Person();
  8. boolean okClicked = mainApp.showPersonEditDialog(tempPerson);
  9. if (okClicked) {
  10. mainApp.getPersonData().add(tempPerson);
  11. }
  12. }
  13.  
  14. /**
  15. * Called when the user clicks the edit button. Opens a dialog to edit
  16. * details for the selected person.
  17. */
  18. @FXML
  19. private void handleEditPerson() {
  20. Person selectedPerson = personTable.getSelectionModel().getSelectedItem();
  21. if (selectedPerson != null) {
  22. boolean okClicked = mainApp.showPersonEditDialog(selectedPerson);
  23. if (okClicked) {
  24. showPersonDetails(selectedPerson);
  25. }
  26.  
  27. } else {
  28. // Nothing selected.
  29. Dialogs.create()
  30. .title("No Selection")
  31. .masthead("No Person Selected")
  32. .message("Please select a person in the table.")
  33. .showWarning();
  34. }
  35. }

在Scene Builder中打开PersonOverview.fxml文件,为New和Edit按钮的*On Action*中选择对应的方法。


完成!

现在你应该有一个可以工作的*Address应用*。应用能够添加、编辑和删除人员。这里甚至有一些文本字段的验证避免坏的用户输入。

我希望本应用的概念和结构让开始编写自己的JavaFX应用!玩的开心。

--------------------- 本文来自 jobbible 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/moshenglv/article/details/82877639?utm_source=copy

【JavaFx教程】第三部分:与用户的交互的更多相关文章

  1. C#入门教程(三)–接收用户输入、转义字符、类型转换-打造C#入门教程

    上次教程主要讲解了visual stdio快捷键.变量相关的知识.具体教程戳这里:http://www.chengxiaoxiao.com/net/1027.html 越来越深入去写教程越来越发现,自 ...

  2. Laravel大型项目系列教程(三)之发表文章

    Laravel大型项目系列教程(三)之发表文章 一.前言 上一节教程中完成了用户管理,这节教程将大概完成发表Markdown格式文章并展示的功能. 二.Let's go 1.数据库迁移 文章模块中我们 ...

  3. [译]MVC网站教程(三):动态布局和站点管理

    目录 1.   介绍 2.   软件环境 3.   在运行示例代码之前(源代码 + 示例登陆帐号) 4.   自定义操作结果和控制器扩展 1)   OpenFileResult 2)   ImageR ...

  4. Senparc.Weixin.MP SDK 微信公众平台开发教程(三):微信公众平台开发验证

    要对接微信公众平台的"开发模式",即对接到自己的网站程序,必须在注册成功之后(见Senparc.Weixin.MP SDK 微信公众平台开发教程(一):微信公众平台注册),等待官方 ...

  5. Webpack4教程 - 第三部分,如何使用插件

    转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者.原文出处:https://wanago.io/2018/07/23/webpack-4-course-part ...

  6. Ocelot简易教程(三)之主要特性及路由详解

    作者:依乐祝 原文地址:https://www.cnblogs.com/yilezhu/p/9664977.html 上篇<Ocelot简易教程(二)之快速开始2>教大家如何快速跑起来一个 ...

  7. Java NIO系列教程(三) Channel之Socket通道

    目录: <Java NIO系列教程(二) Channel> <Java NIO系列教程(三) Channel之Socket通道> 在<Java NIO系列教程(二) Ch ...

  8. Android实战简易教程-第三十九枪(第三方短信验证平台Mob和验证码自己主动填入功能结合实例)

    用户注冊或者找回password时通常会用到短信验证功能.这里我们使用第三方的短信平台进行验证实例. 我们用到第三方短信验证平台是Mob,地址为:http://mob.com/ 一.注冊用户.获取SD ...

  9. EnjoyingSoft之Mule ESB开发教程第三篇:Mule message structure - Mule message结构

    目录 1. 探索Mule Message结构 2. Mule Message的Payload 3. Mule Message的Property 4. Mule Message的Attachment 5 ...

  10. [ABP教程]第三章 创建、更新和删除图书

    Web应用程序开发教程 - 第三章: 创建,更新和删除图书 关于本教程 在本系列教程中, 你将构建一个名为 Acme.BookStore 的用于管理书籍及其作者列表的基于ABP的应用程序. 它是使用以 ...

随机推荐

  1. Google guava cache源码解析1--构建缓存器(1)

    此文已由作者赵计刚授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 1.guava cache 当下最常用最简单的本地缓存 线程安全的本地缓存 类似于ConcurrentHas ...

  2. 31_网络编程-struct

    一.struct   1.简述  我们可以借助一个模块,这个模块可以把要发送的数据长度转换成固定长度的字节.这样客户端每次接收消息之前只要先接受这个固定长度字节的内容看一看接下来要接收的信息大小,那么 ...

  3. Swift5 语言参考(四) 表达式

    在Swift中,有四种表达式:前缀表达式,二进制表达式,主表达式和后缀表达式.评估表达式会返回一个值,导致副作用,或两者兼而有之. 前缀和二进制表达式允许您将运算符应用于较小的表达式.主要表达式在概念 ...

  4. Linux巩固记录(8) Hbase shell 基本使用

    继续前几篇内容,讲解hbase基本使用 1.进入hbase shell: hbase有很多种操作方式,比如shell,java客户端,webUI等,可以直接输入hbase进行提示 [root@mast ...

  5. yarn 学习 小记

    官网:https://yarnpkg.com/zh-Hans/docs/installing-dependencies 简介:包管理工具,和npm类似主要特点:快速.安全.可靠 快速:本地安装包后,会 ...

  6. iOS开发-自动隐藏键盘及状态栏

    1.隐藏状态栏 iOS升级至7.0以后,很多API被废止,其中原有隐藏状态栏StatusBar的方法就失效了. 原有方案 [[UIApplication sharedApplication] setS ...

  7. (转)shlex — 解析 Shell 风格语法

    原文:https://pythoncaff.com/docs/pymotw/shlex-parse-shell-style-syntaxes/171 这是一篇协同翻译的文章,你可以点击『我来翻译』按钮 ...

  8. C# 算法系列一基本数据结构

    一.简介 作为一个程序员,算法是一个永远都绕不过去的话题,虽然在大学里参加过ACM的比赛,没记错的话,浙江赛区倒数第二,后来不知怎么的,就不在Care他了,但是现在后悔了,非常的后悔!!!如果当时好好 ...

  9. python垃圾回收

    python垃圾回收 python垃圾回收主要使用引用计数来跟踪和回收垃圾.在引用计数的基础上,通过“标记—清除”解决容器对象可能产生的循环引用问题,通过“分代回收”以空间换时间的方法提高垃圾回收效率 ...

  10. Qt中QMenu的菜单关闭处理方法

    Qt中qmenu的实现三四千行... 当初有个特殊的需求, 要求菜单的周边带几个像素的阴影, 琢磨了半天, 用QMenu做不来, 就干脆自己用窗口写一个 然而怎么让菜单消失却非常麻烦 1. 点击菜单项 ...