当前位置:   article > 正文

javafX8初探(表格)_javafx 表格

javafx 表格

本节,我们将学习如何在JavaFX应用中操作表格。比如:添加表格,为表格填充数据、编辑表格的行。

JavaFX中提供了一些类让我们更方便的操作表格,最重要的类有TableViewTableColumnTableCell。我们可以通过实现数据模型和使用单元工厂来填充表格。这些类都提供了列排序和改变列的宽度。

下图是一个典型的地址信息表格:

创建一个表格

  1. import javafx.application.Application;
  2. import javafx.geometry.Insets;
  3. import javafx.scene.Group;
  4. import javafx.scene.Scene;
  5. import javafx.scene.control.Label;
  6. import javafx.scene.control.TableColumn;
  7. import javafx.scene.control.TableView;
  8. import javafx.scene.layout.VBox;
  9. import javafx.scene.text.Font;
  10. import javafx.stage.Stage;
  11. public class TableViewSample extends Application {
  12. private final TableView table = new TableView();
  13. public static void main(String[] args) {
  14. launch(args);
  15. }
  16. @Override
  17. public void start(Stage stage) {
  18. Scene scene = new Scene(new Group());
  19. stage.setTitle("Table View Sample");
  20. stage.setWidth(300);
  21. stage.setHeight(500);
  22. final Label label = new Label("Address Book");
  23. label.setFont(new Font("Arial", 20));
  24. table.setEditable(true);
  25. TableColumn firstNameCol = new TableColumn("First Name");
  26. TableColumn lastNameCol = new TableColumn("Last Name");
  27. TableColumn emailCol = new TableColumn("Email");
  28. table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
  29. final VBox vbox = new VBox();
  30. vbox.setSpacing(5);
  31. vbox.setPadding(new Insets(10, 0, 0, 10));
  32. vbox.getChildren().addAll(label, table);
  33. ((Group) scene.getRoot()).getChildren().addAll(vbox);
  34. stage.setScene(scene);
  35. stage.show();
  36. }
  37. }


 

表格控件是通过TableView来创建的,并且被添加到一个VBox的容器中,当然你也可以直接把这个表格添加到场景中。

然后创建了3列来存数地址信息:first name last name和邮件地址。列是通过TableColumn类来创建的。

然后getColumns方法添加了之前创建的3列。在你自己的应用中,你可以通过这个方法来增加和删除列。

编译运行,如下图所示:

你也可以通过setVisble来设置列的可见性。举个例子。如果你的例子中药隐藏邮件地址的列。你可以使用下面的方法。EmailCol.setVisble(false);

如果你的表格需要更复杂的表现,比如需要嵌套列。举个例子,如果一个人有两个邮件地址。那么我们需要两列来存储第一个和第二个邮件地址。我们创建两个子列,然后通过getColumns方法来添加这两个子列。

  1. TableColumn firstEmailCol = new TableColumn("Primary");
  2. TableColumn secondEmailCol = new TableColumn("Secondary");
  3. emailCol.getColumns().addAll(firstEmailCol, secondEmailCol);


 

编译运行代码,如下图所示:

尽管这个表格已经添加到我们的应用中了,但是其中没有内容,显示了“No content

In table.我们可以通过,setPlaceholder方法来指定没有数据时的显示内容。

定义数据模型

当你创建了一个表格后,最好能有一个类定义数据模型,然后提供方法和域来更好的为表格服务。下面我们使用一个Person类来定义地址表格中的数据。

  1. public static class Person {
  2. private final SimpleStringProperty firstName;
  3. private final SimpleStringProperty lastName;
  4. private final SimpleStringProperty email;
  5. private Person(String fName, String lName, String email) {
  6. this.firstName = new SimpleStringProperty(fName);
  7. this.lastName = new SimpleStringProperty(lName);
  8. this.email = new SimpleStringProperty(email);
  9. }
  10. public String getFirstName() {
  11. return firstName.get();
  12. }
  13. public void setFirstName(String fName) {
  14. firstName.set(fName);
  15. }
  16. public String getLastName() {
  17. return lastName.get();
  18. }
  19. public void setLastName(String fName) {
  20. lastName.set(fName);
  21. }
  22. public String getEmail() {
  23. return email.get();
  24. }
  25. public void setEmail(String fName) {
  26. email.set(fName);
  27. }
  28. }


 

