JavaFX 樹表視圖

2018-03-13 00:15 更新

JavaFX教程 - JavaFX樹表視圖


JavaFX TreeTableView在表列中渲染數(shù)據(jù)的層次結(jié)構(gòu)。

TreeTableView組件組合了TreeView和TableView控件。

import javafx.application.Application;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableColumn.CellDataFeatures;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableView;
import javafx.stage.Stage;

public class Main extends Application {
  public static void main(String[] args) {
    Application.launch(args);
  }
  @Override
  public void start(Stage stage) {
    final Scene scene = new Scene(new Group(), 200, 400);
    Group sceneRoot = (Group) scene.getRoot();

    TreeItem<String> childNode1 = new TreeItem<>("Node 1");
    TreeItem<String> childNode2 = new TreeItem<>("Node 2");
    TreeItem<String> childNode3 = new TreeItem<>("Node 3");

    TreeItem<String> root = new TreeItem<>("Root");
    root.setExpanded(true);

    root.getChildren().setAll(childNode1, childNode2, childNode3);

    TreeTableColumn<String, String> column = new TreeTableColumn<>("Column");
    column.setPrefWidth(150);

    column.setCellValueFactory((CellDataFeatures<String, String> p) -> new ReadOnlyStringWrapper(
            p.getValue().getValue()));

    TreeTableView<String> treeTableView = new TreeTableView<>(root);
    treeTableView.getColumns().add(column);
    sceneRoot.getChildren().add(treeTableView);
    stage.setScene(scene);
    stage.show();
  }
}

上面的代碼生成以下結(jié)果。

null

添加幾個(gè)列

