Javafx 简明教程

JavaFX - TableView

TableView 是一种图形用户界面组件,用于以表格形式显示数据。与普通表格类似,TableView 由列、行和单元格组成,每个单元格都可以保存任何类型的数据。通常,表格的表示方式如下面的图片所示:

The TableView is a graphical user interface component used to display data in a tabular form. Similar to a typical table, TableView consists of columns, rows, and cells, each of which can hold any type of data. In general, a table is represented as shown in the following figure −

tableview

TableView in JavaFX

在 JavaFX 中,表格视图由 TableView 类表示。此类是名为 javafx.scene.control 的包的一部分。通过实例化此类,我们可以在 JavaFX 中创建一个 TableView 节点。它有两个构造函数,即:

In JavaFX, the table view is represented by the TableView class. This class is a part of the package named javafx.scene.control. By instantiating this class, we can create a TableView node in JavaFX. It has two constructors namely −

  1. TableView() − It is the default constructor used to create a table view without any predefined data.

  2. TableView(ObservableList items) − It is the parameterized constructor of TableView class which accepts a list of items and creates a new table view with the specified items.

Steps to create a TableView in JavaFX

按照下面给出的步骤在 JavaFX 中创建表视图。

Follow the steps given below to create a table view in JavaFX.

Step 1: Create a Class to represent Data within the Table

首先,我们需要创建一个类来表示在 TableView 中显示的数据。此类应该具有与表列相对应的属性。在此,我们将使用以下代码块创建一个名为“Movie”的类,该类具有标题、演员、价格和评分属性−

First, we need to create a class that represents the data to display within the TableView. This class should have properties that correspond to the columns of the table. Here, we will create a class named movie with properties title, actor, price and rating by using the below code blocks −

// The data model class
public static class Movie {
    private final SimpleStringProperty title;
    private final SimpleStringProperty actor;
    private final SimpleDoubleProperty price;
    private final SimpleIntegerProperty rating;

Step 2: Create the Columns for the TableView

创建 TableColumn 对象并使用 setCellValueFactory() 方法设置其单元格值。单元格值工厂是一个函数,它告诉列如何从上述已声明的数据模型类中提取数据。以下代码块显示了如何创建列−

Create TableColumn objects and set their cell value using the setCellValueFactory() method. A cell value factory is a function that tells the column how to extract the data from the above declared data model class. The following code block shows how to create columns −

// Creating columns for the TableView
TableColumn<Movie, String> titleColumn = new TableColumn<>("Movie Name");
titleColumn.setCellValueFactory(cellData -> cellData.getValue().titleProperty());
TableColumn<Movie, String> actorColumn = new TableColumn<>("Actor");
actorColumn.setCellValueFactory(cellData -> cellData.getValue().authorProperty());
TableColumn<Movie, Number> priceColumn = new TableColumn<>("Price");
priceColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty());
TableColumn<Movie, Number> ratingColumn = new TableColumn<>("IMDB Rating");
ratingColumn.setCellValueFactory(cellData -> cellData.getValue().ratingProperty());

Step 3: Instantiate TableView class

实例化包 javafx.scene.controlTableView 类,不向其构造函数传递任何参数值,并使用以下代码块添加所有列−

Instantiate the TableView class of package javafx.scene.control without passing any parameter value to its constructor and add all the columns using the following code blocks −

// Creating a TableView
TableView<Movie> tableView = new TableView<>();
// Adding the columns to the TableView
tableView.getColumns().addAll(titleColumn, actorColumn, priceColumn, ratingColumn);

Step 4: Launching Application

在创建表视图并添加所有数据后,按照以下步骤正确启动应用程序−

Once the table view is created and all the data are added, follow the given steps below to launch the application properly −

  1. Firstly, instantiate the class named BorderPane by passing the TableView object as a parameter value to its constructor.

  2. Then, instantiate the class named Scene by passing the BorderPane object as a parameter value to its constructor. We can also pass dimensions of the application screen as optional parameters to this constructor.

  3. Then, set the title to the stage using the setTitle() method of the Stage class.

  4. Now, a Scene object is added to the stage using the setScene() method of the class named Stage.

  5. Display the contents of the scene using the method named show().

  6. Lastly, the application is launched with the help of the launch() method.

Example

以下是使用 JavaFX 创建 TableView 的程序。将此代码保存在名为 JavafxTableview.java 的文件中。

Following is the program that will create a TableView using JavaFX. Save this code in a file with the name JavafxTableview.java.