其中firstNamelastNameemail 3个字符串属性代表了表格中的3个列。

而且没有属性都提供了getset方法。Get方法返回属性的值,set方法为属性赋值。

然后我们使用Person类创建一个ObservableList,定义多行数据。

  1. final ObservableList<Person> data = FXCollections.observableArrayList(
  2. new Person("Jacob", "Smith", "jacob.smith@example.com"),
  3. new Person("Isabella", "Johnson", "isabella.johnson@example.com"),
  4. new Person("Ethan", "Williams", "ethan.williams@example.com"),
  5. new Person("Emma", "Jones", "emma.jones@example.com"),
  6. new Person("Michael", "Brown", "michael.brown@example.com")
  7. );


 

下一步就是把这些数据关联到表格中。我们可以通过属性的名字来关联。

  1. firstNameCol.setCellValueFactory(
  2. new PropertyValueFactory<>("firstName")
  3. );
  4. lastNameCol.setCellValueFactory(
  5. new PropertyValueFactory<>("lastName")
  6. );
  7. emailCol.setCellValueFactory(
  8. new PropertyValueFactory<>("email")
  9. );


 

SetCellValueFactory方法指定了每一列的单元格工厂。单元格的属性是通过PropertyValueFactory类来实现的。

当数据模型定义好后并且也关联到表格中,我们就这个通过TableViewsetItems方法来添加数据了。代码如下:

  1. import javafx.application.Application;
  2. import javafx.beans.property.SimpleStringProperty;
  3. import javafx.collections.FXCollections;
  4. import javafx.collections.ObservableList;
  5. import javafx.geometry.Insets;
  6. import javafx.scene.Group;
  7. import javafx.scene.Scene;
  8. import javafx.scene.control.Label;
  9. import javafx.scene.control.TableColumn;
  10. import javafx.scene.control.TableView;
  11. import javafx.scene.control.cell.PropertyValueFactory;
  12. import javafx.scene.layout.VBox;
  13. import javafx.scene.text.Font;
  14. import javafx.stage.Stage;
  15. public class TableViewSample extends Application {
  16. private final TableView<Person> table = new TableView<>();
  17. private final ObservableList<Person> data =
  18. FXCollections.observableArrayList(
  19. new Person("Jacob", "Smith", "jacob.smith@example.com"),
  20. new Person("Isabella", "Johnson", "isabella.johnson@example.com"),
  21. new Person("Ethan", "Williams", "ethan.williams@example.com"),
  22. new Person("Emma", "Jones", "emma.jones@example.com"),
  23. new Person("Michael", "Brown", "michael.brown@example.com")
  24. );
  25. public static void main(String[] args) {
  26. launch(args);
  27. }
  28. @Override
  29. public void start(Stage stage) {
  30. Scene scene = new Scene(new Group());
  31. stage.setTitle("Table View Sample");
  32. stage.setWidth(450);
  33. stage.setHeight(500);
  34. final Label label = new Label("Address Book");
  35. label.setFont(new Font("Arial", 20));
  36. table.setEditable(true);
  37. TableColumn firstNameCol = new TableColumn("First Name");
  38. firstNameCol.setMinWidth(100);
  39. firstNameCol.setCellValueFactory(
  40. new PropertyValueFactory<>("firstName"));
  41. TableColumn lastNameCol = new TableColumn("Last Name");
  42. lastNameCol.setMinWidth(100);
  43. lastNameCol.setCellValueFactory(
  44. new PropertyValueFactory<>("lastName"));
  45. TableColumn emailCol = new TableColumn("Email");
  46. emailCol.setMinWidth(200);
  47. emailCol.setCellValueFactory(
  48. new PropertyValueFactory<>("email"));
  49. table.setItems(data);
  50. table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
  51. final VBox vbox = new VBox();
  52. vbox.setSpacing(5);
  53. vbox.setPadding(new Insets(10, 0, 0, 10));
  54. vbox.getChildren().addAll(label, table);
  55. ((Group) scene.getRoot()).getChildren().addAll(vbox);
  56. stage.setScene(scene);
  57. stage.show();
  58. }
  59. public static class Person {
  60. private final SimpleStringProperty firstName;
  61. private final SimpleStringProperty lastName;
  62. private final SimpleStringProperty email;
  63. private Person(String fName, String lName, String email) {
  64. this.firstName = new SimpleStringProperty(fName);
  65. this.lastName = new SimpleStringProperty(lName);
  66. this.email = new SimpleStringProperty(email);
  67. }
  68. public String getFirstName() {
  69. return firstName.get();
  70. }
  71. public void setFirstName(String fName) {
  72. firstName.set(fName);
  73. }
  74. public String getLastName() {
  75. return lastName.get();
  76. }
  77. public void setLastName(String fName) {
  78. lastName.set(fName);
  79. }
  80. public String getEmail() {
  81. return email.get();
  82. }
  83. public void setEmail(String fName) {
  84. email.set(fName);
  85. }
  86. }
  87. }