/*
 * Copyright (c) 2008, 2014, Oracle and/or its affiliates.
 * All rights reserved. Use is subject to license terms.
 *
 * This file is available and licensed under the following license:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *  - Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the distribution.
 *  - Neither the name of Oracle nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.util.Arrays;
import java.util.List;

import javafx.application.Application;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.stage.Stage;

public class Main extends Application {

  List<Employee> employees = Arrays.<Employee> asList(new Employee(
      "Ethan Williams", "ethan.williams@example.com"), new Employee(
      "Emma Jones", "emma.jones@example.com"), new Employee("Michael Brown",
      "michael.brown@example.com"), new Employee("Anna Black",
      "anna.black@example.com"), new Employee("Rodger York",
      "roger.york@example.com"), new Employee("Susan Collins",
      "susan.collins@example.com"));

  final TreeItem<Employee> root = new TreeItem<>(new Employee(
      "Sales Department", ""));

  public static void main(String[] args) {
    Application.launch(Main.class, args);
  }

  @Override
  public void start(Stage stage) {
    root.setExpanded(true);
    employees.stream().forEach((employee) -> {
      root.getChildren().add(new TreeItem<>(employee));
    });
    Scene scene = new Scene(new Group(), 400, 400);
    Group sceneRoot = (Group) scene.getRoot();

    TreeTableColumn<Employee, String> empColumn = new TreeTableColumn<>(
        "Employee");
    empColumn.setPrefWidth(150);
    empColumn
        .setCellValueFactory((
            TreeTableColumn.CellDataFeatures<Employee, String> param) -> new ReadOnlyStringWrapper(
            param.getValue().getValue().getName()));

    TreeTableColumn<Employee, String> emailColumn = new TreeTableColumn<>(
        "Email");
    emailColumn.setPrefWidth(190);
    emailColumn
        .setCellValueFactory((
            TreeTableColumn.CellDataFeatures<Employee, String> param) -> new ReadOnlyStringWrapper(
            param.getValue().getValue().getEmail()));

    TreeTableView<Employee> treeTableView = new TreeTableView<>(root);
    treeTableView.getColumns().setAll(empColumn, emailColumn);
    sceneRoot.getChildren().add(treeTableView);
    stage.setScene(scene);
    stage.show();
  }

  public class Employee {

    private SimpleStringProperty name;
    private SimpleStringProperty email;

    public SimpleStringProperty nameProperty() {
      if (name == null) {
        name = new SimpleStringProperty(this, "name");
      }
      return name;
    }

    public SimpleStringProperty emailProperty() {
      if (email == null) {
        email = new SimpleStringProperty(this, "email");
      }
      return email;
    }

    private Employee(String name, String email) {
      this.name = new SimpleStringProperty(name);
      this.email = new SimpleStringProperty(email);
    }

    public String getName() {
      return name.get();
    }

    public void setName(String fName) {
      name.set(fName);
    }

    public String getEmail() {
      return email.get();
    }

    public void setEmail(String fName) {
      email.set(fName);
    }
  }
}

上面的代碼生成以下結(jié)果。

null

改變視覺外觀

treeTableView.setTableMenuButtonVisible(true)啟用表格菜單按鈕,以便用戶可以切換表列的可見性。 該方法將“+”按鈕添加到表頭。

/*
 * Copyright (c) 2008, 2014, Oracle and/or its affiliates.
 * All rights reserved. Use is subject to license terms.
 *
 * This file is available and licensed under the following license:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *  - Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the distribution.
 *  - Neither the name of Oracle nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.util.Arrays;
import java.util.List;

import javafx.application.Application;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.stage.Stage;

public class Main extends Application {

  List<Employee> employees = Arrays.<Employee> asList(new Employee(
      "Ethan Williams", "ethan.williams@example.com"), new Employee(
      "Emma Jones", "emma.jones@example.com"), new Employee("Michael Brown",
      "michael.brown@example.com"), new Employee("Anna Black",
      "anna.black@example.com"), new Employee("Rodger York",
      "roger.york@example.com"), new Employee("Susan Collins",
      "susan.collins@example.com"));

  final TreeItem<Employee> root = new TreeItem<>(new Employee(
      "Sales Department", ""));

  public static void main(String[] args) {
    Application.launch(Main.class, args);
  }

  @Override
  public void start(Stage stage) {
    root.setExpanded(true);
    employees.stream().forEach((employee) -> {
      root.getChildren().add(new TreeItem<>(employee));
    });
    Scene scene = new Scene(new Group(), 400, 400);
    Group sceneRoot = (Group) scene.getRoot();

    TreeTableColumn<Employee, String> empColumn = new TreeTableColumn<>(
        "Employee");
    empColumn.setPrefWidth(150);
    empColumn
        .setCellValueFactory((
            TreeTableColumn.CellDataFeatures<Employee, String> param) -> new ReadOnlyStringWrapper(
            param.getValue().getValue().getName()));

    TreeTableColumn<Employee, String> emailColumn = new TreeTableColumn<>(
        "Email");
    emailColumn.setPrefWidth(190);
    emailColumn
        .setCellValueFactory((
            TreeTableColumn.CellDataFeatures<Employee, String> param) -> new ReadOnlyStringWrapper(
            param.getValue().getValue().getEmail()));

    TreeTableView<Employee> treeTableView = new TreeTableView<>(root);
    treeTableView.getColumns().setAll(empColumn, emailColumn);
    
    treeTableView.setTableMenuButtonVisible(true);
    
    
    sceneRoot.getChildren().add(treeTableView);
    stage.setScene(scene);
    stage.show();
  }

  public class Employee {

    private SimpleStringProperty name;
    private SimpleStringProperty email;

    public SimpleStringProperty nameProperty() {
      if (name == null) {
        name = new SimpleStringProperty(this, "name");
      }
      return name;
    }

    public SimpleStringProperty emailProperty() {
      if (email == null) {
        email = new SimpleStringProperty(this, "email");
      }
      return email;
    }

    private Employee(String name, String email) {
      this.name = new SimpleStringProperty(name);
      this.email = new SimpleStringProperty(email);
    }

    public String getName() {
      return name.get();
    }

    public void setName(String fName) {
      name.set(fName);
    }

    public String getEmail() {
      return email.get();
    }

    public void setEmail(String fName) {
      email.set(fName);
    }
  }
}

我們可以通過使用TreeTableView類的setShowRoot方法顯示或隱藏根樹項(xiàng)目。

treeTableView.setShowRoot(false);

上面的代碼生成以下結(jié)果。

null

分類

我們可以通過點(diǎn)擊列標(biāo)題對(duì)數(shù)據(jù)進(jìn)行排序。

設(shè)置列的降序排序模式

aColumn.setSortType(TreeTableColumn.SortType.DESCENDING);

設(shè)置列的升序排序模式

aColumn.setSortType(TreeTableColumn.SortType.ASCENDING);

將排序模式應(yīng)用于所有樹項(xiàng)目

treeTableView.setSortMode(TreeSortMode.ALL_DESCENDANTS);

僅將排序模式應(yīng)用于第一級(jí)節(jié)點(diǎn)

treeTableView.setSortMode(TreeSortMode.ONLY_FIRST_LEVEL);

管理選擇模式

TreeTableView類的默認(rèn)選擇模型是SelectionMode.SINGLE。

要啟用樹項(xiàng)目和單元格的多重選擇,請(qǐng)使用setSelectionModel和setCellSelectionEnabled方法的組合。

啟用單元格的多重選擇

treeTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
treeeTableView.getSelectionModel().setCellSelectionEnabled(true);
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)