import javafx.application.Application;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class JavafxTableview extends Application {
   // The data model class
   public static class Movie {
      private final SimpleStringProperty title;
      private final SimpleStringProperty actor;
      private final SimpleDoubleProperty price;
      private final SimpleIntegerProperty rating;
      // constructor
      public Movie(String title, String actor, double price, int rating) {
         this.title = new SimpleStringProperty(title);
         this.actor = new SimpleStringProperty(actor);
         this.price = new SimpleDoubleProperty(price);
         this.rating = new SimpleIntegerProperty(rating);
      }
      // getters and setters to access the data
      public SimpleStringProperty titleProperty() {
         return title;
      }
      public SimpleStringProperty authorProperty() {
         return actor;
      }
      public SimpleDoubleProperty priceProperty() {
         return price;
      }
      public SimpleIntegerProperty ratingProperty() {
         return rating;
      }
   }
   // main method starts here
   @Override
   public void start(Stage stage) throws Exception {
      // adding some sample data
      ObservableList<Movie> movies = FXCollections.observableArrayList(
         new Movie("The Batman", "Robert Pattinson", 299, 7),
         new Movie("John Wick: Chapter 4", "Keanu Reeves", 199, 7),
         new Movie("12th Fail", "Vikrant Massey", 199, 9),
         new Movie("Money Heist", "Alvaro Morte", 499, 8),
         new Movie("The Family Man", "Manoj Bajpayee", 399, 8)
      );
      // Creating a TableView
      TableView<Movie> tableView = new TableView<>();
      // Creating columns for the TableView
      TableColumn<Movie, String> titleColumn = new TableColumn<>("Movie Name");
      titleColumn.setCellValueFactory(cellData -> cellData.getValue().titleProperty());
      TableColumn<Movie, String> actorColumn = new TableColumn<>("Actor");
      actorColumn.setCellValueFactory(cellData -> cellData.getValue().authorProperty());
      TableColumn<Movie, Number> priceColumn = new TableColumn<>("Price");
      priceColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty());
      TableColumn<Movie, Number> ratingColumn = new TableColumn<>("IMDB Rating");
      ratingColumn.setCellValueFactory(cellData -> cellData.getValue().ratingProperty());
      // Adding the columns to the TableView
      tableView.getColumns().addAll(titleColumn, actorColumn, priceColumn, ratingColumn);
      // Set the items of the TableView
      tableView.setItems(movies);
      // Create a BorderPane and set the TableView as its center
      BorderPane root = new BorderPane();
      root.setCenter(tableView);
      // Create a Scene and set it on the Stage
      Scene scene = new Scene(root, 400, 300);
      stage.setTitle("Table View in JavaFX");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String[] args) {
      launch(args);
   }
}

使用以下命令从命令提示符处编译并执行已保存的 Java 文件。

Compile and execute the saved Java file from the command prompt using the following commands.

javac --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxTableview.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxTableview

执行时,上述程序将生成一个 JavaFX 窗口,其中显示一个 Tableview,其中列出了电影,如下所示。

On executing, the above program generates a JavaFX window displaying a Tableview with a list of movies as shown below.

tableview output

Creating Nested columns of TableView

有时,我们需要在多个子列中显示单列的数据。当单个实体具有多个属性时,这很常见,例如,一个人可能有多个联系电话或电子邮件帐户。在这种情况下,我们创建所需的列,并使用以下 JavaFX 代码中所示的 getColumns() 方法将它们添加到父列中。将此代码保存在名为 NestedTableview.java 的文件中。

Sometimes, we are required to display data of a single column in multiple sub-columns. This is common when a single entity has multiple attributes, for instance, a person can have multiple contact numbers or email accounts. In such cases, we create desired columns and add them to the parent column using getColumns() method as shown in the below JavaFX code. Save this code in a file with the name NestedTableview.java.

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class NestedTableview extends Application {
   @Override
   public void start(Stage stage) {
      // Defining the columns
      TableColumn firstCol = new TableColumn("Column One");
      TableColumn secondCol = new TableColumn("Column Two");
      // creating sub-columns of secondCol
      TableColumn firstSubCol = new TableColumn("Sub Col1");
      TableColumn secondSubCol = new TableColumn("Sub Col2");
      // adding the sub-columns to secondCol
      secondCol.getColumns().addAll(firstSubCol, secondSubCol);
      TableColumn lastCol = new TableColumn("Column Three");
      // instantiating the TableView class
      TableView newTableview = new TableView();
      newTableview.getColumns().addAll(firstCol, secondCol, lastCol);
      VBox root = new VBox();
      root.setSpacing(5);
      root.getChildren().addAll(newTableview);
      // Create a Scene and set it on the Stage
      Scene scene = new Scene(root, 400, 300);
      stage.setTitle("Nested TableView in JavaFX");
      stage.setScene(scene);
      stage.show();
   }
      public static void main(String[] args) {
      launch(args);
   }
}

要从命令提示符编译并执行已保存的 Java 文件,请使用以下命令−

To compile and execute the saved Java file from the command prompt, use the following commands −

javac --module-path %PATH_TO_FX% --add-modules javafx.controls NestedTableview.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls NestedTableview

在执行上述代码时,它将生成以下输出。

On executing the above code, it will generate the following output.

nested tableview