编译运行代码,如下图所示:

添加新行

  1. import javafx.application.Application;
  2. import javafx.beans.property.SimpleStringProperty;
  3. import javafx.collections.FXCollections;
  4. import javafx.collections.ObservableList;
  5. import javafx.event.ActionEvent;
  6. import javafx.geometry.Insets;
  7. import javafx.scene.Group;
  8. import javafx.scene.Scene;
  9. import javafx.scene.control.Button;
  10. import javafx.scene.control.Label;
  11. import javafx.scene.control.TableColumn;
  12. import javafx.scene.control.TableView;
  13. import javafx.scene.control.TextField;
  14. import javafx.scene.control.cell.PropertyValueFactory;
  15. import javafx.scene.layout.HBox;
  16. import javafx.scene.layout.VBox;
  17. import javafx.scene.text.Font;
  18. import javafx.stage.Stage;
  19. public class TableViewSample extends Application {
  20. private final TableView<Person> table = new TableView<>();
  21. private final ObservableList<Person> data =
  22. FXCollections.observableArrayList(
  23. new Person("Jacob", "Smith", "jacob.smith@example.com"),
  24. new Person("Isabella", "Johnson", "isabella.johnson@example.com"),
  25. new Person("Ethan", "Williams", "ethan.williams@example.com"),
  26. new Person("Emma", "Jones", "emma.jones@example.com"),
  27. new Person("Michael", "Brown", "michael.brown@example.com"));
  28. final HBox hb = new HBox();
  29. public static void main(String[] args) {
  30. launch(args);
  31. }
  32. @Override
  33. public void start(Stage stage) {
  34. Scene scene = new Scene(new Group());
  35. stage.setTitle("Table View Sample");
  36. stage.setWidth(450);
  37. stage.setHeight(550);
  38. final Label label = new Label("Address Book");
  39. label.setFont(new Font("Arial", 20));
  40. table.setEditable(true);
  41. TableColumn firstNameCol = new TableColumn("First Name");
  42. firstNameCol.setMinWidth(100);
  43. firstNameCol.setCellValueFactory(
  44. new PropertyValueFactory<>("firstName"));
  45. TableColumn lastNameCol = new TableColumn("Last Name");
  46. lastNameCol.setMinWidth(100);
  47. lastNameCol.setCellValueFactory(
  48. new PropertyValueFactory<>("lastName"));
  49. TableColumn emailCol = new TableColumn("Email");
  50. emailCol.setMinWidth(200);
  51. emailCol.setCellValueFactory(
  52. new PropertyValueFactory<>("email"));
  53. table.setItems(data);
  54. table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
  55. final TextField addFirstName = new TextField();
  56. addFirstName.setPromptText("First Name");
  57. addFirstName.setMaxWidth(firstNameCol.getPrefWidth());
  58. final TextField addLastName = new TextField();
  59. addLastName.setMaxWidth(lastNameCol.getPrefWidth());
  60. addLastName.setPromptText("Last Name");
  61. final TextField addEmail = new TextField();
  62. addEmail.setMaxWidth(emailCol.getPrefWidth());
  63. addEmail.setPromptText("Email");
  64. final Button addButton = new Button("Add");
  65. addButton.setOnAction((ActionEvent e) -> {
  66. data.add(new Person(
  67. addFirstName.getText(),
  68. addLastName.getText(),
  69. addEmail.getText()));
  70. addFirstName.clear();
  71. addLastName.clear();
  72. addEmail.clear();
  73. });
  74. hb.getChildren().addAll(addFirstName, addLastName, addEmail, addButton);
  75. hb.setSpacing(3);
  76. final VBox vbox = new VBox();
  77. vbox.setSpacing(5);
  78. vbox.setPadding(new Insets(10, 0, 0, 10));
  79. vbox.getChildren().addAll(label, table, hb);
  80. ((Group) scene.getRoot()).getChildren().addAll(vbox);
  81. stage.setScene(scene);
  82. stage.show();
  83. }
  84. public static class Person {
  85. private final SimpleStringProperty firstName;
  86. private final SimpleStringProperty lastName;
  87. private final SimpleStringProperty email;
  88. private Person(String fName, String lName, String email) {
  89. this.firstName = new SimpleStringProperty(fName);
  90. this.lastName = new SimpleStringProperty(lName);
  91. this.email = new SimpleStringProperty(email);
  92. }
  93. public String getFirstName() {
  94. return firstName.get();
  95. }
  96. public void setFirstName(String fName) {
  97. firstName.set(fName);
  98. }
  99. public String getLastName() {
  100. return lastName.get();
  101. }
  102. public void setLastName(String fName) {
  103. lastName.set(fName);
  104. }
  105. public String getEmail() {
  106. return email.get();
  107. }
  108. public void setEmail(String fName) {
  109. email.set(fName);
  110. }
  111. }
  112. }


