2017-03-05 44 views
1

我正在嘗試對VBox內部擴展HBox的自定義類的列表進行排序。一切正在完美地完成,而忽略了類型聲明,但我想知道是否有辦法擺脫警告。使用自定義類和比較器時ObservableList的設置類型

public static class FilePane extends HBox {}  

public void sort() { 
    int order = orderBy.getSelectionModel().getSelectedIndex(); 
    Comparator<FilePane> comp = null; 
    if(order == 0) { 
     comp = Comparator.comparing(FilePane::getFileNameLower); 
    } else if(order == 1) { 
     comp = Comparator.comparingLong(FilePane::getFileDate); 
     comp = comp.reversed(); 
    } else if(order == 2) { 
     comp = Comparator.comparingLong(FilePane::getFileSize); 
     comp = comp.reversed(); 
    } else if(order == 3) { 
     comp = Comparator.comparingLong(FilePane::getFileCount); 
     comp = comp.reversed(); 
    } else if(order == 4) { 
     comp = Comparator.comparing(FilePane::getDirectory); 
     comp = comp.reversed(); 
    } 
    ObservableList list = fileList.getChildren(); 
    FXCollections.sort(list, comp); 
} 

嘗試設置listObservableList<FilePane>給出了一個錯誤,告訴我,因爲那是什麼getChildren()返回時,就應設置爲<Node>。將其設置爲<Node>不起作用,FXCollections.sort(list, comp);給出了一個錯誤FilePane不會起作用,因爲:

The method sort(ObservableList<T>, Comparator<? super T>) in the type FXCollections is not applicable for the arguments (ObservableList<Node>, Comparator<FilePane>) 

FilePane擴展HBox中應該考慮的一個節點?比較器的類型不能設置爲節點,因爲它需要與類進行比較。與ObservableList<FilePane> list = (ObservableList<FilePane>) fileList.getChildren();鑄造告訴我,它不能這樣做,所以它不是一個選項。

我應該忽略類型警告,因爲它沒有它們可以正常工作嗎?有沒有辦法將VBox的孩子設置爲ObservableList<FilePane>

回答

2

如果getChildren()返回的列表爲Node s,那麼您需要的列表是Node s的列表。我們從那裏開始並向後工作。

ObservableList<Node> list = fileList.getChildren(); 

好的。如果這是列表,那麼我們如何獲得sort()調用來編譯?答案是比較器必須是Comparator<Node>而不是Comparator<FilePane>

但這不好,對吧?因爲那樣我們就不能使用那些真正光滑的FilePane::方法引用。等一下,夥伴。沒那麼快。難道沒有辦法單獨保留這些代碼,並仍然使sort()高興嗎?

有。單獨留下comp。它可以保持爲Comparator<FilePane>。我們需要做的是將其轉換爲Comparator<Node>一些方法。

FXCollections.sort(list, convertSomeHow(comp)); 

我們如何轉換它?那麼,sort()將通過比較器Node s。我們的比較器想要FilePane s。所以我們需要做的是在那裏獲得一個陣容,然後推遲到comp。事情是這樣的:

FXCollections.sort(list, Comparator.comparing(node -> (FilePane) node, comp)); 

或者:

FXCollections.sort(list, Comparator.comparing(FilePane.class::cast, comp)); 
+0

謝謝!我使用lambda的第一個選擇,警告消失了。 –