Javafx treeview细胞工厂用gridpane


浮华丶
2025-03-18 05:49:17 (6天前)
  1. 我有一个TreeViewlt; GridPanegt; GridPane包含多个节点,如按钮和标签。 GridPane内的节点数量各不相同。

我需要单元工厂来获取MouseEntered …

2 条回复
  1. 0# 子阳 | 2019-08-31 10-32



    这是一个相当简单但全面的例子。分析之后,您应该能够实施您的解决方案。




    1. import javafx.application.Application;
      import javafx.scene.Scene;
      import javafx.scene.control.Label;
      import javafx.scene.control.TreeCell;
      import javafx.scene.control.TreeItem;
      import javafx.scene.control.TreeView;
      import javafx.scene.layout.HBox;
      import javafx.scene.layout.VBox;
      import javafx.stage.Stage;

    2. public class TreeViewCellApp extends Application {

    3. public static void main(String[] args) {
    4.     launch(args);
    5. }
    6. @Override
    7. public void start(Stage stage) throws Exception {
    8.     TreeItem<Employee> leaf1Item = new TreeItem<Employee>(new Employee("Anne Burnes", "Employee"));
    9.     TreeItem<Employee> leaf2Item = new TreeItem<Employee>(new Employee("Ronan Jackson", "Employee"));
    10.     TreeItem<Employee> rootItem = new TreeItem<Employee>(new Employee("Jack Shields", "Head"));
    11.     rootItem.getChildren().add(leaf1Item);
    12.     rootItem.getChildren().add(leaf2Item);
    13.     Label label = new Label();
    14.     TreeView<Employee> treeView = new TreeView<>(rootItem);
    15.     treeView.setCellFactory(param -> new TreeCell<Employee>() {
    16.         @Override
    17.         protected void updateItem(Employee employee, boolean empty) {
    18.             super.updateItem(employee, empty);
    19.             if (employee == null || empty) {
    20.                 setGraphic(null);
    21.             } else {
    22.                 EmployeeControl employeeControl = new EmployeeControl(employee);
    23.                 employeeControl.setOnMouseClicked(mouseEvent -> label.setText(employee.getName()));
    24.                 setGraphic(employeeControl);
    25.             }
    26.         }
    27.     });
    28.     VBox vBox = new VBox(label, treeView);
    29.     stage.setScene(new Scene(vBox));
    30.     stage.show();
    31. }
    32. }

    33. class Employee {

    34. private final String name;
    35. private final String capacity;
    36. public Employee(String name, String capacity) {
    37.     this.name = name;
    38.     this.capacity = capacity;
    39. }
    40. public String getName() {
    41.     return name;
    42. }
    43. public String getCapacity() {
    44.     return capacity;
    45. }
    46. }

    47. class EmployeeControl extends HBox {

    48. private final Label nameLabel = new Label();
    49. private final Label capacityLabel = new Label();
    50. {
    51.     getChildren().addAll(nameLabel, capacityLabel);
    52. }
    53. public EmployeeControl(Employee employee) {
    54.     nameLabel.setText(employee.getName());
    55.     capacityLabel.setText(employee.getCapacity());
    56. }
    57. }

    58. </code>

登录 后才能参与评论