运行,如下图所示:

排序

TableView类为表格提供了排序列的能力,用户可以通过单击列头来实现排序.第一次单击按照升序排列,第二次单击按照降序排列,第三次单击不排序。默认不排序。

用户也可以按照多行排序。当单击列头的是由按住Shift键就可以。如下图所示:

作为开发者,我们可以指定列的排序类型。可用通过setSortType方法来指定比如emailCol.setSortType(TableColumn.SortType.SESCENDING);

我们也可以通过setSortablefalse)方法来禁止排序。

编辑表格数据

  1. import javafx.application.Application;
  2. import javafx.beans.property.SimpleStringProperty;
  3. import javafx.collections.FXCollections;
  4. import javafx.collections.ObservableList;
  5. import javafx.event.ActionEvent;
  6. import javafx.geometry.Insets;
  7. import javafx.scene.Group;
  8. import javafx.scene.Scene;
  9. import javafx.scene.control.Button;
  10. import javafx.scene.control.Label;
  11. import javafx.scene.control.TableColumn;
  12. import javafx.scene.control.TableColumn.CellEditEvent;
  13. import javafx.scene.control.TableView;
  14. import javafx.scene.control.TextField;
  15. import javafx.scene.control.cell.PropertyValueFactory;
  16. import javafx.scene.control.cell.TextFieldTableCell;
  17. import javafx.scene.layout.HBox;
  18. import javafx.scene.layout.VBox;
  19. import javafx.scene.text.Font;
  20. import javafx.stage.Stage;
  21. public class TableViewSample extends Application {
  22. private final TableView<Person> table = new TableView<>();
  23. private final ObservableList<Person> data =
  24. FXCollections.observableArrayList(
  25. new Person("Jacob", "Smith", "jacob.smith@example.com"),
  26. new Person("Isabella", "Johnson", "isabella.johnson@example.com"),
  27. new Person("Ethan", "Williams", "ethan.williams@example.com"),
  28. new Person("Emma", "Jones", "emma.jones@example.com"),
  29. new Person("Michael", "Brown", "michael.brown@example.com"));
  30. final HBox hb = new HBox();
  31. public static void main(String[] args) {
  32. launch(args);
  33. }
  34. @Override
  35. public void start(Stage stage) {
  36. Scene scene = new Scene(new Group());
  37. stage.setTitle("Table View Sample");
  38. stage.setWidth(450);
  39. stage.setHeight(550);
  40. final Label label = new Label("Address Book");
  41. label.setFont(new Font("Arial", 20));
  42. table.setEditable(true);
  43. TableColumn<Person, String> firstNameCol =
  44. new TableColumn<>("First Name");
  45. firstNameCol.setMinWidth(100);
  46. firstNameCol.setCellValueFactory(
  47. new PropertyValueFactory<>("firstName"));
  48. firstNameCol.setCellFactory(TextFieldTableCell.<Person>forTableColumn());
  49. firstNameCol.setOnEditCommit(
  50. (CellEditEvent<Person, String> t) -> {
  51. ((Person) t.getTableView().getItems().get(
  52. t.getTablePosition().getRow())
  53. ).setFirstName(t.getNewValue());
  54. });
  55. TableColumn<Person, String> lastNameCol =
  56. new TableColumn<>("Last Name");
  57. lastNameCol.setMinWidth(100);
  58. lastNameCol.setCellValueFactory(
  59. new PropertyValueFactory<>("lastName"));
  60. lastNameCol.setCellFactory(TextFieldTableCell.<Person>forTableColumn());
  61. lastNameCol.setOnEditCommit(
  62. (CellEditEvent<Person, String> t) -> {
  63. ((Person) t.getTableView().getItems().get(
  64. t.getTablePosition().getRow())
  65. ).setLastName(t.getNewValue());
  66. });
  67. TableColumn<Person, String> emailCol = new TableColumn<>("Email");
  68. emailCol.setMinWidth(200);
  69. emailCol.setCellValueFactory(
  70. new PropertyValueFactory<>("email"));
  71. emailCol.setCellFactory(TextFieldTableCell.<Person>forTableColumn());
  72. emailCol.setOnEditCommit(
  73. (CellEditEvent<Person, String> t) -> {
  74. ((Person) t.getTableView().getItems().get(
  75. t.getTablePosition().getRow())
  76. ).setEmail(t.getNewValue());
  77. });
  78. table.setItems(data);
  79. table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
  80. final TextField addFirstName = new TextField();
  81. addFirstName.setPromptText("First Name");
  82. addFirstName.setMaxWidth(firstNameCol.getPrefWidth());
  83. final TextField addLastName = new TextField();
  84. addLastName.setMaxWidth(lastNameCol.getPrefWidth());
  85. addLastName.setPromptText("Last Name");
  86. final TextField addEmail = new TextField();
  87. addEmail.setMaxWidth(emailCol.getPrefWidth());
  88. addEmail.setPromptText("Email");
  89. final Button addButton = new Button("Add");
  90. addButton.setOnAction((ActionEvent e) -> {
  91. data.add(new Person(
  92. addFirstName.getText(),
  93. addLastName.getText(),
  94. addEmail.getText()));
  95. addFirstName.clear();
  96. addLastName.clear();
  97. addEmail.clear();
  98. });
  99. hb.getChildren().addAll(addFirstName, addLastName, addEmail, addButton);
  100. hb.setSpacing(3);
  101. final VBox vbox = new VBox();
  102. vbox.setSpacing(5);
  103. vbox.setPadding(new Insets(10, 0, 0, 10));
  104. vbox.getChildren().addAll(label, table, hb);
  105. ((Group) scene.getRoot()).getChildren().addAll(vbox);
  106. stage.setScene(scene);
  107. stage.show();
  108. }
  109. public static class Person {
  110. private final SimpleStringProperty firstName;
  111. private final SimpleStringProperty lastName;
  112. private final SimpleStringProperty email;
  113. private Person(String fName, String lName, String email) {
  114. this.firstName = new SimpleStringProperty(fName);
  115. this.lastName = new SimpleStringProperty(lName);
  116. this.email = new SimpleStringProperty(email);
  117. }
  118. public String getFirstName() {
  119. return firstName.get();
  120. }
  121. public void setFirstName(String fName) {
  122. firstName.set(fName);
  123. }
  124. public String getLastName() {
  125. return lastName.get();
  126. }
  127. public void setLastName(String fName) {
  128. lastName.set(fName);
  129. }
  130. public String getEmail() {
  131. return email.get();
  132. }
  133. public void setEmail(String fName) {
  134. email.set(fName);
  135. }
  136. }
  137. }


