2014-09-21 2 views
3

У меня есть этот очень простой пример TreeView.Сортировка TreeView по имени

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 TreeTableViewSample extends Application { 

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

    @Override 
    public void start(Stage stage) { 
     stage.setTitle("Tree Table View Samples"); 
     final Scene scene = new Scene(new Group(), 200, 400); 
     Group sceneRoot = (Group)scene.getRoot(); 

     //Creating tree items 
     final TreeItem<String> childNode1 = new TreeItem<>("Child Node 1"); 
     final TreeItem<String> childNode2 = new TreeItem<>("Child Node 2"); 
     final TreeItem<String> childNode3 = new TreeItem<>("Child Node 3"); 

     //Creating the root element 
     final TreeItem<String> root = new TreeItem<>("Root node"); 
     root.setExpanded(true); 

     //Adding tree items to the root 
     root.getChildren().setAll(childNode1, childNode2, childNode3);   

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

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

     //Creating a tree table view 
     final TreeTableView<String> treeTableView = new TreeTableView<>(root); 
     treeTableView.getColumns().add(column); 
     treeTableView.setPrefWidth(152); 
     treeTableView.setShowRoot(true);    
     sceneRoot.getChildren().add(treeTableView); 
     stage.setScene(scene); 
     stage.show(); 
    }  
} 

Мне интересно, как я могу сортировать узлы дерева по имени?

Эта функциональность уже реализована в JavaFX или мне нужно реализовать пользовательскую древовидную ячейку?

Есть ли какой-нибудь пример, который я могу использовать?

ответ

3

По умолчанию элементы на каждом TableColumn можно отсортировать, просто щелкнув по его заголовку один или два раза, чтобы получить порядок сортировки по умолчанию (по возрастанию или по убыванию).

Компаратор по умолчанию - String.compareTo, который сравнивает две строки лексикографически.

Но вы можете реализовать свои собственные. Например, это будет сортировать по длине строки:

// compare by length of the strings 
column.setComparator(Comparator.comparing(String::length)); 

И это один сортирует сначала по длине, то в случае одинаковой длины, по имени:

// compare by length first, and then lexicographically 
column.setComparator(Comparator.comparing(String::length).thenComparing(String::compareTo)); 

EDIT: Так как пример относится к TreeTableView, но ОП запрашивает TreeView, так можно сортировать элементы:

1) Поскольку мы добавляем коллекцию элементов, мы можем сортировать их перед добавлением детей в е корень

@Override 
public void start(Stage stage) { 
    stage.setTitle("Tree Table View Samples"); 
    final Scene scene = new Scene(new Group(), 200, 400); 
    Group sceneRoot = (Group)scene.getRoot(); 

    //Creating tree items 
    final TreeItem<String> childNode1 = new TreeItem<>("Child Node 10"); 
    final TreeItem<String> childNode2 = new TreeItem<>("Child Node Two"); 
    final TreeItem<String> childNode3 = new TreeItem<>("Child Node 3"); 

    //Creating the root element 
    final TreeItem<String> root = new TreeItem<>("Root node"); 
    root.setExpanded(true); 

    List<TreeItem<String>> list = Arrays.asList(childNode1, childNode2, childNode3); 
    // sort by length of the item's names 
    list.sort(Comparator.comparing(t->t.getValue().length())); 

    //Adding tree items to the root 
    root.getChildren().setAll(list); 

    TreeView<String> tree = new TreeView<> (root);  

    sceneRoot.getChildren().add(tree); 
    stage.setScene(scene); 
    stage.show();   
} 

2) После того, как мы добавили детали к корню мы можем обеспечить Comparator к корню:

@Override 
public void start(Stage stage) { 
    stage.setTitle("Tree Table View Samples"); 
    final Scene scene = new Scene(new Group(), 200, 400); 
    Group sceneRoot = (Group)scene.getRoot(); 

    //Creating tree items 
    final TreeItem<String> childNode1 = new TreeItem<>("Child Node 10"); 
    final TreeItem<String> childNode2 = new TreeItem<>("Child Node Two"); 
    final TreeItem<String> childNode3 = new TreeItem<>("Child Node 3"); 

    //Creating the root element 
    final TreeItem<String> root = new TreeItem<>("Root node"); 
    root.setExpanded(true); 

    //Adding tree items to the root 
    root.getChildren().setAll(childNode1, childNode2, childNode3); 

    TreeView<String> tree = new TreeView<> (root);  

    // sort by length of the item's names   
    root.getChildren().sort(Comparator.comparing(t->t.getValue().length())); 

    sceneRoot.getChildren().add(tree); 
    stage.setScene(scene); 
    stage.show();   
} 
+2

Можете ли вы показать мне несколько примеров для TreeView? – user1285928

+0

Большое спасибо. – chris