运行,如下图所示:

上面的例子,我们修改后需要按回车键才能生效,我们可以让当焦点改变的时候就生效:

  1. import javafx.application.Application;
  2. import javafx.beans.property.SimpleStringProperty;
  3. import javafx.beans.value.ObservableValue;
  4. import javafx.collections.FXCollections;
  5. import javafx.collections.ObservableList;
  6. import javafx.event.ActionEvent;
  7. import javafx.geometry.Insets;
  8. import javafx.scene.Group;
  9. import javafx.scene.Scene;
  10. import javafx.scene.control.Button;
  11. import javafx.scene.control.Label;
  12. import javafx.scene.control.TableCell;
  13. import javafx.scene.control.TableColumn;
  14. import javafx.scene.control.TableColumn.CellEditEvent;
  15. import javafx.scene.control.TableView;
  16. import javafx.scene.control.TextField;
  17. import javafx.scene.control.cell.PropertyValueFactory;
  18. import javafx.scene.layout.HBox;
  19. import javafx.scene.layout.VBox;
  20. import javafx.scene.text.Font;
  21. import javafx.stage.Stage;
  22. import javafx.util.Callback;
  23. public class TableViewSample extends Application {
  24. private final TableView<Person> table = new TableView<>();
  25. private final ObservableList<Person> data =
  26. FXCollections.observableArrayList(
  27. new Person("Jacob", "Smith", "jacob.smith@example.com"),
  28. new Person("Isabella", "Johnson", "isabella.johnson@example.com"),
  29. new Person("Ethan", "Williams", "ethan.williams@example.com"),
  30. new Person("Emma", "Jones", "emma.jones@example.com"),
  31. new Person("Michael", "Brown", "michael.brown@example.com"));
  32. final HBox hb = new HBox();
  33. public static void main(String[] args) {
  34. launch(args);
  35. }
  36. @Override
  37. public void start(Stage stage) {
  38. Scene scene = new Scene(new Group());
  39. stage.setTitle("Table View Sample");
  40. stage.setWidth(450);
  41. stage.setHeight(550);
  42. final Label label = new Label("Address Book");
  43. label.setFont(new Font("Arial", 20));
  44. table.setEditable(true);
  45. Callback<TableColumn<Person, String>,
  46. TableCell<Person, String>> cellFactory
  47. = (TableColumn<Person, String> p) -> new EditingCell();
  48. TableColumn<Person, String> firstNameCol =
  49. new TableColumn<>("First Name");
  50. TableColumn<Person, String> lastNameCol =
  51. new TableColumn<>("Last Name");
  52. TableColumn<Person, String> emailCol =
  53. new TableColumn<>("Email");
  54. firstNameCol.setMinWidth(100);
  55. firstNameCol.setCellValueFactory(
  56. new PropertyValueFactory<>("firstName"));
  57. firstNameCol.setCellFactory(cellFactory);
  58. firstNameCol.setOnEditCommit(
  59. (CellEditEvent<Person, String> t) -> {
  60. ((Person) t.getTableView().getItems().get(
  61. t.getTablePosition().getRow())
  62. ).setFirstName(t.getNewValue());
  63. });
  64. lastNameCol.setMinWidth(100);
  65. lastNameCol.setCellValueFactory(
  66. new PropertyValueFactory<>("lastName"));
  67. lastNameCol.setCellFactory(cellFactory);
  68. lastNameCol.setOnEditCommit(
  69. (CellEditEvent<Person, String> t) -> {
  70. ((Person) t.getTableView().getItems().get(
  71. t.getTablePosition().getRow())
  72. ).setLastName(t.getNewValue());
  73. });
  74. emailCol.setMinWidth(200);
  75. emailCol.setCellValueFactory(
  76. new PropertyValueFactory<>("email"));
  77. emailCol.setCellFactory(cellFactory);
  78. emailCol.setOnEditCommit(
  79. (CellEditEvent<Person, String> t) -> {
  80. ((Person) t.getTableView().getItems().get(
  81. t.getTablePosition().getRow())
  82. ).setEmail(t.getNewValue());
  83. });
  84. table.setItems(data);
  85. table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
  86. final TextField addFirstName = new TextField();
  87. addFirstName.setPromptText("First Name");
  88. addFirstName.setMaxWidth(firstNameCol.getPrefWidth());
  89. final TextField addLastName = new TextField();
  90. addLastName.setMaxWidth(lastNameCol.getPrefWidth());
  91. addLastName.setPromptText("Last Name");
  92. final TextField addEmail = new TextField();
  93. addEmail.setMaxWidth(emailCol.getPrefWidth());
  94. addEmail.setPromptText("Email");
  95. final Button addButton = new Button("Add");
  96. addButton.setOnAction((ActionEvent e) -> {
  97. data.add(new Person(
  98. addFirstName.getText(),
  99. addLastName.getText(),
  100. addEmail.getText()));
  101. addFirstName.clear();
  102. addLastName.clear();
  103. addEmail.clear();
  104. });
  105. hb.getChildren().addAll(addFirstName, addLastName, addEmail, addButton);
  106. hb.setSpacing(3);
  107. final VBox vbox = new VBox();
  108. vbox.setSpacing(5);
  109. vbox.setPadding(new Insets(10, 0, 0, 10));
  110. vbox.getChildren().addAll(label, table, hb);
  111. ((Group) scene.getRoot()).getChildren().addAll(vbox);
  112. stage.setScene(scene);
  113. stage.show();
  114. }
  115. public static class Person {
  116. private final SimpleStringProperty firstName;
  117. private final SimpleStringProperty lastName;
  118. private final SimpleStringProperty email;
  119. private Person(String fName, String lName, String email) {
  120. this.firstName = new SimpleStringProperty(fName);
  121. this.lastName = new SimpleStringProperty(lName);
  122. this.email = new SimpleStringProperty(email);
  123. }
  124. public String getFirstName() {
  125. return firstName.get();
  126. }
  127. public void setFirstName(String fName) {
  128. firstName.set(fName);
  129. }
  130. public String getLastName() {
  131. return lastName.get();
  132. }
  133. public void setLastName(String fName) {
  134. lastName.set(fName);
  135. }
  136. public String getEmail() {
  137. return email.get();
  138. }
  139. public void setEmail(String fName) {
  140. email.set(fName);
  141. }
  142. }
  143. class EditingCell extends TableCell<Person, String> {
  144. private TextField textField;
  145. public EditingCell() {
  146. }
  147. @Override
  148. public void startEdit() {
  149. if (!isEmpty()) {
  150. super.startEdit();
  151. createTextField();
  152. setText(null);
  153. setGraphic(textField);
  154. textField.selectAll();
  155. }
  156. }
  157. @Override
  158. public void cancelEdit() {
  159. super.cancelEdit();
  160. setText((String) getItem());
  161. setGraphic(null);
  162. }
  163. @Override
  164. public void updateItem(String item, boolean empty) {
  165. super.updateItem(item, empty);
  166. if (empty) {
  167. setText(null);
  168. setGraphic(null);
  169. } else {
  170. if (isEditing()) {
  171. if (textField != null) {
  172. textField.setText(getString());
  173. }
  174. setText(null);
  175. setGraphic(textField);
  176. } else {
  177. setText(getString());
  178. setGraphic(null);
  179. }
  180. }
  181. }
  182. private void createTextField() {
  183. textField = new TextField(getString());
  184. textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
  185. textField.focusedProperty().addListener(
  186. (ObservableValue<? extends Boolean> arg0,
  187. Boolean arg1, Boolean arg2) -> {
  188. if (!arg2) {
  189. commitEdit(textField.getText());
  190. }
  191. });
  192. }
  193. private String getString() {
  194. return getItem() == null ? "" : getItem().toString();
  195. }
  196. }
  197. }


 

为表格添加数据映射

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import javafx.application.Application;
  4. import javafx.collections.FXCollections;
  5. import javafx.collections.ObservableList;
  6. import javafx.geometry.Insets;
  7. import javafx.scene.Group;
  8. import javafx.scene.Scene;
  9. import javafx.scene.control.Label;
  10. import javafx.scene.control.TableCell;
  11. import javafx.scene.control.TableColumn;
  12. import javafx.scene.control.TableView;
  13. import javafx.scene.control.cell.MapValueFactory;
  14. import javafx.scene.control.cell.TextFieldTableCell;
  15. import javafx.scene.layout.VBox;
  16. import javafx.scene.text.Font;
  17. import javafx.stage.Stage;
  18. import javafx.util.Callback;
  19. import javafx.util.StringConverter;
  20. public class TableViewSample extends Application {
  21. public static final String Column1MapKey = "A";
  22. public static final String Column2MapKey = "B";
  23. public static void main(String[] args) {
  24. launch(args);
  25. }
  26. @Override
  27. public void start(Stage stage) {
  28. Scene scene = new Scene(new Group());
  29. stage.setTitle("Table View Sample");
  30. stage.setWidth(300);
  31. stage.setHeight(500);
  32. final Label label = new Label("Student IDs");
  33. label.setFont(new Font("Arial", 20));
  34. TableColumn<Map, String> firstDataColumn = new TableColumn<>("Class A");
  35. TableColumn<Map, String> secondDataColumn = new TableColumn<>("Class B");
  36. firstDataColumn.setCellValueFactory(new MapValueFactory(Column1MapKey));
  37. firstDataColumn.setMinWidth(130);
  38. secondDataColumn.setCellValueFactory(new MapValueFactory(Column2MapKey));
  39. secondDataColumn.setMinWidth(130);
  40. TableView tableView = new TableView<>(generateDataInMap());
  41. tableView.setEditable(true);
  42. tableView.getSelectionModel().setCellSelectionEnabled(true);
  43. tableView.getColumns().setAll(firstDataColumn, secondDataColumn);
  44. Callback<TableColumn<Map, String>, TableCell<Map, String>>
  45. cellFactoryForMap = (TableColumn<Map, String> p) ->
  46. new TextFieldTableCell(new StringConverter() {
  47. @Override
  48. public String toString(Object t) {
  49. return t.toString();
  50. }
  51. @Override
  52. public Object fromString(String string) {
  53. return string;
  54. }
  55. });
  56. firstDataColumn.setCellFactory(cellFactoryForMap);
  57. secondDataColumn.setCellFactory(cellFactoryForMap);
  58. final VBox vbox = new VBox();
  59. vbox.setSpacing(5);
  60. vbox.setPadding(new Insets(10, 0, 0, 10));
  61. vbox.getChildren().addAll(label, tableView);
  62. ((Group) scene.getRoot()).getChildren().addAll(vbox);
  63. stage.setScene(scene);
  64. stage.show();
  65. }
  66. private ObservableList<Map> generateDataInMap() {
  67. int max = 10;
  68. ObservableList<Map> allData = FXCollections.observableArrayList();
  69. for (int i = 1; i < max; i++) {
  70. Map<String, String> dataRow = new HashMap<>();
  71. String value1 = "A" + i;
  72. String value2 = "B" + i;
  73. dataRow.put(Column1MapKey, value1);
  74. dataRow.put(Column2MapKey, value2);
  75. allData.add(dataRow);
  76. }
  77. return allData;
  78. }
  79. }


 

如下图所示:

 


 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/191667
推荐阅读
  

闽ICP备14008679号